Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,11 @@ async function bundleExtension(context: BuildContext): Promise<void> {
outfile: path.join(context.buildDir, "content_script.js"),
label: "content_script",
},
{
entrypoint: path.join(context.srcDir, "entries", "content_script_main_world_start.ts"),
outfile: path.join(context.buildDir, "content_script_main_world_start.js"),
label: "content_script_main_world_start",
},
{
entrypoint: path.join(context.srcDir, "entries", "content_script_main_world.ts"),
outfile: path.join(context.buildDir, "content_script_main_world.js"),
Expand Down
8 changes: 8 additions & 0 deletions platform/chrome/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
},
"optional_host_permissions": ["<all_urls>"],
"content_scripts": [
{
"js": ["content_script_main_world_start.js"],
"matches": ["<all_urls>"],
"run_at": "document_start",
"all_frames": true,
"match_about_blank": true,
"world": "MAIN"
},
{
"js": ["content_script_main_world.js"],
"matches": ["<all_urls>"],
Expand Down
8 changes: 8 additions & 0 deletions platform/edge/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
},
"optional_host_permissions": ["<all_urls>"],
"content_scripts": [
{
"js": ["content_script_main_world_start.js"],
"matches": ["<all_urls>"],
"run_at": "document_start",
"all_frames": true,
"match_about_blank": true,
"world": "MAIN"
},
{
"js": ["content_script_main_world.js"],
"matches": ["<all_urls>"],
Expand Down
8 changes: 8 additions & 0 deletions platform/firefox/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
},
"optional_host_permissions": ["<all_urls>"],
"content_scripts": [
{
"js": ["content_script_main_world_start.js"],
"matches": ["<all_urls>"],
"run_at": "document_start",
"all_frames": true,
"match_about_blank": true,
"world": "MAIN"
},
{
"js": ["content_script_main_world.js"],
"matches": ["<all_urls>"],
Expand Down
14 changes: 14 additions & 0 deletions src/adapters/chrome/content-script/ContentRuntimeController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,19 @@ export class ContentRuntimeController {
this.suggestionManager?.triggerActiveSuggestion();
}

handleEarlyTabAcceptRequest(entryId: string): EarlyTabAcceptResult {
return (
this.suggestionManager?.handleEarlyTabAcceptRequest(entryId) ?? {
accepted: false,
reason: "entry_not_found",
entryId,
suggestionCount: 0,
menuVisible: false,
hasInlineSuggestion: false,
}
);
}

getPredictionGeneration(): number {
return this.predictionGeneration;
}
Expand Down Expand Up @@ -420,3 +433,4 @@ export class ContentRuntimeController {
}
}
}
import type { EarlyTabAcceptResult } from "./suggestions/SuggestionManagerRuntime";
9 changes: 8 additions & 1 deletion src/adapters/chrome/content-script/SuggestionManager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { SuggestionManagerRuntime } from "./suggestions/SuggestionManagerRuntime";
import {
SuggestionManagerRuntime,
type EarlyTabAcceptResult,
} from "./suggestions/SuggestionManagerRuntime";
import type { PredictionResponse, SuggestionManagerOptions } from "./suggestions/types";

export class SuggestionManager {
Expand All @@ -20,6 +23,10 @@ export class SuggestionManager {
this.runtime.triggerActiveSuggestion();
}

public handleEarlyTabAcceptRequest(entryId: string): EarlyTabAcceptResult {
return this.runtime.handleEarlyTabAcceptRequest(entryId);
}

public updateLangConfig(lang: string): void {
this.runtime.updateLangConfig(lang);
}
Expand Down
13 changes: 13 additions & 0 deletions src/adapters/chrome/content-script/content_script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
import { ContentMessageHandler } from "./ContentMessageHandler";
import { ContentRuntimeController } from "./ContentRuntimeController";
import { HostChangeWatcher } from "./HostChangeWatcher";
import { isEarlyTabAcceptMessage } from "./suggestions/EarlyTabAcceptBridgeProtocol";
import { ThemeApplicator } from "./ThemeApplicator";
import type { DomObserver } from "./DomObserver";
import type { SuggestionManager } from "./SuggestionManager";
Expand Down Expand Up @@ -68,6 +69,8 @@ class FluentTyper {
sender?: chrome.runtime.MessageSender,
sendResponse?: (response: unknown) => void,
) => this.messageHandler(message, sender, sendResponse);
private readonly boundEarlyTabAcceptHandler = (event: MessageEvent) =>
this.handleEarlyTabAccept(event);

constructor() {
logger.info("Initializing content script", {
Expand Down Expand Up @@ -110,6 +113,7 @@ class FluentTyper {
});

chrome.runtime.onMessage.addListener(this.boundMessageHandler);
window.addEventListener("message", this.boundEarlyTabAcceptHandler);
this.hostChangeWatcher.start();
this.getConfig();
}
Expand Down Expand Up @@ -186,9 +190,18 @@ class FluentTyper {
logger.info("Destroying content script instance");
this.hostChangeWatcher.stop();
this.disable();
window.removeEventListener("message", this.boundEarlyTabAcceptHandler);
chrome.runtime.onMessage.removeListener(this.boundMessageHandler);
}

handleEarlyTabAccept(event: MessageEvent): void {
if (!isEarlyTabAcceptMessage(event.data)) {
return;
}

this.runtimeController.handleEarlyTabAcceptRequest(event.data.entryId);
}

messageHandler(
message: Message | null,
sender?: chrome.runtime.MessageSender,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export const EARLY_TAB_ACCEPT_REQUEST_EVENT = "ft-early-tab-accept-request";
export const EARLY_TAB_ACCEPT_MAIN_WORLD_FLAG = "__ftEarlyTabAcceptBridgeInstalled";
export const EARLY_TAB_ACCEPT_ENTRY_ID_ATTR = "data-ft-suggestion-id";
export const EARLY_TAB_ACCEPT_ENABLED_ATTR = "data-ft-autocomplete-on-tab";
export const EARLY_TAB_ACCEPT_BRIDGE_TARGET_ATTR = "data-ft-early-tab-bridge";
export const EARLY_TAB_ACCEPT_MESSAGE_TYPE = "ft-early-tab-accept-message";

export interface EarlyTabAcceptMessage {
source: typeof EARLY_TAB_ACCEPT_REQUEST_EVENT;
type: typeof EARLY_TAB_ACCEPT_MESSAGE_TYPE;
entryId: string;
}

export function isEarlyTabAcceptMessage(value: unknown): value is EarlyTabAcceptMessage {
if (!value || typeof value !== "object") {
return false;
}

const candidate = value as Partial<EarlyTabAcceptMessage>;
return (
candidate.source === EARLY_TAB_ACCEPT_REQUEST_EVENT &&
candidate.type === EARLY_TAB_ACCEPT_MESSAGE_TYPE &&
typeof candidate.entryId === "string"
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import {
EARLY_TAB_ACCEPT_BRIDGE_TARGET_ATTR,
EARLY_TAB_ACCEPT_ENABLED_ATTR,
EARLY_TAB_ACCEPT_ENTRY_ID_ATTR,
EARLY_TAB_ACCEPT_MAIN_WORLD_FLAG,
EARLY_TAB_ACCEPT_MESSAGE_TYPE,
EARLY_TAB_ACCEPT_REQUEST_EVENT,
} from "./EarlyTabAcceptBridgeProtocol";

type FluentTyperManagedElement = HTMLElement;
type FluentTyperBridgeWindow = Window & {
[EARLY_TAB_ACCEPT_MAIN_WORLD_FLAG]?: boolean;
__ftEarlyTabAcceptBridgeKeydownHandler?: (event: KeyboardEvent) => void;
};

function resolveSuggestionMenu(
element: FluentTyperManagedElement,
doc: Document,
): HTMLElement | null {
const entryId = element.getAttribute(EARLY_TAB_ACCEPT_ENTRY_ID_ATTR);
if (!entryId) {
return null;
}

const menu = doc.querySelector(
`[data-ft-suggestion-role="menu"][${EARLY_TAB_ACCEPT_ENTRY_ID_ATTR}="${entryId}"]`,
);
return menu instanceof HTMLElement ? menu : null;
}

function hasVisibleSuggestionMenu(element: FluentTyperManagedElement, doc: Document): boolean {
const menu = resolveSuggestionMenu(element, doc);
return menu instanceof HTMLElement && menu.isConnected && menu.style.display !== "none";
}

function isManagedSuggestionTarget(
element: HTMLElement | null,
doc: Document,
): element is FluentTyperManagedElement {
return (
element instanceof HTMLElement &&
element.getAttribute("data-suggestion") === "true" &&
element.getAttribute(EARLY_TAB_ACCEPT_ENABLED_ATTR) === "true" &&
element.getAttribute(EARLY_TAB_ACCEPT_BRIDGE_TARGET_ATTR) === "true" &&
hasVisibleSuggestionMenu(element, doc)
);
}

function findManagedSuggestionTarget(
start: HTMLElement | null,
doc: Document,
): FluentTyperManagedElement | null {
let current: Node | null = start;
while (current) {
if (current instanceof HTMLElement && isManagedSuggestionTarget(current, doc)) {
return current;
}
current = current.parentNode;
}
return null;
}

function resolveManagedSuggestionTarget(
event: KeyboardEvent,
doc: Document,
): FluentTyperManagedElement | null {
const path = typeof event.composedPath === "function" ? event.composedPath() : [event.target];
for (const node of path) {
if (node instanceof HTMLElement) {
const match = findManagedSuggestionTarget(node, doc);
if (match) {
return match;
}
}
}

const activeElement = doc.activeElement;
return activeElement instanceof HTMLElement
? findManagedSuggestionTarget(activeElement, doc)
: null;
}

export function installEarlyTabAcceptMainWorldBridge(doc: Document = document): void {
const win = doc.defaultView;
if (!win) {
return;
}
const bridgeWindow = win as FluentTyperBridgeWindow;
if (bridgeWindow[EARLY_TAB_ACCEPT_MAIN_WORLD_FLAG]) {
return;
}

bridgeWindow[EARLY_TAB_ACCEPT_MAIN_WORLD_FLAG] = true;

const handler = (event: KeyboardEvent) => {
if (
event.defaultPrevented ||
event.key !== "Tab" ||
event.shiftKey ||
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.isComposing
) {
return;
}

const target = resolveManagedSuggestionTarget(event, doc);
if (!target) {
return;
}

const entryId = target.getAttribute(EARLY_TAB_ACCEPT_ENTRY_ID_ATTR);
if (!entryId) {
return;
}

win.postMessage(
{
source: EARLY_TAB_ACCEPT_REQUEST_EVENT,
type: EARLY_TAB_ACCEPT_MESSAGE_TYPE,
entryId,
},
"*",
);
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
};
bridgeWindow.__ftEarlyTabAcceptBridgeKeydownHandler = handler;

win.addEventListener("keydown", handler, true);
}

export function resetEarlyTabAcceptMainWorldBridgeForTests(doc: Document = document): void {
const win = doc.defaultView as FluentTyperBridgeWindow | null;
if (!win) {
return;
}

const handler = win.__ftEarlyTabAcceptBridgeKeydownHandler;
if (handler) {
win.removeEventListener("keydown", handler, true);
delete win.__ftEarlyTabAcceptBridgeKeydownHandler;
}

if (win[EARLY_TAB_ACCEPT_MAIN_WORLD_FLAG]) {
delete win[EARLY_TAB_ACCEPT_MAIN_WORLD_FLAG];
}
}

export {
EARLY_TAB_ACCEPT_BRIDGE_TARGET_ATTR,
EARLY_TAB_ACCEPT_ENABLED_ATTR,
EARLY_TAB_ACCEPT_ENTRY_ID_ATTR,
EARLY_TAB_ACCEPT_MESSAGE_TYPE,
EARLY_TAB_ACCEPT_REQUEST_EVENT,
} from "./EarlyTabAcceptBridgeProtocol";
Original file line number Diff line number Diff line change
Expand Up @@ -432,16 +432,16 @@ export class SuggestionEntrySession {
controls.dismissEntry();
}

public acceptSuggestionAtIndex(index: number): void {
public acceptSuggestionAtIndex(index: number): boolean {
const suggestion = this.entry.suggestions[index];
if (!suggestion) {
return;
return false;
}
this.acceptSuggestion(suggestion);
return this.acceptSuggestion(suggestion);
}

public acceptSuggestion(suggestion: string): void {
this.acceptSuggestionInternal(suggestion);
public acceptSuggestion(suggestion: string): boolean {
return this.acceptSuggestionInternal(suggestion);
}

public reconcileSelection(controls: { dismissEntry: () => void }): void {
Expand Down Expand Up @@ -1187,19 +1187,20 @@ export class SuggestionEntrySession {
return true;
}

private acceptSuggestionInternal(suggestion: string): void {
private acceptSuggestionInternal(suggestion: string): boolean {
this.entry.suppressNextSuggestionInputPrediction = true;
const accepted = this.textEditService.acceptSuggestion(this.entry, suggestion);
if (!accepted) {
this.entry.suppressNextSuggestionInputPrediction = false;
return;
return false;
}
this.finishAcceptedSuggestion(
accepted.triggerText,
accepted.insertedText,
accepted.cursorAfter,
accepted.cursorAfterIsBlockLocal,
);
return true;
}

private finishAcceptedSuggestion(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ interface SuggestionKeyboardHandlerOptions {
clearSuggestions: (entry: SuggestionEntry) => void;
isMenuVisible: (entry: SuggestionEntry) => boolean;
updateSelectionHighlight: (entry: SuggestionEntry) => void;
acceptSuggestion: (entry: SuggestionEntry, suggestion: string) => void;
acceptSuggestionAtIndex: (entry: SuggestionEntry, index: number) => void;
acceptSuggestion: (entry: SuggestionEntry, suggestion: string) => boolean;
acceptSuggestionAtIndex: (entry: SuggestionEntry, index: number) => boolean;
requestInlineSuggestion: (entry: SuggestionEntry) => void;
}

Expand All @@ -38,8 +38,8 @@ export class SuggestionKeyboardHandler {
private readonly clearSuggestions: (entry: SuggestionEntry) => void;
private readonly isMenuVisible: (entry: SuggestionEntry) => boolean;
private readonly updateSelectionHighlight: (entry: SuggestionEntry) => void;
private readonly acceptSuggestion: (entry: SuggestionEntry, suggestion: string) => void;
private readonly acceptSuggestionAtIndex: (entry: SuggestionEntry, index: number) => void;
private readonly acceptSuggestion: (entry: SuggestionEntry, suggestion: string) => boolean;
private readonly acceptSuggestionAtIndex: (entry: SuggestionEntry, index: number) => boolean;
private readonly requestInlineSuggestion: (entry: SuggestionEntry) => void;

constructor(options: SuggestionKeyboardHandlerOptions) {
Expand Down
Loading
Loading