// Copyright 2026 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import { debugLog, DebugLogTag, log, warnLog } from './logging.js';
const FILE = 'PageContextManager';
export var PageContextChangeType;
(function (PageContextChangeType) {
    PageContextChangeType["UPDATE_CURRENT"] = "update_current";
    PageContextChangeType["NEW_PAGE"] = "new_page";
})(PageContextChangeType || (PageContextChangeType = {}));
// Some pages fire load before real content is actually rendered. Try to avoid
// considering such pages as having content.
function isNonEmpty(str) {
    const kMinimumContentThreshold = 100;
    if (!str) {
        return false;
    }
    // Consider only alphanumeric characters to look for real content.
    return str.replace(/[^a-zA-Z0-9]/g, '').length > kMinimumContentThreshold;
}
/**
 * PageContextManager maintains state about the current page context as
 * provided by the browser.
 */
export class PageContextManager {
    /**
     * Context for the current page. The object is replaced with a new one
     * whenever the current page is navigated to a new document. Content updates
     * to the current document are done in-place.
     */
    context = null;
    listeners = [];
    constructor() { }
    get pageContext() {
        return this.context;
    }
    registerListener(listener) {
        this.listeners.push(listener);
    }
    updateCurrentPageContext(title, content) {
        log(FILE, 'updateCurrentPageContext', title);
        debugLog(FILE, DebugLogTag.PAGE_CONTENT, 'PageContextManager: Update', title, content);
        if (!this.context) {
            warnLog(FILE, 'updateCurrentPageContext called without context');
            return;
        }
        const oldContext = { ...this.context };
        this.context.title = title;
        this.context.content = content;
        this.context.hasHadContent ||= isNonEmpty(content);
        for (const listener of this.listeners) {
            const event = {
                type: PageContextChangeType.UPDATE_CURRENT,
                newContext: { ...this.context },
                oldContext,
            };
            listener(event);
        }
    }
    createNewPageContext(url, title, content) {
        log(FILE, 'CreateNewPageContext', title, url);
        debugLog(FILE, DebugLogTag.PAGE_CONTENT, 'Content', content);
        const oldContext = this.context ? { ...this.context } : null;
        this.context = { url, title, content, hasHadContent: isNonEmpty(content) };
        for (const listener of this.listeners) {
            const event = {
                type: PageContextChangeType.NEW_PAGE,
                newContext: { ...this.context },
                oldContext,
            };
            listener(event);
        }
    }
}
