PM-44318 Add Autotype Default Keyboard Shortcut to Autotype GA Policy (#24427)

* PM-44318 Add Autotype Default Keyboard Shortcut to Autotype GA Policy

* address aikido feedback

* address design feedback

* address feedback
This commit is contained in:
Daniel Riera
2026-11-13 09:11:32 -05:00
committed by GitHub
parent 4b6c72ec2a
commit 80507e69c7
16 changed files with 987 additions and 180 deletions

View File

@@ -8,7 +8,10 @@ import { BehaviorSubject, EMPTY, firstValueFrom, from, fromEvent } from "rxjs";
import { catchError, concatMap, map, switchMap, timeout } from "rxjs/operators";
import { PremiumBadgeComponent } from "@bitwarden/angular/billing/components/premium-badge";
import { AutotypeShortcutComponent } from "@bitwarden/angular/desktop-native/components/autotype-shortcut.component";
import {
AutotypeShortcutComponent,
formatAutotypeShortcut,
} from "@bitwarden/angular/desktop-native/components/autotype-shortcut.component";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { getFirstPolicy } from "@bitwarden/common/admin-console/services/policy/default-policy.service";
@@ -843,7 +846,7 @@ export class SettingsDialogComponent implements OnInit {
}
private getFormattedAutotypeShortcutText(shortcut: string[]) {
return shortcut ? shortcut.join("+").replace("Super", "Win") : null;
return shortcut ? formatAutotypeShortcut(shortcut) : null;
}
static open(dialogService: DialogService) {

View File

@@ -1,14 +1,14 @@
import {
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
isAutotypeGaShortcut,
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
/**
Electron's representation of modifier keys
<https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts#cross-platform-modifiers>
*/
export const CONTROL_KEY_STR = "Control";
export const ALT_KEY_STR = "Alt";
export const SUPER_KEY_STR = "Super";
export const VALID_SHORTCUT_MODIFIER_KEYS: string[] = [CONTROL_KEY_STR, ALT_KEY_STR, SUPER_KEY_STR];
export const DEFAULT_KEYBOARD_SHORTCUT: string[] = [CONTROL_KEY_STR, ALT_KEY_STR, "B"];
// Shared with the web Autotype GA policy, which shows this as its Default option
export const DEFAULT_KEYBOARD_SHORTCUT: string[] = [...DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT];
/*
This class provides the following:
@@ -30,8 +30,8 @@ export class AutotypeKeyboardShortcut {
Returns a boolean value indicating if the autotypeKeyboardShortcut
was valid and set or not.
*/
set(newAutotypeKeyboardShortcut: string[]) {
if (!this.#keyboardShortcutIsValid(newAutotypeKeyboardShortcut)) {
set(newAutotypeKeyboardShortcut: string[]): boolean {
if (!isAutotypeGaShortcut(newAutotypeKeyboardShortcut)) {
return false;
}
@@ -56,55 +56,4 @@ export class AutotypeKeyboardShortcut {
getElectronFormat() {
return this.autotypeKeyboardShortcut.join("+");
}
/*
This private function validates the strArray input to make sure the array contains
valid, currently accepted shortcut keys for Windows.
Valid shortcut keys: Control, Alt, Super, letters A - Z
Platform specifics:
- On Windows, Super maps to the Windows key.
- On MacOS, Super maps to the Command key.
- On MacOS, Alt maps to the Option key.
See Electron keyboard shortcut docs for more info:
https://www.electronjs.org/docs/latest/tutorial/keyboard-shortcuts
*/
#keyboardShortcutIsValid(strArray: string[]) {
const UNICODE_LOWER_BOUND = 65; // unicode 'A'
const UNICODE_UPPER_BOUND = 90; // unicode 'Z'
const MIN_LENGTH: number = 2;
const MAX_LENGTH: number = 3;
// Ensure strArray is a string array of valid length
if (
strArray === undefined ||
strArray === null ||
strArray.length < MIN_LENGTH ||
strArray.length > MAX_LENGTH
) {
return false;
}
// Ensure strArray is all modifier keys, and that the last key is a letter
for (let i = 0; i < strArray.length; i++) {
if (i < strArray.length - 1) {
if (!VALID_SHORTCUT_MODIFIER_KEYS.includes(strArray[i])) {
return false;
}
} else {
const unicodeValue: number = strArray[i].charCodeAt(0);
if (
Number.isNaN(unicodeValue) ||
unicodeValue < UNICODE_LOWER_BOUND ||
unicodeValue > UNICODE_UPPER_BOUND
) {
return false;
}
}
}
return true;
}
}

View File

@@ -4,6 +4,7 @@ import { BehaviorSubject, firstValueFrom, take } from "rxjs";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
@@ -30,6 +31,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
let featureFlagSubject: BehaviorSubject<AutotypeFeatureFlagState>;
let mockAuthStatusSubject: BehaviorSubject<AuthenticationStatus>;
let mockPolicyAppliesSubject: BehaviorSubject<boolean>;
let mockPoliciesSubject: BehaviorSubject<Policy[]>;
const mockUserId = "user-123" as UserId;
@@ -46,6 +48,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
AuthenticationStatus.Unlocked,
);
mockPolicyAppliesSubject = new BehaviorSubject<boolean>(false);
mockPoliciesSubject = new BehaviorSubject<Policy[]>([]);
accountService = mock<AccountService>();
authService = mock<AuthService>();
@@ -60,6 +63,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
policyService.policyAppliesToUser$ = jest
.fn()
.mockReturnValue(mockPolicyAppliesSubject.asObservable());
policyService.policiesByType$ = jest.fn().mockReturnValue(mockPoliciesSubject.asObservable());
TestBed.configureTestingModule({
providers: [
@@ -80,6 +84,7 @@ describe("DesktopAutotypeGaPolicyService", () => {
featureFlagSubject.complete();
mockAuthStatusSubject.complete();
mockPolicyAppliesSubject.complete();
mockPoliciesSubject.complete();
});
describe("autotypeGaDefaultSetting$", () => {
@@ -246,4 +251,99 @@ describe("DesktopAutotypeGaPolicyService", () => {
);
});
});
describe("autotypeGaDefaultKeyboardShortcut$", () => {
const policyWith = (data: unknown, enabled = true, organizationId = "org-1") =>
({ enabled, data, organizationId }) as Policy;
const custom = (defaultKeyboardShortcut: unknown, organizationId = "org-1", enabled = true) =>
policyWith({ shortcutOption: "custom", defaultKeyboardShortcut }, enabled, organizationId);
const latest = () => firstValueFrom(service.autotypeGaDefaultKeyboardShortcut$.pipe(take(1)));
const record = () => {
const emissions: (string[] | null)[] = [];
const subscription = service.autotypeGaDefaultKeyboardShortcut$.subscribe((value) =>
emissions.push(value),
);
return { emissions, subscription };
};
it("emits the enabled custom shortcut for the active user", async () => {
mockPoliciesSubject.next([custom(["Super", "K"])]);
expect(await latest()).toEqual(["Super", "K"]);
expect(policyService.policiesByType$).toHaveBeenCalledWith(
PolicyType.AutotypeGaPolicy,
mockUserId,
);
});
it("skips policies that do not yield a registerable custom shortcut", () => {
const { emissions, subscription } = record();
for (const policies of [
[],
[custom(["Super", "K"], "org-1", false)],
[policyWith(null)],
[
policyWith({
shortcutOption: "default",
defaultKeyboardShortcut: ["Control", "Alt", "B"],
}),
],
[custom(["Shift", "1"])],
[custom(["Control", "Bogus"])],
[custom(["Alt", "Alt", "K"])],
[custom(["Control", 5])],
]) {
mockPoliciesSubject.next(policies);
}
mockPoliciesSubject.next([custom(["Super", "K"])]);
mockPoliciesSubject.next([custom(["Super", "K"])]);
mockPoliciesSubject.next([custom(["Alt", "Q"])]);
expect(emissions).toEqual([null, ["Super", "K"], ["Alt", "Q"]]);
subscription.unsubscribe();
});
it("uses the custom shortcut from the organization with the lowest id", async () => {
mockPoliciesSubject.next([
custom(["Alt", "Q"], "org-b"),
custom(["Control", "L"], "org-0", false),
policyWith(
{ shortcutOption: "default", defaultKeyboardShortcut: ["Control", "Alt", "B"] },
true,
"org-1",
),
custom(["Super", "K"], "org-a"),
]);
expect(await latest()).toEqual(["Super", "K"]);
});
it("emits null unless the GA flag is on for an unlocked account", async () => {
mockPoliciesSubject.next([custom(["Super", "K"])]);
featureFlagSubject.next(AutotypeFeatureFlagState.Mvp);
expect(await latest()).toBeNull();
expect(policyService.policiesByType$).not.toHaveBeenCalled();
featureFlagSubject.next(AutotypeFeatureFlagState.Ga);
mockAuthStatusSubject.next(AuthenticationStatus.Locked);
expect(await latest()).toBeNull();
});
it("emits null while locked and the shortcut again after unlock", () => {
mockPoliciesSubject.next([custom(["Super", "K"])]);
const { emissions, subscription } = record();
mockAuthStatusSubject.next(AuthenticationStatus.Locked);
mockAuthStatusSubject.next(AuthenticationStatus.Unlocked);
expect(emissions).toEqual([["Super", "K"], null, ["Super", "K"]]);
subscription.unsubscribe();
});
});
});

View File

@@ -4,13 +4,20 @@ import { distinctUntilChanged, filter, map, shareReplay, switchMap } from "rxjs/
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { AutotypeFeatureFlagState } from "@bitwarden/common/desktop-native/enums/autotype-feature-flag-state.enum";
import {
AutotypeGaPolicyData,
AutotypeShortcutOption,
isAutotypeGaShortcut,
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
import { autotypeFeatureFlagState$ } from "@bitwarden/common/desktop-native/services/autotype-feature-flags";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { UserId } from "@bitwarden/common/types/guid";
@Injectable({ providedIn: "root" })
export class DesktopAutotypeGaPolicyService {
@@ -21,35 +28,68 @@ export class DesktopAutotypeGaPolicyService {
private readonly configService: ConfigService,
) {}
readonly autotypeGaDefaultSetting$: Observable<boolean | null> = autotypeFeatureFlagState$(
this.configService,
).pipe(
switchMap((autotypeFeatureFlagState) => {
if (autotypeFeatureFlagState !== AutotypeFeatureFlagState.Ga) {
return of(null);
}
return this.accountService.activeAccount$.pipe(
filter((account) => account != null && account.id != null),
getUserId,
readonly autotypeGaDefaultSetting$: Observable<boolean | null> = this.whenGaAndUnlocked$(
(userId) =>
this.policyService.policyAppliesToUser$(PolicyType.AutotypeGaPolicy, userId).pipe(
map((applies) => (applies ? true : null)),
distinctUntilChanged(),
switchMap((userId) => {
const isUnlocked$ = this.authService.authStatusFor$(userId).pipe(
map((status) => status === AuthenticationStatus.Unlocked),
distinctUntilChanged(),
);
),
);
const policy$ = this.policyService
.policyAppliesToUser$(PolicyType.AutotypeGaPolicy, userId)
.pipe(
map((applies) => (applies ? true : null)),
// The custom shortcut from the Autotype GA policy, or null when there is none.
readonly autotypeGaDefaultKeyboardShortcut$: Observable<string[] | null> =
this.whenGaAndUnlocked$((userId) =>
this.policyService.policiesByType$(PolicyType.AutotypeGaPolicy, userId).pipe(
map((policies) => this.shortcutFromPolicies(policies)),
distinctUntilChanged((a, b) => a?.join("+") === b?.join("+")),
),
);
/** Lowest organization id. Default and invalid shortcuts are skipped, so sync order does not matter. */
private shortcutFromPolicies(policies: Policy[]): string[] | null {
return (
policies
.filter((policy) => policy.enabled)
.sort((a, b) => a.organizationId.localeCompare(b.organizationId))
.map((policy) => this.shortcutFromPolicy(policy.data))
.find((shortcut) => shortcut != null) ?? null
);
}
private shortcutFromPolicy(data: Partial<AutotypeGaPolicyData> | undefined): string[] | null {
const keys = data?.defaultKeyboardShortcut;
return data?.shortcutOption === AutotypeShortcutOption.Custom && isAutotypeGaShortcut(keys)
? keys
: null;
}
/** Emits the active user's policy value while the GA flag is on and the vault is unlocked, otherwise null. */
private whenGaAndUnlocked$<T>(
userPolicy$: (userId: UserId) => Observable<T | null>,
): Observable<T | null> {
return autotypeFeatureFlagState$(this.configService).pipe(
switchMap((autotypeFeatureFlagState) => {
if (autotypeFeatureFlagState !== AutotypeFeatureFlagState.Ga) {
return of(null);
}
return this.accountService.activeAccount$.pipe(
filter((account) => account != null && account.id != null),
getUserId,
distinctUntilChanged(),
switchMap((userId) => {
const isUnlocked$ = this.authService.authStatusFor$(userId).pipe(
map((status) => status === AuthenticationStatus.Unlocked),
distinctUntilChanged(),
);
return isUnlocked$.pipe(switchMap((unlocked) => (unlocked ? policy$ : of(null))));
}),
);
}),
shareReplay({ bufferSize: 1, refCount: true }),
);
return isUnlocked$.pipe(
switchMap((unlocked) => (unlocked ? userPolicy$(userId) : of(null))),
);
}),
);
}),
shareReplay({ bufferSize: 1, refCount: true }),
);
}
}

View File

@@ -15,6 +15,8 @@ import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { LogService } from "@bitwarden/logging";
import { DEFAULT_KEYBOARD_SHORTCUT } from "../models/main-autotype-keyboard-shortcut";
import { DesktopAutotypeGaPolicyService } from "./desktop-autotype-ga-policy.service";
import { DesktopAutotypeService } from "./desktop-autotype.service";
@@ -38,8 +40,9 @@ describe("DesktopAutotypeService", () => {
let mockAutotypeKeyboardShortcutState: FakeGlobalState<string[]>;
let autotypeEnabledSubject: BehaviorSubject<boolean | null>;
let autotypeKeyboardShortcutSubject: BehaviorSubject<string[]>;
let autotypeKeyboardShortcutSubject: BehaviorSubject<string[] | null>;
let autotypeGaPolicySubject: BehaviorSubject<boolean | null>;
let autotypeGaPolicyShortcutSubject: BehaviorSubject<string[] | null>;
let activeAccountSubject: BehaviorSubject<Account | null>;
let activeAccountStatusSubject: BehaviorSubject<AuthenticationStatus>;
let hasPremiumSubject: BehaviorSubject<boolean>;
@@ -62,8 +65,9 @@ describe("DesktopAutotypeService", () => {
beforeEach(() => {
autotypeEnabledSubject = new BehaviorSubject<boolean | null>(null);
autotypeKeyboardShortcutSubject = new BehaviorSubject<string[]>(["Control", "Alt", "B"]);
autotypeKeyboardShortcutSubject = new BehaviorSubject<string[] | null>(["Control", "Alt", "B"]);
autotypeGaPolicySubject = new BehaviorSubject<boolean | null>(null);
autotypeGaPolicyShortcutSubject = new BehaviorSubject<string[] | null>(null);
activeAccountSubject = new BehaviorSubject<Account | null>({
id: "user-123" as UserId,
email: "user@bitwarden.com",
@@ -143,7 +147,10 @@ describe("DesktopAutotypeService", () => {
},
{
provide: DesktopAutotypeGaPolicyService,
useValue: { autotypeGaDefaultSetting$: autotypeGaPolicySubject.asObservable() },
useValue: {
autotypeGaDefaultSetting$: autotypeGaPolicySubject.asObservable(),
autotypeGaDefaultKeyboardShortcut$: autotypeGaPolicyShortcutSubject.asObservable(),
},
},
{ provide: LogService, useValue: mock<LogService>() },
],
@@ -236,6 +243,55 @@ describe("DesktopAutotypeService", () => {
expect(autotypeEnabledSubject.value).toBe(false);
});
it("stores the policy shortcut when the local shortcut has never been set", async () => {
autotypeKeyboardShortcutSubject.next(null);
autotypeGaPolicyShortcutSubject.next(["Super", "K"]);
await service.init();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(autotypeKeyboardShortcutSubject.value).toEqual(["Super", "K"]);
expect(await firstValueFrom(service.autotypeKeyboardShortcut$)).toEqual(["Super", "K"]);
});
it("does not overwrite a stored shortcut when the policy shortcut changes", async () => {
autotypeKeyboardShortcutSubject.next(null);
autotypeGaPolicyShortcutSubject.next(["Super", "K"]);
await service.init();
await new Promise((resolve) => setTimeout(resolve, 0));
autotypeGaPolicyShortcutSubject.next(["Alt", "Q"]);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(mockAutotypeKeyboardShortcutState.update).toHaveBeenCalledTimes(1);
expect(autotypeKeyboardShortcutSubject.value).toEqual(["Super", "K"]);
});
it("does not overwrite a local keyboard shortcut the user already chose", async () => {
autotypeKeyboardShortcutSubject.next(["Control", "Alt", "A"]);
autotypeGaPolicyShortcutSubject.next(["Super", "K"]);
await service.init();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(mockAutotypeKeyboardShortcutState.update).not.toHaveBeenCalled();
expect(autotypeKeyboardShortcutSubject.value).toEqual(["Control", "Alt", "A"]);
});
it("uses the built-in shortcut when there is no local shortcut and no policy shortcut", async () => {
autotypeKeyboardShortcutSubject.next(null);
await service.init();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(await firstValueFrom(service.autotypeKeyboardShortcut$)).toEqual(
DEFAULT_KEYBOARD_SHORTCUT,
);
expect(mockAutotypeKeyboardShortcutState.update).not.toHaveBeenCalled();
expect(autotypeKeyboardShortcutSubject.value).toBeNull();
});
});
describe("setAutotypeEnabledState", () => {

View File

@@ -139,6 +139,24 @@ export class DesktopAutotypeService implements OnDestroy {
)
.subscribe();
combineLatest([
this.autotypeKeyboardShortcutState.state$,
this.desktopAutotypeGaPolicyService.autotypeGaDefaultKeyboardShortcut$,
])
.pipe(
concatMap(async ([keyboardShortcutState, policyKeyboardShortcut]) => {
try {
if (policyKeyboardShortcut != null && keyboardShortcutState == null) {
await this.setAutotypeKeyboardShortcutState(policyKeyboardShortcut);
}
} catch {
this.logService.error("Failed to set Autotype keyboard shortcut.");
}
}),
takeUntil(this.destroy$),
)
.subscribe();
// Listen for changes in keyboard shortcut settings
this.autotypeKeyboardShortcut$
.pipe(

View File

@@ -31,7 +31,8 @@ import { PolicyEditDialogData, PolicyEditDrawerComponent } from "./policy-edit-d
const ORG_ID = "test-org-id";
export type PolicyDialogStoryArgs = { enabled: boolean; isCloud?: boolean };
/** `data` is the saved policy data the drawer loads, omit it for a policy that was never saved. */
export type PolicyDialogStoryArgs = { enabled: boolean; isCloud?: boolean; data?: object };
/** @deprecated Use {@link PolicyDialogStoryArgs}. Kept as an alias for existing story files. */
export type PolicyDrawerStoryArgs = PolicyDialogStoryArgs;
@@ -166,7 +167,7 @@ export function policyDrawerMeta(
new PolicyStatusResponse({
OrganizationId: ORG_ID,
Type: policy.type,
Data: null,
Data: args.data ?? null,
Enabled: args.enabled,
CanToggleState: true,
}),

View File

@@ -1,11 +1,25 @@
import { NO_ERRORS_SCHEMA } from "@angular/core";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { mock, MockProxy } from "jest-mock-extended";
import { firstValueFrom, of } from "rxjs";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { PolicyStatusResponse } from "@bitwarden/common/admin-console/models/response/policy-status.response";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { AutotypeFeatureFlagState } from "@bitwarden/common/desktop-native/enums/autotype-feature-flag-state.enum";
import {
AutotypeShortcutOption,
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
import { autotypeFeatureFlagState$ } from "@bitwarden/common/desktop-native/services/autotype-feature-flags";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { mockAccountServiceWith } from "@bitwarden/common/spec";
import { OrganizationId, UserId } from "@bitwarden/common/types/guid";
import { KeyService } from "@bitwarden/key-management";
import {
DesktopAutotypeGaPolicy,
@@ -62,3 +76,187 @@ describe("DesktopAutotypeGaPolicy", () => {
});
});
});
describe("DesktopAutotypeGaPolicyComponent", () => {
let component: DesktopAutotypeGaPolicyComponent;
let fixture: ComponentFixture<DesktopAutotypeGaPolicyComponent>;
const makePolicyResponse = (data: object | null, enabled = true) =>
new PolicyStatusResponse({
OrganizationId: "org1" as OrganizationId,
Type: PolicyType.AutotypeGaPolicy,
Enabled: enabled,
Data: data,
});
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
{ provide: OrganizationService, useValue: { organizations$: () => of([]) } },
{ provide: AccountService, useValue: mockAccountServiceWith("user1" as UserId) },
{ provide: KeyService, useValue: mock<KeyService>() },
{ provide: PolicyApiServiceAbstraction, useValue: mock<PolicyApiServiceAbstraction>() },
{ provide: I18nService, useValue: { t: jest.fn((key: string) => key) } },
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
fixture = TestBed.createComponent(DesktopAutotypeGaPolicyComponent);
fixture.componentRef.setInput("policy", new DesktopAutotypeGaPolicy());
component = fixture.componentInstance;
});
const requestData = async () => (await component.buildRequest()).policy.data;
it("saves the built-in shortcut when Default is selected", async () => {
component.ngOnInit();
component.enabled.setValue(true);
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Default);
expect(component["customShortcut"]()).toBeNull();
expect(component.data.valid).toBe(true);
expect(await requestData()).toEqual({
shortcutOption: AutotypeShortcutOption.Default,
defaultKeyboardShortcut: DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
});
});
it("leaves an unsaved policy on Default with no shortcut", () => {
fixture.componentRef.setInput("policyResponse", makePolicyResponse(null, false));
component.ngOnInit();
const loaded = component.data.getRawValue();
expect(loaded).toEqual({
shortcutOption: AutotypeShortcutOption.Default,
defaultKeyboardShortcut: null,
});
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
component["shortcutOption"].setValue(AutotypeShortcutOption.Default);
expect(component.data.getRawValue()).toEqual(loaded);
});
it("loads older or invalid saved data without changing it or throwing", () => {
const response = makePolicyResponse({});
fixture.componentRef.setInput("policyResponse", response);
component.ngOnInit();
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Default);
expect(component.data.valid).toBe(true);
expect(response.data).toEqual({});
fixture.componentRef.setInput(
"policyResponse",
makePolicyResponse({
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: "Ctrl+K",
}),
);
expect(() => {
component.ngOnInit();
fixture.detectChanges();
}).not.toThrow();
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Custom);
expect(component["defaultKeyboardShortcut"].value).toBeNull();
});
it("loads a saved custom shortcut and marks the form dirty only when it changes", async () => {
fixture.componentRef.setInput(
"policyResponse",
makePolicyResponse({
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: ["Control", "Super", "K"],
}),
);
component.ngOnInit();
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Custom);
expect(component["customShortcut"]()).toEqual(["Control", "Super", "K"]);
expect(component.data.dirty).toBe(false);
expect(await requestData()).toEqual({
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: ["Control", "Super", "K"],
});
component["onCustomShortcut"](["Alt", "Q"]);
expect(component.data.dirty).toBe(true);
});
it("saves a custom shortcut and keeps it when switching back to Default", async () => {
component.ngOnInit();
component.enabled.setValue(true);
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
expect(component.data.valid).toBe(false);
component["onCustomShortcut"](["Alt", "Q"]);
expect(component.data.valid).toBe(true);
expect(await requestData()).toEqual({
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: ["Alt", "Q"],
});
component["shortcutOption"].setValue(AutotypeShortcutOption.Default);
expect(await requestData()).toEqual({
shortcutOption: AutotypeShortcutOption.Default,
defaultKeyboardShortcut: DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
});
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
expect(component["customShortcut"]()).toEqual(["Alt", "Q"]);
expect(component.data.valid).toBe(true);
component["onCustomShortcut"](["Control", "Alt", "Super", "K"]);
expect(component.data.valid).toBe(false);
});
it("saves Custom with no shortcut when the policy is turned off", async () => {
fixture.componentRef.setInput(
"policyResponse",
makePolicyResponse(
{
shortcutOption: AutotypeShortcutOption.Default,
defaultKeyboardShortcut: null,
},
true,
),
);
component.ngOnInit();
component["shortcutOption"].setValue(AutotypeShortcutOption.Custom);
expect(component["customShortcut"]()).toBeNull();
expect(component.data.valid).toBe(false);
component.enabled.setValue(false);
expect(component.data.valid).toBe(true);
expect(await requestData()).toEqual({
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: null,
});
fixture.componentRef.setInput(
"policyResponse",
makePolicyResponse(
{
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: null,
},
false,
),
);
component.ngOnInit();
expect(component["shortcutOption"].value).toBe(AutotypeShortcutOption.Custom);
expect(component["customShortcut"]()).toBeNull();
expect(component.enabled.value).toBe(false);
});
});

View File

@@ -1,5 +1,11 @@
import { StoryObj } from "@storybook/angular";
import {
AutotypeGaPolicyData,
AutotypeShortcutOption,
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
import { PolicyDialogStoryArgs, policyDrawerMeta } from "../policy-drawer-story.helper";
import { DesktopAutotypeGaPolicy } from "./autotype-ga-policy.component";
@@ -16,3 +22,23 @@ export const PolicyOff: Story = {};
export const PolicyOn: Story = {
args: { enabled: true },
};
export const DefaultShortcut: Story = {
args: {
enabled: true,
data: {
shortcutOption: AutotypeShortcutOption.Default,
defaultKeyboardShortcut: [...DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT],
} satisfies AutotypeGaPolicyData,
},
};
export const CustomShortcut: Story = {
args: {
enabled: true,
data: {
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: ["Control", "Super", "K"],
} satisfies AutotypeGaPolicyData,
},
};

View File

@@ -1,15 +1,27 @@
import { ChangeDetectionStrategy, Component } from "@angular/core";
import { ReactiveFormsModule } from "@angular/forms";
import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop";
import { FormControl, FormGroup, ReactiveFormsModule } from "@angular/forms";
import { merge } from "rxjs";
import { map } from "rxjs/operators";
import {
AutotypeShortcutComponent,
formatAutotypeShortcut,
} from "@bitwarden/angular/desktop-native/components/autotype-shortcut.component";
import { PolicyType } from "@bitwarden/common/admin-console/enums";
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { AutotypeFeatureFlagState } from "@bitwarden/common/desktop-native/enums/autotype-feature-flag-state.enum";
import {
AutotypeGaPolicyData,
AutotypeShortcutOption,
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
isAutotypeGaShortcut,
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
import { autotypeFeatureFlagState$ } from "@bitwarden/common/desktop-native/services/autotype-feature-flags";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import {
FormControlModule,
LinkComponent,
RadioButtonModule,
SwitchComponent,
TypographyModule,
} from "@bitwarden/components";
@@ -52,15 +64,140 @@ export class DesktopAutotypeGaPolicy extends BasePolicyEditDefinition {
<bit-switch [formControl]="enabled"></bit-switch>
<bit-label>{{ "enablePolicy" | i18n }}</bit-label>
</bit-form-control>
<div [formGroup]="data">
<bit-form-control-group formControlName="shortcutOption" [block]="true">
<bit-label>
<span class="tw-flex tw-flex-col">
<span>{{ "appAutofillShortcut" | i18n }}</span>
<span bitTypography="body2" class="tw-text-muted tw-font-normal">
{{ "appAutofillShortcutDesc" | i18n }}
</span>
</span>
</bit-label>
<bit-form-control disableMargin>
<input
type="radio"
bitRadio
[value]="shortcutOptions.Default"
id="autotype-ga-policy_input_shortcut-default"
/>
<bit-label>{{ "default" | i18n }}</bit-label>
<bit-hint>{{ "autotypeDefaultShortcutDesc" | i18n: defaultShortcutText }}</bit-hint>
</bit-form-control>
<bit-form-control disableMargin>
<input
type="radio"
bitRadio
[value]="shortcutOptions.Custom"
id="autotype-ga-policy_input_shortcut-custom"
/>
<bit-label>{{ "custom" | i18n }}</bit-label>
<bit-hint>{{ "autotypeCustomShortcutDesc" | i18n }}</bit-hint>
</bit-form-control>
</bit-form-control-group>
@if (selectedShortcutOption() === shortcutOptions.Custom) {
<app-autotype-shortcut
class="tw-block"
[inline]="true"
[shortcut]="customShortcut()"
(shortcutChange)="onCustomShortcut($event)"
/>
}
</div>
`,
imports: [
ReactiveFormsModule,
FormControlModule,
AutotypeShortcutComponent,
LinkComponent,
RadioButtonModule,
SwitchComponent,
TypographyModule,
I18nPipe,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DesktopAutotypeGaPolicyComponent extends BasePolicyEditComponent {}
export class DesktopAutotypeGaPolicyComponent extends BasePolicyEditComponent {
protected readonly shortcutOptions = AutotypeShortcutOption;
protected readonly defaultShortcutText = formatAutotypeShortcut(
DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT,
);
private readonly shortcutOption = new FormControl<AutotypeShortcutOption>(
AutotypeShortcutOption.Default,
{ nonNullable: true },
);
/**
* The custom shortcut. Kept while Default is selected so switching back restores it.
* Required only while Custom is selected and the policy is on.
*/
private readonly defaultKeyboardShortcut = new FormControl<string[] | null>(null, {
validators: (control) => {
if (control.value != null && !isAutotypeGaShortcut(control.value)) {
return { invalidShortcut: true };
}
return control.value == null &&
this.shortcutOption.value === AutotypeShortcutOption.Custom &&
this.enabled.value === true
? { required: true }
: null;
},
});
protected readonly customShortcut = toSignal(this.defaultKeyboardShortcut.valueChanges, {
initialValue: this.defaultKeyboardShortcut.value,
});
protected readonly selectedShortcutOption = toSignal(this.shortcutOption.valueChanges, {
initialValue: this.shortcutOption.value,
});
readonly data = new FormGroup({
shortcutOption: this.shortcutOption,
defaultKeyboardShortcut: this.defaultKeyboardShortcut,
});
constructor() {
super();
// The shortcut's required check depends on the option and the policy toggle.
merge(this.shortcutOption.valueChanges, this.enabled.valueChanges)
.pipe(takeUntilDestroyed())
.subscribe(() => {
this.defaultKeyboardShortcut.updateValueAndValidity();
});
}
protected onCustomShortcut(keys: string[] | null): void {
this.defaultKeyboardShortcut.setValue(keys);
this.data.markAsDirty();
}
/** Saved data without the Custom option, including data from before this setting existed, loads as Default. */
protected override loadData() {
const data = this.policyResponse()?.data as Partial<AutotypeGaPolicyData> | null;
const custom = data?.shortcutOption === AutotypeShortcutOption.Custom;
const storedShortcut = data?.defaultKeyboardShortcut;
const stored = isAutotypeGaShortcut(storedShortcut) ? storedShortcut : null;
this.defaultKeyboardShortcut.setValue(custom ? stored : null);
this.shortcutOption.setValue(
custom ? AutotypeShortcutOption.Custom : AutotypeShortcutOption.Default,
);
}
protected override buildRequestData(): AutotypeGaPolicyData {
if (this.shortcutOption.value === AutotypeShortcutOption.Custom) {
return {
shortcutOption: AutotypeShortcutOption.Custom,
defaultKeyboardShortcut: this.defaultKeyboardShortcut.value,
};
}
return {
shortcutOption: AutotypeShortcutOption.Default,
defaultKeyboardShortcut: [...DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT],
};
}
}

View File

@@ -9539,6 +9539,33 @@
"desktopAppAutofillPolicyDrawerDesc": {
"message": "Turn on desktop app autofill by default for all members. You can set a keyboard shortcut and choose whether members must confirm before it fills. This feature is in beta."
},
"keyboardShortcut": {
"message": "Keyboard shortcut"
},
"appAutofillShortcut": {
"message": "App autofill shortcut"
},
"appAutofillShortcutDesc": {
"message": "Members can change this keyboard shortcut at any time."
},
"autotypeDefaultShortcutDesc": {
"message": "Use the Bitwarden default shortcut: $SHORTCUT$.",
"placeholders": {
"shortcut": {
"content": "$1",
"example": "Ctrl + Alt + B"
}
}
},
"autotypeCustomShortcutDesc": {
"message": "Enter your own custom shortcut."
},
"defaultKeyboardShortcutPolicyHint": {
"message": "Include Ctrl, Alt, or Win and at least 1 letter."
},
"invalidShortcut": {
"message": "Invalid shortcut"
},
"disableSend": {
"message": "Remove Send"
},

View File

@@ -1,31 +1,55 @@
<form [bitSubmit]="submit" [formGroup]="setShortcutForm" bit-dialog>
<div class="tw-font-medium" bitDialogTitle>
{{ "typeShortcut" | i18n }}
</div>
<div bitDialogContent>
<p>
{{ "editAutotypeKeyboardModifiersDescription" | i18n }}
</p>
@if (inline()) {
<div [formGroup]="setShortcutForm">
<bit-form-field>
<bit-label>{{ "typeShortcut" | i18n }}</bit-label>
<bit-label>{{ "keyboardShortcut" | i18n }}</bit-label>
<input
id="autotype-shortcut_input_keyboard-shortcut"
class="tw-font-mono"
bitInput
type="text"
formControlName="shortcut"
(keydown)="onShortcutKeydown($event)"
(paste)="onShortcutTextInsert($event)"
(drop)="onShortcutTextInsert($event)"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
/>
<bit-hint>{{ "defaultKeyboardShortcutPolicyHint" | i18n }}</bit-hint>
</bit-form-field>
</div>
<ng-container bitDialogFooter>
<button type="submit" bitButton bitFormButton buttonType="primary">
<span>{{ "save" | i18n }}</span>
</button>
<button type="button" bitButton bitFormButton buttonType="secondary" bitDialogClose>
{{ "cancel" | i18n }}
</button>
</ng-container>
</form>
} @else {
<form [bitSubmit]="submit" [formGroup]="setShortcutForm" bit-dialog>
<div class="tw-font-medium" bitDialogTitle>
{{ "typeShortcut" | i18n }}
</div>
<div bitDialogContent>
<p>
{{ "editAutotypeKeyboardModifiersDescription" | i18n }}
</p>
<bit-form-field>
<bit-label>{{ "typeShortcut" | i18n }}</bit-label>
<input
class="tw-font-mono"
bitInput
type="text"
formControlName="shortcut"
(keydown)="onShortcutKeydown($event)"
(paste)="onShortcutTextInsert($event)"
(drop)="onShortcutTextInsert($event)"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
/>
</bit-form-field>
</div>
<ng-container bitDialogFooter>
<button type="submit" bitButton bitFormButton buttonType="primary">
<span>{{ "save" | i18n }}</span>
</button>
<button type="button" bitButton bitFormButton buttonType="secondary" bitDialogClose>
{{ "cancel" | i18n }}
</button>
</ng-container>
</form>
}

View File

@@ -1,21 +1,95 @@
import { AbstractControl, FormBuilder, ValidationErrors } from "@angular/forms";
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { AbstractControl, ValidationErrors } from "@angular/forms";
import { mock, MockProxy } from "jest-mock-extended";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { AutotypeShortcutComponent } from "./autotype-shortcut.component";
describe("AutotypeShortcutComponent inline field", () => {
let field: AutotypeShortcutComponent;
let fixture: ComponentFixture<AutotypeShortcutComponent>;
beforeEach(() => {
const i18nService = mock<I18nService>();
i18nService.t.mockReturnValue("Invalid shortcut");
fixture = TestBed.configureTestingModule({
providers: [{ provide: I18nService, useValue: i18nService }],
}).createComponent(AutotypeShortcutComponent);
fixture.componentRef.setInput("inline", true);
field = fixture.componentInstance;
});
const keydown = (init: KeyboardEventInit) => new KeyboardEvent("keydown", init);
it("shows, captures, and clears a shortcut without taking Tab or Escape", () => {
const emitted: (string[] | null)[] = [];
field.shortcutChange.subscribe((keys) => emitted.push(keys));
fixture.componentRef.setInput("shortcut", ["Control", "Super", "K"]);
fixture.detectChanges();
expect(field.setShortcutForm.controls.shortcut.value).toBe("Ctrl + Win + K");
fixture.componentRef.setInput("shortcut", ["Control", "K"]);
fixture.detectChanges();
expect(field.setShortcutForm.controls.shortcut.value).toBe("Ctrl + K");
for (const init of [
{ key: "@", code: "KeyQ", altKey: true, ctrlKey: true },
{ key: "1", ctrlKey: true },
{ key: "k", ctrlKey: true, shiftKey: true },
{ key: "k", ctrlKey: true, altKey: true, metaKey: true },
]) {
field.onShortcutKeydown(keydown(init));
}
expect(field.setShortcutForm.controls.shortcut.value).toBe("Ctrl + K");
expect(emitted).toEqual([]);
field.onShortcutKeydown(keydown({ key: "a", code: "KeyQ", altKey: true, ctrlKey: true }));
expect(field.setShortcutForm.controls.shortcut.value).toBe("Ctrl + Alt + A");
field.onShortcutKeydown(keydown({ key: "k", metaKey: true }));
expect(field.setShortcutForm.controls.shortcut.value).toBe("Win + K");
for (const key of ["Tab", "Escape"]) {
const event = keydown({ key, cancelable: true });
field.onShortcutKeydown(event);
expect(event.defaultPrevented).toBe(false);
}
expect(field.setShortcutForm.controls.shortcut.value).toBe("Win + K");
const backspace = keydown({ key: "Backspace", cancelable: true });
field.onShortcutKeydown(backspace);
expect(backspace.defaultPrevented).toBe(true);
expect(field.setShortcutForm.controls.shortcut.value).toBe("");
expect(emitted).toEqual([["Control", "Alt", "A"], ["Super", "K"], null]);
});
it("is required when empty and touched, and ignores pasted text", () => {
field.setShortcutForm.controls.shortcut.markAsTouched();
expect(field.setShortcutForm.controls.shortcut.errors).toEqual({ required: true });
const event = new Event("paste", { cancelable: true });
field.onShortcutTextInsert(event);
expect(event.defaultPrevented).toBe(true);
expect(field.setShortcutForm.controls.shortcut.value).toBe("");
});
});
describe("AutotypeShortcutComponent", () => {
let component: AutotypeShortcutComponent;
let validator: (control: AbstractControl) => ValidationErrors | null;
let formBuilder: MockProxy<FormBuilder>;
let i18nService: MockProxy<I18nService>;
beforeEach(() => {
formBuilder = mock<FormBuilder>();
i18nService = mock<I18nService>();
i18nService.t.mockReturnValue("Invalid shortcut");
component = new AutotypeShortcutComponent(null as any, formBuilder, i18nService);
TestBed.configureTestingModule({
providers: [{ provide: I18nService, useValue: i18nService }],
});
component = TestBed.runInInjectionContext(() => new AutotypeShortcutComponent());
validator = component["shortcutCombinationValidator"]();
});
@@ -114,8 +188,18 @@ describe("AutotypeShortcutComponent", () => {
});
});
it("should accept the displayed format", () => {
const validShortcuts = ["Ctrl + Alt + L", "Win + K", "Ctrl+A", "Alt + Win + B"];
validShortcuts.forEach((shortcut) => {
const control = createControl(shortcut);
const result = validator(control);
expect(result).toBeNull();
});
});
it("should reject shortcuts with invalid modifier names", () => {
const invalidShortcuts = ["Ctrl+A", "Command+A", "Meta+A", "Cmd+A", "Invalid+A"];
const invalidShortcuts = ["Command+A", "Meta+A", "Cmd+A", "Invalid+A"];
invalidShortcuts.forEach((shortcut) => {
const control = createControl(shortcut);
@@ -134,6 +218,12 @@ describe("AutotypeShortcutComponent", () => {
});
});
it("should reject a repeated modifier", () => {
expect(validator(createControl("Alt+Alt+K"))).toEqual({
invalidShortcut: { message: "Invalid shortcut" },
});
});
it("should reject shortcuts with more than two modifiers", () => {
const invalidShortcuts = [
"Control+Alt+Win+A",

View File

@@ -1,5 +1,5 @@
import { CommonModule } from "@angular/common";
import { Component } from "@angular/core";
import { Component, effect, inject, input, output, untracked } from "@angular/core";
import {
FormBuilder,
ReactiveFormsModule,
@@ -9,6 +9,10 @@ import {
ValidationErrors,
} from "@angular/forms";
import {
autotypeGaShortcutFromText,
isAutotypeGaShortcut,
} from "@bitwarden/common/desktop-native/models/autotype-ga-policy.data";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { Utils } from "@bitwarden/common/platform/misc/utils";
import {
@@ -22,9 +26,60 @@ import {
} from "@bitwarden/components";
import { I18nPipe } from "@bitwarden/ui-common";
// Electron's "Super" is the Windows key on Windows and the Command key on macOS.
const DISPLAY_KEY_NAMES: Record<string, string> = {
Control: "Ctrl",
Super: "Win",
};
/** Formats stored keys for display, e.g. ["Control", "Alt", "L"] as "Ctrl + Alt + L". */
export function formatAutotypeShortcut(keys: readonly string[]): string {
return keys.map((key) => DISPLAY_KEY_NAMES[key] ?? key).join(" + ");
}
function shortcutLetter(event: KeyboardEvent): string | null {
return /^[a-z]$/i.test(event.key) ? event.key.toUpperCase() : null;
}
/** One or two of Ctrl, Alt, or Win, plus a letter. The command key is stored as Super. */
export function captureAutotypeShortcut(event: KeyboardEvent): string[] | null {
const hasCtrl = event.ctrlKey;
const hasAlt = event.altKey;
const hasShift = event.shiftKey;
const hasSuper = event.metaKey;
if (!hasCtrl && !hasAlt && !hasSuper) {
return null;
}
if (hasShift) {
return null;
}
const letter = shortcutLetter(event);
if (letter == null) {
return null;
}
const keys: string[] = [];
if (hasCtrl) {
keys.push("Control");
}
if (hasAlt) {
keys.push("Alt");
}
if (hasSuper) {
keys.push("Super");
}
keys.push(letter);
return isAutotypeGaShortcut(keys) ? keys : null;
}
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
@Component({
selector: "app-autotype-shortcut",
templateUrl: "autotype-shortcut.component.html",
imports: [
DialogModule,
@@ -38,11 +93,13 @@ import { I18nPipe } from "@bitwarden/ui-common";
],
})
export class AutotypeShortcutComponent {
constructor(
private dialogRef: DialogRef,
private formBuilder: FormBuilder,
private i18nService: I18nService,
) {}
readonly inline = input(false);
readonly shortcut = input<string[] | null>(null);
readonly shortcutChange = output<string[] | null>();
private readonly dialogRef = inject<DialogRef<string[]>>(DialogRef, { optional: true });
private readonly formBuilder = inject(FormBuilder);
private readonly i18nService = inject(I18nService);
private shortcutArray: string[] = [];
@@ -50,6 +107,19 @@ export class AutotypeShortcutComponent {
shortcut: ["", [Validators.required, this.shortcutCombinationValidator()]],
});
constructor() {
effect(() => {
const shortcut = this.shortcut();
const keys = isAutotypeGaShortcut(shortcut) ? shortcut : [];
untracked(() => {
this.shortcutArray = keys;
this.setShortcutForm.controls.shortcut.setValue(
keys.length > 0 ? formatAutotypeShortcut(keys) : "",
);
});
});
}
submit = async () => {
const shortcutFormControl = this.setShortcutForm.controls.shortcut;
@@ -57,7 +127,7 @@ export class AutotypeShortcutComponent {
return;
}
await this.dialogRef.close(this.shortcutArray);
await this.dialogRef?.close(this.shortcutArray);
};
static open(dialogService: DialogService) {
@@ -65,62 +135,39 @@ export class AutotypeShortcutComponent {
}
onShortcutKeydown(event: KeyboardEvent): void {
if (this.inline() && (event.key === "Tab" || event.key === "Escape")) {
return;
}
event.preventDefault();
const shortcut = this.buildShortcutFromEvent(event);
if (this.inline() && event.key === "Backspace") {
if (this.shortcutArray.length === 0) {
return;
}
if (shortcut != null) {
this.setShortcutForm.controls.shortcut.setValue(shortcut);
this.shortcutArray = [];
this.setShortcutForm.controls.shortcut.setValue("");
this.setShortcutForm.controls.shortcut.markAsDirty();
this.setShortcutForm.controls.shortcut.updateValueAndValidity();
this.shortcutChange.emit(null);
return;
}
const keys = captureAutotypeShortcut(event);
if (keys != null) {
this.shortcutArray = keys;
this.setShortcutForm.controls.shortcut.setValue(formatAutotypeShortcut(keys));
this.setShortcutForm.controls.shortcut.markAsDirty();
this.setShortcutForm.controls.shortcut.updateValueAndValidity();
this.shortcutChange.emit(keys);
}
}
// <https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent>
private buildShortcutFromEvent(event: KeyboardEvent): string | null {
const hasCtrl = event.ctrlKey;
const hasAlt = event.altKey;
const hasShift = event.shiftKey;
const hasSuper = event.metaKey; // Windows key on Windows, Command on macOS
// Require at least one valid modifier (Control, Alt, Super)
if (!hasCtrl && !hasAlt && !hasSuper) {
return null;
}
const key = event.key;
// disallow pure modifier keys themselves
if (key === "Control" || key === "Alt" || key === "Meta") {
return null;
}
// disallow shift modifier
if (hasShift) {
return null;
}
// require a single alphabetical letter as the base key
const isAlphabetical = typeof key === "string" && /^[a-z]$/i.test(key);
if (!isAlphabetical) {
return null;
}
const parts: string[] = [];
if (hasCtrl) {
parts.push("Control");
}
if (hasAlt) {
parts.push("Alt");
}
if (hasSuper) {
parts.push("Super");
}
parts.push(key.toUpperCase());
this.shortcutArray = parts;
return parts.join("+").replace("Super", "Win");
/** Only keyboard capture may set the shortcut, so pasted or dropped text is ignored. */
onShortcutTextInsert(event: Event): void {
event.preventDefault();
}
private shortcutCombinationValidator(): ValidatorFn {
@@ -130,11 +177,7 @@ export class AutotypeShortcutComponent {
return null; // handled by required
}
// Must include exactly 1-2 modifiers and end with a single letter
// Valid examples: Ctrl+A, Alt+B, Ctrl+Alt+X, Alt+Control+Q, Win+B, Ctrl+Win+A
// Allow modifiers in any order, but only 1-2 modifiers total
const pattern = /^(?=.*\b(Control|Alt|Win)\b)(?:Control\+|Alt\+|Win\+){1,2}[A-Z]$/i;
return pattern.test(value)
return autotypeGaShortcutFromText(value) != null
? null
: { invalidShortcut: { message: this.i18nService.t("invalidShortcut") } };
};

View File

@@ -0,0 +1,16 @@
import { isAutotypeGaShortcut } from "./autotype-ga-policy.data";
describe("isAutotypeGaShortcut", () => {
it("accepts one or two modifiers and a letter", () => {
expect(isAutotypeGaShortcut(["Control", "Alt", "B"])).toBe(true);
expect(isAutotypeGaShortcut(["Super", "K"])).toBe(true);
});
it("rejects shortcuts Electron cannot register", () => {
expect(isAutotypeGaShortcut(["Control", "Alt", "Super", "K"])).toBe(false);
expect(isAutotypeGaShortcut(["Alt", "Alt", "K"])).toBe(false);
expect(isAutotypeGaShortcut(["Control", "Bogus"])).toBe(false);
expect(isAutotypeGaShortcut(["Control", 5])).toBe(false);
expect(isAutotypeGaShortcut("Ctrl+K")).toBe(false);
});
});

View File

@@ -0,0 +1,79 @@
export const AutotypeShortcutOption = Object.freeze({
Default: "default",
Custom: "custom",
} as const);
export type AutotypeShortcutOption =
(typeof AutotypeShortcutOption)[keyof typeof AutotypeShortcutOption];
/** Electron key names for the desktop app's built-in shortcut, shown as Ctrl+Alt+B. */
export const DEFAULT_AUTOTYPE_GA_KEYBOARD_SHORTCUT: readonly string[] = Object.freeze([
"Control",
"Alt",
"B",
]);
const AUTOTYPE_SHORTCUT_MODIFIERS = new Set(["Control", "Alt", "Super"]);
const AUTOTYPE_SHORTCUT_TEXT_MODIFIERS: Record<string, string> = {
control: "Control",
ctrl: "Control",
alt: "Alt",
super: "Super",
win: "Super",
};
/*
Data stored on the Autotype GA policy.
`default` stores the built-in shortcut, ["Control", "Alt", "B"] (Ctrl+Alt+B).
`custom` stores Electron modifier names (Control, Alt, Super) plus a letter.
Super is the Windows key, and the Command key on macOS.
*/
export type AutotypeGaPolicyData = {
shortcutOption: AutotypeShortcutOption;
defaultKeyboardShortcut: string[] | null;
};
/** One or two distinct modifiers, then a single letter A–Z. */
export function isAutotypeGaShortcut(value: unknown): value is string[] {
if (!Array.isArray(value) || value.length < 2 || value.length > 3) {
return false;
}
const modifiers = new Set<string>();
for (let i = 0; i < value.length; i++) {
const key = value[i];
if (typeof key !== "string") {
return false;
}
if (i < value.length - 1) {
if (!AUTOTYPE_SHORTCUT_MODIFIERS.has(key) || modifiers.has(key)) {
return false;
}
modifiers.add(key);
} else if (!/^[A-Z]$/.test(key)) {
return false;
}
}
return true;
}
/** Parses a shortcut typed or shown in the field, such as "Ctrl + Alt + L". */
export function autotypeGaShortcutFromText(value: string): string[] | null {
const keys: string[] = [];
for (const part of value.split("+").map((part) => part.trim())) {
const modifier = AUTOTYPE_SHORTCUT_TEXT_MODIFIERS[part.toLowerCase()];
if (modifier != null) {
keys.push(modifier);
} else if (/^[a-z]$/i.test(part)) {
keys.push(part.toUpperCase());
} else {
return null;
}
}
return isAutotypeGaShortcut(keys) ? keys : null;
}