@unson/brainbase-mcp 0.50.16 → 0.50.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ export interface JudgmentJournalTurnInput {
2
+ sessionId: string;
3
+ turnId: string;
4
+ projectCode: string;
5
+ trustedToken: string;
6
+ /** Identity verified by the Host JWT boundary, never client body fields. */
7
+ trustedPrincipal: {
8
+ personId: string;
9
+ tenantId: string;
10
+ };
11
+ }
12
+ export interface JudgmentJournalTurnPublisherOptions {
13
+ apiBaseUrl?: string;
14
+ journalRoot: string;
15
+ fetch?: typeof globalThis.fetch;
16
+ /** Receives only a fixed reason code, never exception details or journal data. */
17
+ onError?: (reason: string) => void;
18
+ }
19
+ /** HTTP-only, best-effort publication of the host's finished canonical journal. */
20
+ export declare function createJudgmentJournalTurnPublisher(options: JudgmentJournalTurnPublisherOptions): (input: JudgmentJournalTurnInput) => Promise<void>;
@@ -0,0 +1,112 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, readdir } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
5
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
6
+ /** HTTP-only, best-effort publication of the host's finished canonical journal. */
7
+ export function createJudgmentJournalTurnPublisher(options) {
8
+ const report = (reason) => {
9
+ try {
10
+ (options.onError ?? console.warn)(reason);
11
+ }
12
+ catch { /* Diagnostics must fail open too. */ }
13
+ };
14
+ return async (input) => {
15
+ if (!options.apiBaseUrl || !options.journalRoot) {
16
+ report('judgment_journal_not_configured');
17
+ return;
18
+ }
19
+ if (!input.trustedToken) {
20
+ report('judgment_journal_token_missing');
21
+ return;
22
+ }
23
+ let body;
24
+ try {
25
+ const sessionRef = hash(input.sessionId);
26
+ const prefix = join(options.journalRoot, sessionRef, hash(input.turnId));
27
+ const read = async (path, optional = false) => {
28
+ let text;
29
+ try {
30
+ text = await readFile(path, 'utf8');
31
+ }
32
+ catch (error) {
33
+ if (optional && error.code === 'ENOENT')
34
+ return undefined;
35
+ throw error;
36
+ }
37
+ const value = JSON.parse(text);
38
+ if (!object(value))
39
+ throw new Error('invalid');
40
+ return value;
41
+ };
42
+ const episode = (await read(`${prefix}.episode.json`));
43
+ // Check ownership when supplied; current hosts rely on the receiving API receipt-owner binding.
44
+ if (!input.trustedPrincipal?.personId?.trim() || !input.trustedPrincipal.tenantId?.trim()
45
+ || ('owner_person_id' in episode && episode.owner_person_id !== input.trustedPrincipal.personId)
46
+ || ('tenant_id' in episode && episode.tenant_id !== input.trustedPrincipal.tenantId))
47
+ throw new Error('invalid');
48
+ const final = (await read(`${prefix}.final.json`));
49
+ const receipt = episode.initial_route_receipt;
50
+ if (!object(receipt) || typeof receipt.resolution_id !== 'string' || !receipt.resolution_id
51
+ || receipt.project_code !== input.projectCode
52
+ || (receipt.turn_id !== undefined && receipt.turn_id !== input.turnId)
53
+ || (episode.turn_id !== undefined && episode.turn_id !== input.turnId)
54
+ || (episode.session_ref !== undefined && episode.session_ref !== sessionRef)
55
+ || (final.turn_id !== undefined && final.turn_id !== input.turnId)
56
+ || (final.session_ref !== undefined && final.session_ref !== sessionRef)
57
+ || typeof final.finalized_at !== 'string'
58
+ || !Number.isFinite(Date.parse(final.finalized_at)))
59
+ throw new Error('invalid');
60
+ let names;
61
+ try {
62
+ names = await readdir(`${prefix}.events`);
63
+ }
64
+ catch (error) {
65
+ if (error.code !== 'ENOENT')
66
+ throw error;
67
+ names = []; // Hosts need not create a directory for a zero-tool turn.
68
+ }
69
+ const rawEvents = await Promise.all(names.filter(name => name.endsWith('.json'))
70
+ .map(async (name) => (await read(join(`${prefix}.events`, name)))));
71
+ const sequence = (event) => typeof event.event_sequence === 'number' ? event.event_sequence : Number(event.sequence) - 1;
72
+ rawEvents.sort((a, b) => sequence(a) - sequence(b));
73
+ const events = rawEvents.map((event, index) => {
74
+ if (sequence(event) !== index || index >= 4096
75
+ || typeof event.event_fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(event.event_fingerprint)
76
+ || typeof event.tool_use_id !== 'string' || !event.tool_use_id.trim())
77
+ throw new Error('invalid');
78
+ return { event_sequence: index, event_fingerprint: event.event_fingerprint,
79
+ tool_use_id: event.tool_use_id, event };
80
+ });
81
+ if (final.event_count !== events.length)
82
+ throw new Error('invalid');
83
+ const turnInput = await read(`${prefix}.turn-input.json`, true);
84
+ const valueProof = await read(`${prefix}.value-proof.json`, true);
85
+ body = {
86
+ resolution_id: receipt.resolution_id, turn_id: input.turnId, project_code: input.projectCode,
87
+ turn_ref: `${sessionRef}/${hash(input.turnId)}`, entrypoint: 'claude_code',
88
+ receipt, episode, final, events,
89
+ ...(turnInput ? { turn_input: turnInput } : {}),
90
+ ...(valueProof ? { value_proof: valueProof } : {}), recorded_at: final.finalized_at,
91
+ };
92
+ }
93
+ catch (error) {
94
+ report(error.code === 'ENOENT'
95
+ ? 'judgment_journal_files_missing' : 'judgment_journal_files_invalid');
96
+ return;
97
+ }
98
+ try {
99
+ const response = await (options.fetch ?? globalThis.fetch)(`${options.apiBaseUrl.replace(/\/$/, '')}/api/organization/judgment-journal/turns`, {
100
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(1000),
101
+ headers: { Authorization: `Bearer ${input.trustedToken}`, 'Content-Type': 'application/json' },
102
+ body: JSON.stringify(body),
103
+ });
104
+ if (response.status !== 200 && response.status !== 201) {
105
+ report(response.status === 409 ? 'judgment_journal_conflict' : 'judgment_journal_http_failed');
106
+ }
107
+ }
108
+ catch {
109
+ report('judgment_journal_network_failed');
110
+ }
111
+ };
112
+ }
@@ -0,0 +1,82 @@
1
+ import type { JudgmentJournalTurnInput } from './judgment-journal-turn-publisher.js';
2
+ /** Minimal identity verified by the consuming host's authentication boundary. */
3
+ export interface RemoteJudgmentHookPrincipal {
4
+ personId: string;
5
+ organizationId: string;
6
+ tenantId?: string;
7
+ projectCodes: string[];
8
+ }
9
+ export declare const REMOTE_JUDGMENT_HOOK_PATH = "/host/judgment/hook";
10
+ export declare const REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES: number;
11
+ export interface RemoteJudgmentHookDispatchResult {
12
+ output: Record<string, unknown>;
13
+ receiptId?: string;
14
+ routeResolutionSha256?: string;
15
+ }
16
+ /**
17
+ * `remote`: a remote runtime. `claude-code`: Claude Code on
18
+ * the owner's loopback bridge or authenticated with a person's hosted JWT.
19
+ */
20
+ export type RemoteJudgmentHookHost = 'remote' | 'claude-code';
21
+ /**
22
+ * Authentication context verified by the Host before it reaches the hook
23
+ * dispatcher. A shared bearer intentionally has no trusted principal or
24
+ * auth kind and therefore is not represented here.
25
+ */
26
+ export type RemoteJudgmentHookAuthKind = 'brainbase-jwt' | 'company-authority';
27
+ /** Derive flags from verified authentication and the host's owner-loopback check. */
28
+ export declare function remoteJudgmentHookHostFlags(authKind: RemoteJudgmentHookAuthKind | 'shared-bearer', isOwnerLocalBridge: boolean): {
29
+ personHostedClaudeCodeAllowed: boolean;
30
+ localClaudeCodeAllowed: boolean;
31
+ };
32
+ export interface RemoteJudgmentHookDispatchOptions {
33
+ host: RemoteJudgmentHookHost;
34
+ /** Principal verified by the Host authentication boundary, when available. */
35
+ trustedPrincipal?: RemoteJudgmentHookPrincipal;
36
+ /** The verified caller token, kept inside the dispatch boundary for canonical readback. */
37
+ trustedToken?: string;
38
+ /** Authentication kind verified by the Host authentication boundary. */
39
+ trustedAuthKind?: RemoteJudgmentHookAuthKind;
40
+ /** Raw encoded Company Authority response verified by the canonical API. */
41
+ companyAuthorityResponse?: string;
42
+ }
43
+ export type RemoteJudgmentHookDispatch = (payload: Record<string, unknown>, projectCode: string | undefined, options: RemoteJudgmentHookDispatchOptions) => Promise<RemoteJudgmentHookDispatchResult>;
44
+ export interface RemoteJudgmentHookRequest {
45
+ method?: string;
46
+ url?: string;
47
+ authorization?: string;
48
+ body: Buffer;
49
+ bearerToken: string;
50
+ projectCode?: string;
51
+ /** Principal verified by the Host authentication boundary, never by request body fields. */
52
+ trustedPrincipal?: RemoteJudgmentHookPrincipal;
53
+ /** Verified caller token; never included in the response or diagnostic payload. */
54
+ trustedToken?: string;
55
+ /** Authentication kind verified by the Host authentication boundary. */
56
+ trustedAuthKind?: RemoteJudgmentHookAuthKind;
57
+ /** Raw encoded Company Authority response verified by the canonical API. */
58
+ companyAuthorityResponse?: string;
59
+ /** The x-brainbase-judgment-host header, when the caller declared one. */
60
+ declaredHost?: string;
61
+ /** True only on the owner's loopback bridge for a shared-bearer request. */
62
+ localClaudeCodeAllowed?: boolean;
63
+ /** True only for a person authenticated by the hosted MCP's JWT boundary. */
64
+ personHostedClaudeCodeAllowed?: boolean;
65
+ isAuthorized: (authorization: string | undefined, expectedToken: string) => boolean;
66
+ dispatch: RemoteJudgmentHookDispatch;
67
+ /** Optional HTTP publisher for person-authenticated hosted Claude Code Stop events. */
68
+ journalTurnPublisher?: (input: JudgmentJournalTurnInput) => Promise<void>;
69
+ onDispatchError?: (details: {
70
+ eventName: string;
71
+ reason: string;
72
+ errorName: string;
73
+ errorCode?: string;
74
+ causeReasonCode?: string;
75
+ }) => void;
76
+ }
77
+ export interface RemoteJudgmentHookResponse {
78
+ status: number;
79
+ headers?: Record<string, string>;
80
+ body: Record<string, unknown>;
81
+ }
82
+ export declare function handleRemoteJudgmentHookRequest(request: RemoteJudgmentHookRequest): Promise<RemoteJudgmentHookResponse | null>;
@@ -0,0 +1,207 @@
1
+ export const REMOTE_JUDGMENT_HOOK_PATH = '/host/judgment/hook';
2
+ export const REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES = 1024 * 1024;
3
+ /** Derive flags from verified authentication and the host's owner-loopback check. */
4
+ export function remoteJudgmentHookHostFlags(authKind, isOwnerLocalBridge) {
5
+ return {
6
+ personHostedClaudeCodeAllowed: authKind === 'brainbase-jwt',
7
+ localClaudeCodeAllowed: authKind === 'shared-bearer' && isOwnerLocalBridge === true,
8
+ };
9
+ }
10
+ const PROJECT_CODE_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
11
+ const SUPPORTED_HOOK_EVENTS = new Set(['UserPromptSubmit', 'PostToolUse', 'PostToolUseFailure', 'Stop']);
12
+ // The owner's Claude Code also sends a knowledge lookup's PreToolUse, so the
13
+ // Host can reserve the attempt it later records. A remote runtime keeps the
14
+ // events above.
15
+ const CLAUDE_CODE_HOOK_EVENTS = new Set([...SUPPORTED_HOOK_EVENTS, 'PreToolUse']);
16
+ const SAFE_REASON_CODE = /^[a-z][a-z0-9_]{1,80}$/;
17
+ const FORBIDDEN_SCOPE_REASON_CODES = new Set([
18
+ 'judgment_history_scope_mismatch',
19
+ 'judgment_history_project_denied',
20
+ 'judgment_history_shared_bearer_denied',
21
+ // Current scope binder wording; retain the explicit deny classification if
22
+ // the binder has not yet adopted the shorter reason code above.
23
+ 'judgment_history_scope_shared_bearer_rejected',
24
+ ]);
25
+ function isInternalJudgmentControlTool(payload) {
26
+ const toolName = payload.tool_name ?? payload.toolName;
27
+ return typeof toolName === 'string'
28
+ && ['mcp__brainbase__brainbase_judgment_state_record',
29
+ 'mcp__brainbase__brainbase_judgment_audit_read',
30
+ 'mcp__brainbase__brainbase_judgment_repair_read'].includes(toolName);
31
+ }
32
+ function safeCauseReasonCode(error) {
33
+ let current = typeof error === 'object' && error && 'cause' in error ? error.cause : undefined;
34
+ const visited = new Set();
35
+ for (let depth = 0; depth < 6 && current && !visited.has(current); depth += 1) {
36
+ visited.add(current);
37
+ if (current instanceof Error && SAFE_REASON_CODE.test(current.message))
38
+ return current.message;
39
+ current = typeof current === 'object' && 'cause' in current ? current.cause : undefined;
40
+ }
41
+ return undefined;
42
+ }
43
+ export async function handleRemoteJudgmentHookRequest(request) {
44
+ if (request.method !== 'POST' || request.url !== REMOTE_JUDGMENT_HOOK_PATH)
45
+ return null;
46
+ if (!request.isAuthorized(request.authorization, request.bearerToken)) {
47
+ return {
48
+ status: 401,
49
+ headers: { 'WWW-Authenticate': 'Bearer' },
50
+ body: { error: 'unauthorized' },
51
+ };
52
+ }
53
+ if (request.body.length > REMOTE_JUDGMENT_HOOK_MAX_BODY_BYTES) {
54
+ return { status: 413, body: { error: 'judgment_hook_payload_too_large' } };
55
+ }
56
+ let payload;
57
+ try {
58
+ payload = JSON.parse(request.body.toString('utf8'));
59
+ }
60
+ catch {
61
+ return { status: 400, body: { error: 'invalid_json' } };
62
+ }
63
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
64
+ return { status: 400, body: { error: 'invalid_hook_payload' } };
65
+ }
66
+ const hookPayload = payload;
67
+ const eventName = hookPayload.hook_event_name ?? hookPayload.hookEventName;
68
+ if (typeof eventName !== 'string' || !CLAUDE_CODE_HOOK_EVENTS.has(eventName)) {
69
+ return { status: 400, body: { error: 'unsupported_hook_event' } };
70
+ }
71
+ const personHostedClaudeCode = request.personHostedClaudeCodeAllowed === true
72
+ && request.trustedAuthKind === 'brainbase-jwt';
73
+ const host = request.declaredHost === undefined || request.declaredHost === ''
74
+ ? 'remote' : 'claude-code';
75
+ if (host === 'claude-code'
76
+ && (request.declaredHost !== 'claude-code' || (request.localClaudeCodeAllowed !== true && !personHostedClaudeCode))) {
77
+ return { status: 400, body: { error: 'judgment_hook_host_unsupported' } };
78
+ }
79
+ if (host === 'remote' && !SUPPORTED_HOOK_EVENTS.has(eventName)) {
80
+ return { status: 400, body: { error: 'unsupported_hook_event' } };
81
+ }
82
+ // A local Claude Code turn may leave the project to the Host, which derives
83
+ // it from the turn's cwd exactly as for Codex.
84
+ const requiresProjectScope = host === 'remote' || (host === 'claude-code' && personHostedClaudeCode);
85
+ if (host === 'claude-code' && personHostedClaudeCode
86
+ && !request.trustedPrincipal?.tenantId?.trim()) {
87
+ return { status: 403, body: { error: 'authenticated_history_principal_unavailable' } };
88
+ }
89
+ if ((requiresProjectScope || request.projectCode !== undefined)
90
+ && (!request.projectCode || !PROJECT_CODE_PATTERN.test(request.projectCode))) {
91
+ return { status: 400, body: { error: 'invalid_project_code' } };
92
+ }
93
+ if (requiresProjectScope && request.trustedPrincipal
94
+ && (!request.projectCode || !request.trustedPrincipal.projectCodes.includes(request.projectCode))) {
95
+ return { status: 403, body: { error: 'project_not_authorized' } };
96
+ }
97
+ if (request.trustedPrincipal && !request.trustedPrincipal.tenantId?.trim()) {
98
+ return { status: 403, body: { error: 'authenticated_history_principal_unavailable' } };
99
+ }
100
+ const sessionId = hookPayload.session_id;
101
+ const turnId = hookPayload.turn_id;
102
+ if (typeof sessionId !== 'string' || !sessionId || typeof turnId !== 'string' || !turnId) {
103
+ return { status: 400, body: { error: 'invalid_hook_identity' } };
104
+ }
105
+ try {
106
+ const dispatchOptions = request.trustedPrincipal
107
+ ? {
108
+ host,
109
+ trustedPrincipal: request.trustedPrincipal,
110
+ ...(request.trustedToken ? { trustedToken: request.trustedToken } : {}),
111
+ ...(request.trustedAuthKind ? { trustedAuthKind: request.trustedAuthKind } : {}),
112
+ ...(request.companyAuthorityResponse
113
+ ? { companyAuthorityResponse: request.companyAuthorityResponse }
114
+ : {}),
115
+ }
116
+ : { host };
117
+ const dispatchResult = await request.dispatch(hookPayload, request.projectCode, dispatchOptions);
118
+ const { output } = dispatchResult;
119
+ if (!output || typeof output !== 'object' || Array.isArray(output)) {
120
+ return { status: 503, body: { error: 'judgment_hook_output_invalid' } };
121
+ }
122
+ // The remote runtime's stream validator needs an audit line per tool. A
123
+ // local Claude Code turn has no such validator; the Host decides alone.
124
+ if (host === 'remote' && (eventName === 'PostToolUse' || eventName === 'PostToolUseFailure')
125
+ && !isInternalJudgmentControlTool(hookPayload)
126
+ && (typeof output.systemMessage !== 'string' || !output.systemMessage.trim())) {
127
+ return { status: 503, body: { error: 'judgment_hook_audit_not_recorded' } };
128
+ }
129
+ if (eventName === 'UserPromptSubmit'
130
+ && (typeof dispatchResult.receiptId !== 'string' || !dispatchResult.receiptId.trim()
131
+ || typeof dispatchResult.routeResolutionSha256 !== 'string'
132
+ || !/^[a-f0-9]{64}$/.test(dispatchResult.routeResolutionSha256))) {
133
+ return { status: 503, body: { error: 'judgment_hook_route_receipt_missing' } };
134
+ }
135
+ if (eventName === 'Stop' && host === 'claude-code' && personHostedClaudeCode
136
+ && request.localClaudeCodeAllowed !== true) {
137
+ const report = (reason) => {
138
+ try {
139
+ console.warn(reason);
140
+ }
141
+ catch { /* Logging cannot affect the hook response. */ }
142
+ };
143
+ if (!request.journalTurnPublisher)
144
+ report('judgment_journal_not_configured');
145
+ else if (!request.trustedToken)
146
+ report('judgment_journal_token_missing');
147
+ else {
148
+ let timer;
149
+ try {
150
+ await Promise.race([
151
+ Promise.resolve().then(() => request.journalTurnPublisher({
152
+ sessionId, turnId, projectCode: request.projectCode, trustedToken: request.trustedToken,
153
+ trustedPrincipal: { personId: request.trustedPrincipal.personId, tenantId: request.trustedPrincipal.tenantId },
154
+ })),
155
+ new Promise((_resolve, reject) => {
156
+ timer = setTimeout(() => reject(new Error()), 1500);
157
+ }),
158
+ ]);
159
+ }
160
+ catch {
161
+ report('judgment_journal_publish_failed');
162
+ }
163
+ finally {
164
+ if (timer)
165
+ clearTimeout(timer);
166
+ }
167
+ }
168
+ }
169
+ const hasRouteReceipt = typeof dispatchResult.receiptId === 'string'
170
+ && dispatchResult.receiptId.trim().length > 0
171
+ && typeof dispatchResult.routeResolutionSha256 === 'string'
172
+ && /^[a-f0-9]{64}$/.test(dispatchResult.routeResolutionSha256);
173
+ return {
174
+ status: 200,
175
+ body: {
176
+ schema_version: '1', accepted: true,
177
+ hook_event_name: eventName, session_id: sessionId, turn_id: turnId,
178
+ ...((eventName === 'UserPromptSubmit' || eventName === 'Stop') && hasRouteReceipt ? {
179
+ receipt_id: dispatchResult.receiptId,
180
+ route_resolution_sha256: dispatchResult.routeResolutionSha256,
181
+ } : {}),
182
+ output,
183
+ },
184
+ };
185
+ }
186
+ catch (error) {
187
+ const reason = error instanceof Error
188
+ && /^judgment_[a-z0-9_]{1,80}$/.test(error.message)
189
+ ? error.message
190
+ : 'judgment_hook_unavailable';
191
+ const errorCode = error && typeof error === 'object'
192
+ && 'code' in error && typeof error.code === 'string'
193
+ && /^[A-Z0-9_]{1,80}$/.test(error.code)
194
+ ? error.code
195
+ : undefined;
196
+ const causeReasonCode = safeCauseReasonCode(error);
197
+ request.onDispatchError?.({
198
+ eventName,
199
+ reason,
200
+ errorName: error instanceof Error ? error.name : 'UnknownError',
201
+ ...(errorCode ? { errorCode } : {}),
202
+ ...(causeReasonCode && causeReasonCode !== reason ? { causeReasonCode } : {}),
203
+ });
204
+ const status = FORBIDDEN_SCOPE_REASON_CODES.has(reason) ? 403 : 503;
205
+ return { status, body: { error: reason } };
206
+ }
207
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.50.16",
3
+ "version": "0.50.19",
4
4
  "description": "Local-first Brainbase judgment OS that lets supported AI agents reuse a user's approved goals, priorities, decisions, and judgment criteria.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,6 +43,14 @@
43
43
  "types": "./dist/judgment-history.d.ts",
44
44
  "import": "./dist/judgment-history.js"
45
45
  },
46
+ "./judgment-journal-turn-publisher": {
47
+ "types": "./dist/judgment-journal-turn-publisher.d.ts",
48
+ "import": "./dist/judgment-journal-turn-publisher.js"
49
+ },
50
+ "./remote-judgment-hook-http": {
51
+ "types": "./dist/remote-judgment-hook-http.d.ts",
52
+ "import": "./dist/remote-judgment-hook-http.js"
53
+ },
46
54
  "./judgment-history-http": {
47
55
  "types": "./dist/judgment-history-http.d.ts",
48
56
  "import": "./dist/judgment-history-http.js"
@@ -649,5 +657,5 @@
649
657
  "url": "https://github.com/Unson-LLC/brainbase/issues"
650
658
  },
651
659
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
652
- "gitHead": "0b52026e8133edbd1d811a3a34f77a740922f5ad"
660
+ "gitHead": "bf9c68fa85fbb56c74133fab383bd39248fdae92"
653
661
  }
@@ -201,6 +201,7 @@
201
201
  --bb-row-move-ease: cubic-bezier(.2,.8,.2,1);
202
202
  --bb-shadow-compact-dropdown: 0 0 0 1px rgb(27 36 51 / .08), 0 12px 28px rgb(27 36 51 / .18);
203
203
  --bb-shadow-control-panel: 0 0 0 1px rgb(27 36 51 / .08), 0 20px 44px -12px rgb(27 36 51 / .28);
204
+ --bb-shadow-compact-dialog: 0 0 0 1px rgb(27 36 51 / .08), 0 24px 60px -12px rgb(27 36 51 / .32);
204
205
  --bb-input-frame-width: 600px;
205
206
  --bb-control-panel-width: 372px;
206
207
  --bb-control-panel-duration: 160ms;
@@ -1201,3 +1201,79 @@
1201
1201
  .bb-ws-tabs--header .bb-ws-tab-count { font-feature-settings:normal; font-variant-numeric:normal; }
1202
1202
 
1203
1203
  .bb-ws-input-frame { font:13px/1.6 var(--bb-font-sans); }
1204
+
1205
+ /* Opt-in anchored surfaces; existing dialogs and filters keep their defaults. */
1206
+ .bb-ws-anchored-popover { position:fixed; z-index:70; box-sizing:border-box; width:var(--bb-anchored-width,276px); max-width:calc(100vw - 16px); max-height:calc(100dvh - 16px); overflow:auto; padding:14px 8px 8px; border:0; border-radius:14px; background:var(--bb-color-paper); color:var(--bb-color-ink); box-shadow:var(--bb-shadow-control-panel); font:inherit; text-align:left; transform-origin:50% 40px; animation:bb-ws-anchored-in 160ms cubic-bezier(.2,.8,.2,1); }
1207
+ .bb-ws-anchored-popover[hidden] { display:none; }
1208
+ .bb-ws-anchored-popover--muted { padding:0 0 16px; background:var(--bb-segmented-surface); }
1209
+ .bb-ws-anchored-popover:focus-visible { outline:2px solid var(--bb-color-focus); outline-offset:2px; }
1210
+ @keyframes bb-ws-anchored-in { from { transform:scale(.94); opacity:0; } to { transform:none; opacity:1; } }
1211
+
1212
+ .bb-ws-dialog.bb-ws-dialog--compact { width:min(440px,calc(100vw - 32px)); padding:20px 20px 18px; border:0; border-radius:16px; background:var(--bb-color-paper); box-shadow:var(--bb-shadow-compact-dialog); animation:bb-ws-compact-dialog-in 200ms cubic-bezier(.2,.8,.2,1); }
1213
+ .bb-ws-dialog--compact::backdrop { background:color-mix(in srgb,var(--bb-color-ink) 18%,transparent); }
1214
+ .bb-ws-dialog--compact .bb-ws-dialog-head { align-items:center; gap:0; margin-bottom:4px; padding:0; border:0; }
1215
+ .bb-ws-dialog--compact .bb-ws-dialog-head h2 { flex:1; font-size:16px; font-weight:600; line-height:1.6; }
1216
+ .bb-ws-dialog--compact .bb-ws-dialog-head > .bb-ws-button { display:grid; place-items:center; width:28px; min-height:28px; height:28px; margin-right:-6px; padding:0; border:0; border-radius:6px; background:transparent; color:var(--bb-color-muted); font-size:20px; }
1217
+ .bb-ws-dialog--compact .bb-ws-dialog-head > .bb-ws-button:hover { background:var(--bb-color-canvas); color:var(--bb-color-ink); }
1218
+ .bb-ws-dialog--compact .bb-ws-dialog-body { padding:0; }
1219
+ .bb-ws-dialog-tools { display:flex; align-items:center; }
1220
+ .bb-ws-help--bottom-end .bb-ws-help-button { width:28px; height:28px; border:0; border-radius:6px; background:transparent; color:var(--bb-color-muted); font:600 16px var(--bb-font-sans); }
1221
+ .bb-ws-help--bottom-end .bb-ws-help-button:hover { background:var(--bb-color-canvas); }
1222
+ .bb-ws-help--bottom-end .bb-ws-help-bubble { top:34px; bottom:auto; left:auto; right:-28px; width:min(300px,calc(100vw - 48px)); padding:12px 14px; border:0; border-radius:12px; background:var(--bb-color-paper); box-shadow:var(--bb-shadow-control-panel); font-size:13px; transform:translateY(-4px); }
1223
+ .bb-ws-help--bottom-end:not(.is-dismissed):is(:hover,:focus-within,.is-open) .bb-ws-help-bubble { transform:none; }
1224
+ .bb-ws-help--bottom-end .bb-ws-help-bubble::after { top:-10px; }
1225
+
1226
+ /* Stable boxed trigger: hover and expanded change only the surface. */
1227
+ .bb-ws-combobox--compact.bb-ws-combobox--stable-box .bb-ws-combobox-trigger { border:0; border-radius:7px; background:var(--bb-color-paper); box-shadow:inset 0 0 0 1px var(--bb-color-border); }
1228
+ .bb-ws-combobox--compact.bb-ws-combobox--stable-box .bb-ws-combobox-trigger:is(:hover,[aria-expanded="true"]) { background:var(--bb-color-canvas); box-shadow:inset 0 0 0 1px var(--bb-color-border); color:var(--bb-color-ink); }
1229
+ .bb-ws-combobox--compact.bb-ws-combobox--stable-box.is-active .bb-ws-combobox-trigger { background:var(--bb-color-accent-soft); box-shadow:none; color:var(--bb-color-action); font-weight:600; }
1230
+ .bb-ws-combobox--compact.bb-ws-combobox--stable-box .bb-ws-combobox-trigger:focus-visible { outline:2px solid var(--bb-color-focus); outline-offset:2px; }
1231
+ .bb-ws-combobox--compact.bb-ws-combobox--tall .bb-ws-combobox-trigger { height:32px; min-height:32px; padding:0 10px; }
1232
+ .bb-ws-combobox--compact .bb-ws-combobox-popup { width:var(--bb-combobox-popup-width,max-content); }
1233
+ .bb-ws-combobox--compact.bb-ws-combobox--match-width .bb-ws-combobox-popup { box-sizing:border-box; width:100%; min-width:0; }
1234
+ .bb-ws-combobox--match-width .bb-ws-combobox-option { padding-inline:6px; gap:5px; }
1235
+
1236
+ .bb-ws-selection-row { --bb-selection-color:var(--bb-color-action); display:flex; align-items:center; gap:8px; width:100%; min-height:34px; border-radius:8px; }
1237
+ .bb-ws-selection-row:not(.is-disabled):hover { background:var(--bb-color-canvas); }
1238
+ .bb-ws-selection-row .bb-ws-selection-control { display:flex; flex:1; align-items:center; justify-content:flex-start; gap:10px; width:auto; min-width:0; height:34px; min-height:34px; padding:0 10px; border:0; border-radius:8px; background:transparent; color:var(--bb-color-ink); box-shadow:none; font:400 13px/1.6 var(--bb-font-sans); text-align:left; }
1239
+ .bb-ws-selection-row .bb-ws-selection-control:not(:disabled):hover { background:transparent; border:0; box-shadow:none; }
1240
+ .bb-ws-selection-check { display:grid; place-items:center; flex:none; width:16px; height:16px; border-radius:4px; box-shadow:inset 0 0 0 1.5px var(--bb-selection-color); color:transparent; transition:background 120ms; }
1241
+ .bb-ws-selection-check .bb-ws-action-icon { width:11px; height:11px; stroke-width:3; }
1242
+ .bb-ws-selection-control[aria-checked="true"] .bb-ws-selection-check { background:var(--bb-selection-color); color:var(--bb-color-action-text); }
1243
+ .bb-ws-selection-label { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
1244
+ .bb-ws-selection-trailing { display:inline-flex; align-items:center; flex:none; gap:8px; padding-right:10px; font-size:11px; color:var(--bb-color-muted); }
1245
+ .bb-ws-selection-row.is-disabled .bb-ws-selection-control { color:var(--bb-color-placeholder); opacity:1; cursor:default; }
1246
+ .bb-ws-selection-row.is-disabled .bb-ws-selection-check { box-shadow:inset 0 0 0 1.5px var(--bb-color-border); }
1247
+ .bb-ws-selection-control:focus-visible { outline:2px solid var(--bb-color-focus); outline-offset:2px; }
1248
+ .bb-ws-switch.bb-ws-button { display:flex; align-items:center; justify-content:flex-start; gap:10px; width:100%; min-height:18px; padding:0; border:0; border-radius:0; background:transparent; color:var(--bb-color-ink); box-shadow:none; font:400 13px/1.6 var(--bb-font-sans); text-align:left; }
1249
+ .bb-ws-switch.bb-ws-button:not(:disabled):hover { background:transparent; border:0; box-shadow:none; }
1250
+ .bb-ws-switch-track { position:relative; flex:none; width:30px; height:18px; border-radius:var(--bb-radius-pill); background:var(--bb-color-placeholder); transition:background 160ms; }
1251
+ .bb-ws-switch-track::after { content:''; position:absolute; top:2px; left:2px; width:14px; height:14px; border-radius:50%; background:var(--bb-color-paper); transition:transform 160ms cubic-bezier(.3,1.4,.5,1); }
1252
+ .bb-ws-switch[aria-checked="true"] .bb-ws-switch-track { background:var(--bb-color-action); }
1253
+ .bb-ws-switch[aria-checked="true"] .bb-ws-switch-track::after { transform:translateX(12px); }
1254
+ .bb-ws-switch.bb-ws-button:focus-visible { outline:2px solid var(--bb-color-focus); outline-offset:3px; }
1255
+ @media(prefers-reduced-motion:reduce) {
1256
+ .bb-ws-anchored-popover { animation:none; }
1257
+ .bb-ws-selection-check, .bb-ws-switch-track, .bb-ws-switch-track::after { transition:none; }
1258
+ }
1259
+ .bb-ws-help--bottom-end .bb-ws-help-bubble > dl { display:grid; grid-template-columns:max-content minmax(0,1fr); gap:8px 12px; margin:0; }
1260
+ .bb-ws-help--bottom-end .bb-ws-help-bubble dt { color:var(--bb-color-ink); font-weight:600; white-space:nowrap; }
1261
+ .bb-ws-help--bottom-end .bb-ws-help-bubble dd { margin:0; color:var(--bb-color-slate); }
1262
+
1263
+ @keyframes bb-ws-compact-dialog-in { from { opacity:0; transform:translateY(8px) scale(.98); } to { opacity:1; transform:none; } }
1264
+ @media(prefers-reduced-motion:reduce) { .bb-ws-dialog.bb-ws-dialog--compact { animation:none; } }
1265
+
1266
+ /* Explicit small widths opt out of the legacy 150px minimum. Match-width still wins. */
1267
+ .bb-ws-combobox--compact.bb-ws-combobox--fixed-width .bb-ws-combobox-popup { box-sizing:border-box; min-width:0; }
1268
+ .bb-ws-dialog--compact .bb-ws-actions > .bb-ws-button { min-height:34px; height:34px; padding:0 14px; border-radius:7px; font-size:13px; }
1269
+
1270
+ .bb-ws-anchored-popover--flush { padding:0; }
1271
+
1272
+ /* Explicit icon control keeps the same square and inset edge inside a topbar. */
1273
+ .bb-ws-button.is-icon,
1274
+ .bb-ws-topbar.has-tabs .bb-ws-topbar-tools > .bb-ws-button.is-icon { display:grid; place-items:center; flex:none; box-sizing:border-box; width:32px; min-width:32px; height:32px; min-height:32px; padding:0; gap:0; border:0; border-radius:7px; background:var(--bb-color-paper); box-shadow:inset 0 0 0 1px var(--bb-color-border); color:var(--bb-color-slate); font:inherit; }
1275
+ .bb-ws-button.is-icon:not(:disabled):is(:hover,[aria-expanded="true"]),
1276
+ .bb-ws-topbar.has-tabs .bb-ws-topbar-tools > .bb-ws-button.is-icon:not(:disabled):is(:hover,[aria-expanded="true"]) { background:var(--bb-color-canvas); color:var(--bb-color-ink); border:0; box-shadow:inset 0 0 0 1px var(--bb-color-border); }
1277
+ .bb-ws-button.is-icon .bb-ws-action-icon,
1278
+ .bb-ws-topbar.has-tabs .bb-ws-topbar-tools > .bb-ws-button.is-icon .bb-ws-action-icon { width:16px; height:16px; }
1279
+ .bb-ws-button.is-icon:focus-visible { outline:2px solid var(--bb-color-focus); outline-offset:2px; }
@@ -217,7 +217,7 @@ export function workspaceHostActions(actions) {
217
217
 
218
218
  export function workspaceButton(doc, { text, variant = 'default', onClick, disabled = false, attrs = {} } = {}) {
219
219
  const button = el(doc, 'button', {
220
- className: `bb-ws-button${variant === 'primary' ? ' is-primary' : variant === 'danger' ? ' is-danger' : variant === 'quiet' ? ' is-quiet' : ''}`,
220
+ className: `bb-ws-button${variant === 'primary' ? ' is-primary' : variant === 'danger' ? ' is-danger' : variant === 'quiet' ? ' is-quiet' : variant === 'icon' ? ' is-icon' : ''}`,
221
221
  text,
222
222
  attrs: { type: 'button', disabled, ...attrs },
223
223
  });
@@ -361,12 +361,16 @@ function nextWorkspaceSequence() {
361
361
  const next = ++workspaceSequence;
362
362
  return workspaceIdScope ? `${encodeURIComponent(workspaceIdScope)}-${next}` : next;
363
363
  }
364
+ const workspaceHelpDismissers = new WeakMap();
365
+
364
366
  /** Shared explanatory help: hover/focus above the control, click for touch. */
365
- export function workspaceHelp(doc, { text, label } = {}) {
366
- const wrap = el(doc, 'span', { className: 'bb-ws-help' });
367
- const control = workspaceButton(doc, { text: 'i', attrs: { 'aria-label': `${label}の説明`, 'aria-expanded': 'false' } });
367
+ export function workspaceHelp(doc, { text, label, content, icon = 'i', placement } = {}) {
368
+ const wrap = el(doc, content === undefined ? 'span' : 'div', { className: 'bb-ws-help' });
369
+ const control = workspaceButton(doc, { text: icon, attrs: { 'aria-label': `${label}の説明`, 'aria-expanded': 'false' } });
368
370
  control.className = 'bb-ws-help-button';
369
- const bubble = el(doc, 'span', { className: 'bb-ws-help-bubble', text, attrs: { id: `bb-ws-help-${nextWorkspaceSequence()}`, role: 'tooltip' } });
371
+ const bubble = el(doc, content === undefined ? 'span' : 'div', { className: 'bb-ws-help-bubble', text, attrs: { id: `bb-ws-help-${nextWorkspaceSequence()}`, role: 'tooltip' } });
372
+ if (content !== undefined) { bubble.textContent = ''; appendContent(bubble, doc, content); }
373
+ if (placement === 'bottom-end') toggleWorkspaceClass(wrap, 'bb-ws-help--bottom-end', true);
370
374
  control.setAttribute('aria-describedby', bubble.id || bubble.getAttribute?.('id') || bubble.attributes?.id);
371
375
  control.addEventListener('click', event => {
372
376
  event.stopPropagation(); event.preventDefault();
@@ -374,13 +378,26 @@ export function workspaceHelp(doc, { text, label } = {}) {
374
378
  wrap.classList.remove('is-dismissed');
375
379
  control.setAttribute('aria-expanded', String(opened));
376
380
  });
377
- wrap.addEventListener('mouseleave', () => wrap.classList.remove('is-dismissed'));
378
- control.addEventListener('blur', () => { wrap.classList.remove('is-open', 'is-dismissed'); control.setAttribute('aria-expanded', 'false'); });
379
- control.addEventListener('keydown', event => {
380
- if (event.key !== 'Escape') return;
381
- wrap.classList.remove('is-open'); wrap.classList.add('is-dismissed');
382
- control.setAttribute('aria-expanded', 'false'); event.stopPropagation();
381
+ let hovered = false;
382
+ wrap.addEventListener('mouseenter', () => { hovered = true; });
383
+ wrap.addEventListener('mouseleave', () => {
384
+ hovered = false;
385
+ if (!wrap.contains?.(doc.activeElement)) wrap.classList.remove('is-dismissed');
383
386
  });
387
+ wrap.addEventListener('focusout', event => {
388
+ if (wrap.contains?.(event.relatedTarget)) return;
389
+ wrap.classList.remove('is-open'); control.setAttribute('aria-expanded', 'false');
390
+ if (!hovered) wrap.classList.remove('is-dismissed');
391
+ });
392
+ const dismissExplanation = event => {
393
+ if (event.key !== 'Escape' || event.defaultPrevented || wrap.classList.contains('is-dismissed')) return false;
394
+ if (!wrap.classList.contains('is-open') && !hovered && !wrap.contains?.(doc.activeElement)) return false;
395
+ event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation?.();
396
+ wrap.classList.remove('is-open'); wrap.classList.add('is-dismissed');
397
+ control.setAttribute('aria-expanded', 'false'); return true;
398
+ };
399
+ workspaceHelpDismissers.set(wrap, dismissExplanation);
400
+ control.addEventListener('keydown', dismissExplanation);
384
401
  wrap.append(control, bubble); return wrap;
385
402
  }
386
403
 
@@ -430,17 +447,26 @@ export function workspaceCloseDrawer(dialog, finish) {
430
447
  }
431
448
 
432
449
  /** Native modal, optionally a right drawer. close() animates; dispose() tears down immediately. */
433
- export function workspaceDialog(doc, { title, content, opener, presentation = 'center', onClose } = {}) {
450
+ export function workspaceDialog(doc, { title, content, opener, presentation = 'center', onClose, appearance, headerTools } = {}) {
434
451
  const dialog = el(doc, 'dialog', { className: 'bb-ws-dialog' });
452
+ if (appearance === 'compact') toggleWorkspaceClass(dialog, 'bb-ws-dialog--compact', true);
435
453
  if (presentation === 'drawer') workspaceApplyDrawer(dialog);
436
454
  const headingId = `bb-ws-dialog-${nextWorkspaceSequence()}`;
437
455
  dialog.setAttribute('aria-labelledby', headingId);
438
456
  const head = el(doc, 'header', { className: 'bb-ws-dialog-head' });
439
457
  const nativeClose = dialog.close.bind(dialog);
440
458
  let disposed = false;
459
+ const dismissVisibleHelp = event => {
460
+ if (event.key !== 'Escape' || event.defaultPrevented) return;
461
+ for (const help of dialog.querySelectorAll?.('.bb-ws-help') ?? []) {
462
+ if (workspaceHelpDismissers.get(help)?.(event)) return;
463
+ }
464
+ };
465
+ dialog.addEventListener('keydown', dismissVisibleHelp, true);
441
466
  const cleanup = () => {
442
467
  if (disposed) return;
443
468
  disposed = true;
469
+ dialog.removeEventListener('keydown', dismissVisibleHelp, true);
444
470
  drawerClosings.get(dialog)?.();
445
471
  dialog.remove();
446
472
  try { onClose?.(); } finally {
@@ -460,7 +486,11 @@ export function workspaceDialog(doc, { title, content, opener, presentation = 'c
460
486
  nativeClose(); cleanup();
461
487
  };
462
488
  const close = workspaceButton(doc, { text: '×', attrs: { 'aria-label': '閉じる' }, onClick: () => dialog.close() });
463
- head.append(el(doc, 'h2', { text: title, attrs: { id: headingId } }), close);
489
+ head.append(el(doc, 'h2', { text: title, attrs: { id: headingId } }));
490
+ if (headerTools) {
491
+ const tools = el(doc, 'div', { className: 'bb-ws-dialog-tools' }); appendContent(tools, doc, headerTools); head.append(tools);
492
+ }
493
+ head.append(close);
464
494
  const body = el(doc, 'div', { className: 'bb-ws-dialog-body' }); appendContent(body, doc, content);
465
495
  dialog.append(head, body); doc.body.append(dialog);
466
496
  dialog.addEventListener('cancel', event => { event.preventDefault(); dialog.close(); });
@@ -477,6 +507,145 @@ export function workspaceFilterChip(doc, { label, onRemove, attrs = {} } = {}) {
477
507
  return chip;
478
508
  }
479
509
 
510
+ const anchoredPopoverBindings = new WeakMap();
511
+
512
+ /** Non-modal anchored surface. Content and visibility have independent lifecycles. */
513
+ export function workspaceAnchoredPopover(doc, {
514
+ anchor, positionAnchor = anchor, content, label, surface = 'default', width = 276, placement = 'bottom', align = 'start', padding, onClose,
515
+ } = {}) {
516
+ if (!anchor || typeof anchor.getBoundingClientRect !== 'function') throw new TypeError('popover_anchor_required');
517
+ if (!positionAnchor || typeof positionAnchor.getBoundingClientRect !== 'function') throw new TypeError('popover_position_anchor_required');
518
+ const element = el(doc, 'div', { className: `bb-ws-anchored-popover${surface === 'muted' ? ' bb-ws-anchored-popover--muted' : ''}`, attrs: {
519
+ role: 'dialog', 'aria-label': label || '詳細', tabindex: '-1', id: `bb-ws-popover-${nextWorkspaceSequence()}`,
520
+ } });
521
+ if (padding === 'none') toggleWorkspaceClass(element, 'bb-ws-anchored-popover--flush', true);
522
+ const binding = anchoredPopoverBindings.get(anchor) || { original: new Map(['aria-controls', 'aria-expanded', 'aria-haspopup'].map(name => [name, anchor.getAttribute?.(name)])) };
523
+ const displaced = binding.owner;
524
+ const owner = {};
525
+ binding.owner = owner; anchoredPopoverBindings.set(anchor, binding);
526
+ displaced?.revoke?.();
527
+ const ownsAnchor = () => anchoredPopoverBindings.get(anchor)?.owner === owner;
528
+ const panelId = element.getAttribute('id');
529
+ anchor.setAttribute('aria-controls', panelId); anchor.setAttribute('aria-haspopup', 'dialog'); anchor.setAttribute('aria-expanded', 'false');
530
+ if (Number.isFinite(width) && width > 0) element.style?.setProperty('--bb-anchored-width', `${width}px`);
531
+ let opened = false;
532
+ let destroyed = false;
533
+ let modalHost;
534
+ const view = doc.defaultView;
535
+ const setContent = next => {
536
+ if (destroyed) return;
537
+ element.replaceChildren(); appendContent(element, doc, next);
538
+ if (opened) reposition();
539
+ };
540
+ const reposition = () => {
541
+ if (!opened || destroyed) return;
542
+ if (anchor.isConnected === false || positionAnchor.isConnected === false) { close({ restoreFocus: false }); return; }
543
+ const at = positionAnchor.getBoundingClientRect();
544
+ const box = element.getBoundingClientRect();
545
+ const viewportWidth = view?.innerWidth || doc.documentElement?.clientWidth || 1024;
546
+ const viewportHeight = view?.innerHeight || doc.documentElement?.clientHeight || 768;
547
+ // offset dimensions are layout sizes, unaffected by the entrance transform.
548
+ const panelWidth = element.offsetWidth || box.width || box.right - box.left;
549
+ const panelHeight = element.offsetHeight || box.height || box.bottom - box.top;
550
+ const x = align === 'end' ? at.right - panelWidth : align === 'center' ? at.left + ((at.width ?? at.right - at.left) - panelWidth) / 2 : at.left;
551
+ const y = placement === 'overlap' ? at.top - 10 : at.bottom + 4;
552
+ element.style?.setProperty('left', `${Math.max(8, Math.min(x, viewportWidth - panelWidth - 8))}px`);
553
+ element.style?.setProperty('top', `${Math.max(8, Math.min(y, viewportHeight - panelHeight - 8))}px`);
554
+ };
555
+ const removeListeners = () => {
556
+ doc.removeEventListener?.('pointerdown', outside); doc.removeEventListener?.('keydown', escape);
557
+ doc.removeEventListener?.('scroll', reposition, true); view?.removeEventListener?.('resize', reposition);
558
+ modalHost?.removeEventListener?.('close', modalClosed); modalHost = undefined;
559
+ };
560
+ const close = ({ restoreFocus = true } = {}) => {
561
+ if (!opened) return;
562
+ opened = false; removeListeners(); element.hidden = true; element.inert = true;
563
+ element.setAttribute('aria-hidden', 'true');
564
+ if (ownsAnchor()) anchor.setAttribute('aria-expanded', 'false');
565
+ if (restoreFocus && anchor.isConnected) anchor.focus?.({ preventScroll: true });
566
+ onClose?.();
567
+ };
568
+ const modalClosed = () => close({ restoreFocus: false });
569
+ const outside = event => {
570
+ if (!element.contains?.(event.target) && !anchor.contains?.(event.target)) close({ restoreFocus: false });
571
+ };
572
+ const escape = event => {
573
+ if (event.key !== 'Escape' || event.defaultPrevented) return;
574
+ event.preventDefault(); event.stopPropagation(); close();
575
+ };
576
+ const open = ({ focus = true } = {}) => {
577
+ if (destroyed || opened || !ownsAnchor() || anchor.isConnected === false || positionAnchor.isConnected === false || anchor.disabled || anchor.getAttribute?.('aria-disabled') === 'true') return;
578
+ // A surface opened inside a native modal must remain inside that top layer.
579
+ const modal = anchor.closest?.('dialog[open]');
580
+ (modal || doc.body).append(element); modalHost = modal;
581
+ modalHost?.addEventListener?.('close', modalClosed);
582
+ opened = true; element.hidden = false; element.inert = false; element.removeAttribute('aria-hidden');
583
+ anchor.setAttribute('aria-expanded', 'true'); reposition();
584
+ if (!opened) return;
585
+ doc.addEventListener?.('pointerdown', outside); doc.addEventListener?.('keydown', escape);
586
+ doc.addEventListener?.('scroll', reposition, true); view?.addEventListener?.('resize', reposition);
587
+ if (focus) (element.querySelector?.('button:not(:disabled),input:not(:disabled),select:not(:disabled),[tabindex="0"]') || element).focus?.({ preventScroll: true });
588
+ };
589
+ owner.revoke = () => close({ restoreFocus: false });
590
+ element.hidden = true; element.inert = true; element.setAttribute('aria-hidden', 'true');
591
+ setContent(content);
592
+ return { element, setContent, open, close, reposition, get isOpen() { return opened; }, destroy() {
593
+ if (destroyed) return;
594
+ destroyed = true; close({ restoreFocus: false }); removeListeners(); element.remove();
595
+ // Do not overwrite a newer surface bound to the same trigger.
596
+ if (ownsAnchor()) {
597
+ anchoredPopoverBindings.delete(anchor);
598
+ for (const [name, value] of binding.original) {
599
+ if (value === null || value === undefined) anchor.removeAttribute?.(name); else anchor.setAttribute(name, value);
600
+ }
601
+ }
602
+ } };
603
+ }
604
+
605
+ /** A checkable row with sibling status/actions, so retry buttons never nest in buttons. */
606
+ export function workspaceSelectionRow(doc, { label, checked = false, disabled = false, leading, trailing, color, onChange } = {}) {
607
+ const root = el(doc, 'div', { className: 'bb-ws-selection-row' });
608
+ const control = workspaceButton(doc, { attrs: { role: 'checkbox', 'aria-label': label } });
609
+ control.className += ' bb-ws-selection-control';
610
+ const check = el(doc, 'span', { className: 'bb-ws-selection-check', attrs: { 'aria-hidden': 'true' } });
611
+ check.append(workspaceActionIcon(doc, 'check')); control.append(check);
612
+ if (leading) appendContent(control, doc, leading);
613
+ control.append(el(doc, 'span', { className: 'bb-ws-selection-label', text: label }));
614
+ root.append(control);
615
+ if (trailing) {
616
+ const slot = el(doc, 'span', { className: 'bb-ws-selection-trailing' }); appendContent(slot, doc, trailing); root.append(slot);
617
+ }
618
+ if (color) root.style?.setProperty('--bb-selection-color', color);
619
+ let selected = Boolean(checked), unavailable = Boolean(disabled), destroyed = false;
620
+ const update = ({ checked: nextChecked, disabled: nextDisabled } = {}) => {
621
+ if (destroyed) return;
622
+ if (nextChecked !== undefined) selected = Boolean(nextChecked);
623
+ if (nextDisabled !== undefined) unavailable = Boolean(nextDisabled);
624
+ control.setAttribute('aria-checked', String(selected)); control.disabled = unavailable;
625
+ toggleWorkspaceClass(root, 'is-disabled', unavailable);
626
+ };
627
+ const click = () => { if (!destroyed && !unavailable) { update({ checked: !selected }); onChange?.(selected); } };
628
+ control.addEventListener('click', click); update();
629
+ return { root, control, update, destroy() { destroyed = true; control.removeEventListener?.('click', click); } };
630
+ }
631
+
632
+ /** Native button keyboard activation with controlled switch state. */
633
+ export function workspaceSwitch(doc, { label, checked = false, disabled = false, onChange } = {}) {
634
+ const control = workspaceButton(doc, { attrs: { role: 'switch', 'aria-label': label } });
635
+ control.className += ' bb-ws-switch';
636
+ control.append(el(doc, 'span', { className: 'bb-ws-switch-track', attrs: { 'aria-hidden': 'true' } }), el(doc, 'span', { text: label }));
637
+ let selected = Boolean(checked), unavailable = Boolean(disabled), destroyed = false;
638
+ const update = ({ checked: nextChecked, disabled: nextDisabled } = {}) => {
639
+ if (destroyed) return;
640
+ if (nextChecked !== undefined) selected = Boolean(nextChecked);
641
+ if (nextDisabled !== undefined) unavailable = Boolean(nextDisabled);
642
+ control.setAttribute('aria-checked', String(selected)); control.disabled = unavailable;
643
+ };
644
+ const click = () => { if (!destroyed && !unavailable) { update({ checked: !selected }); onChange?.(selected); } };
645
+ control.addEventListener('click', click); update();
646
+ return { root: control, control, update, destroy() { destroyed = true; control.removeEventListener?.('click', click); } };
647
+ }
648
+
480
649
  /** One filter choice; callers retain selection and lifecycle ownership. */
481
650
  export function workspaceFilterOption(doc, { label, count, checked = false, disabled = false, role = 'radio', attrs = {}, onClick } = {}) {
482
651
  const button = workspaceButton(doc, { attrs: { ...attrs, role, 'aria-checked': String(checked) }, disabled, onClick });
@@ -654,12 +823,20 @@ function comboboxText(value) {
654
823
  export function workspaceCombobox(doc, {
655
824
  label, options = [], value = '', placeholder = '選択してください', searchLabel, searchPlaceholder = '絞り込む',
656
825
  emptyText = '一致する候補はありません', limit = 100, searchable = 'auto', className, onChange,
657
- multiple = false, values = [], selectionLabel = '', renderIcon, showCount = true, showHints = true, align = 'start', appearance,
826
+ multiple = false, values = [], selectionLabel = '', renderIcon, showCount = true, showHints = true, align = 'start', appearance, boxed = false, matchTriggerWidth = false, triggerHeight, popupWidth, active = false,
658
827
  } = {}) {
659
828
  const sequence = nextWorkspaceSequence();
660
829
  const listId = `bb-ws-combobox-${sequence}-list`;
661
830
  const root = el(doc, 'span', { className: ['bb-ws-combobox', className].filter(Boolean).join(' ') });
662
831
  if (appearance === 'compact') toggleWorkspaceClass(root, 'bb-ws-combobox--compact', true);
832
+ if (boxed) { toggleWorkspaceClass(root, 'is-boxed', true); toggleWorkspaceClass(root, 'bb-ws-combobox--stable-box', true); }
833
+ if (active) toggleWorkspaceClass(root, 'is-active', true);
834
+ if (matchTriggerWidth) toggleWorkspaceClass(root, 'bb-ws-combobox--match-width', true);
835
+ if (triggerHeight === 32) toggleWorkspaceClass(root, 'bb-ws-combobox--tall', true);
836
+ if (Number.isFinite(popupWidth) && popupWidth > 0) {
837
+ toggleWorkspaceClass(root, 'bb-ws-combobox--fixed-width', true);
838
+ root.style?.setProperty('--bb-combobox-popup-width', `${popupWidth}px`);
839
+ }
663
840
  if (multiple) root.classList?.add('bb-ws-combobox-multiple');
664
841
  if (align === 'end') root.classList?.add('bb-ws-combobox-align-end');
665
842
  const trigger = el(doc, 'button', { className: 'bb-ws-combobox-trigger', attrs: { type: 'button', 'aria-haspopup': 'listbox', 'aria-expanded': 'false', 'aria-controls': listId } });
@@ -836,7 +1013,8 @@ export function workspaceCombobox(doc, {
836
1013
  get values() { return [...state.values]; },
837
1014
  get isOpen() { return state.open; },
838
1015
  open, close,
839
- update({ options: nextOptions, value: nextValue, values: nextValues, selectionLabel: nextSelectionLabel, disabled } = {}) {
1016
+ update({ options: nextOptions, value: nextValue, values: nextValues, selectionLabel: nextSelectionLabel, disabled, active: nextActive } = {}) {
1017
+ if (nextActive !== undefined) toggleWorkspaceClass(root, 'is-active', Boolean(nextActive));
840
1018
  const previous = JSON.stringify([state.options, state.value, state.values, state.selectionLabel, state.disabled]);
841
1019
  if (nextOptions !== undefined) setOptions(nextOptions);
842
1020
  if (nextSelectionLabel !== undefined) state.selectionLabel = String(nextSelectionLabel ?? '');
@@ -857,6 +1035,13 @@ export function workspaceActionIcon(doc, name) {
857
1035
  for (const [key, value] of Object.entries({ class: 'bb-ws-action-icon', viewBox: '0 0 24 24', 'aria-hidden': 'true' })) svg.setAttribute(key, value);
858
1036
  const path = typeof doc.createElementNS === 'function' ? doc.createElementNS('http://www.w3.org/2000/svg', 'path') : doc.createElement('path');
859
1037
  const paths = { edit: 'M4 20h4L19 9l-4-4L4 16z M13.5 6.5l4 4', undo: 'M4 5v5h5 M4.6 10A8 8 0 1 1 6.3 17.7', check: 'M5 12l5 5 9-10', sliders: 'M4 8h8M18 8h2M4 16h2M12 16h8 M17.4 8a2.4 2.4 0 1 1-4.8 0 2.4 2.4 0 0 1 4.8 0 M11.4 16a2.4 2.4 0 1 1-4.8 0 2.4 2.4 0 0 1 4.8 0', plus: 'M12 5v14M5 12h14', search: 'M21 21l-4.35-4.35M19 11a8 8 0 1 1-16 0 8 8 0 0 1 16 0', filter: 'M4 7h16M7 12h10M10 17h4', sort: 'M8 4v16m-3-3 3 3 3-3M16 20V4m-3 3 3-3 3 3' };
1038
+ Object.assign(paths, {
1039
+ clock: 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0 M12 7v5l3 2',
1040
+ users: 'M12.2 8a3.2 3.2 0 1 1-6.4 0 3.2 3.2 0 0 1 6.4 0 M3 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5 M16 5.2a3.2 3.2 0 0 1 0 5.6 M18 14.8c1.9.7 3 2.5 3 5.2',
1041
+ calendar: 'M5 4h14a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2 M8 2v4 M16 2v4 M3 10h18',
1042
+ share: 'M20.6 5a2.6 2.6 0 1 1-5.2 0 2.6 2.6 0 0 1 5.2 0 M8.6 12a2.6 2.6 0 1 1-5.2 0 2.6 2.6 0 0 1 5.2 0 M20.6 19a2.6 2.6 0 1 1-5.2 0 2.6 2.6 0 0 1 5.2 0 M8.3 10.7l7.4-4.3 M8.3 13.3l7.4 4.3',
1043
+ folder: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z',
1044
+ });
860
1045
  path.setAttribute('d', paths[name] || paths.filter); svg.append(path); return svg;
861
1046
  }
862
1047