import { Toolbar } from '../../extensions/toolbar' import { isString, isUndefined } from '@posthog/core' import { PostHog } from '../../posthog-core' import { ToolbarParams } from '../../types' import { window } from '@posthog/browser-common/utils/globals' import { assignableWindow } from '../../utils/globals' import { RequestRouter } from '../../utils/request-router' import { TOOLBAR_ID } from '@posthog/browser-common/constants' import { createMockPostHog, createMockConfig } from '../helpers/posthog-instance' const makeToolbarParams = (overrides: Partial): ToolbarParams => ({ token: 'test_token', ...overrides, }) describe('Toolbar', () => { let toolbar: Toolbar let instance: PostHog const toolbarParams = makeToolbarParams({}) beforeEach(() => { delete assignableWindow.ph_toolbar_state window.localStorage.removeItem('_postHogToolbarParams') instance = createMockPostHog({ config: createMockConfig({ api_host: 'http://api.example.com', token: 'test_token', }), set_config: vi.fn(), }) instance.requestRouter = new RequestRouter(instance) assignableWindow.__PosthogExtensions__ = { loadExternalDependency: vi.fn((_ph, _path: any, callback: any) => callback()), } toolbar = new Toolbar(instance) }) beforeEach(() => { if (document.getElementById(TOOLBAR_ID)) { document.body.removeChild(document.getElementById(TOOLBAR_ID)!) } assignableWindow.ph_load_toolbar = vi.fn(() => { const mockToolbarElement = document.createElement('div') mockToolbarElement.setAttribute('id', TOOLBAR_ID) document.body.appendChild(mockToolbarElement) }) }) describe('maybeLoadToolbar', () => { const localStorage = { getItem: vi.fn(), setItem: vi.fn(), } const storage = localStorage as unknown as Storage const history = { replaceState: vi.fn() } as unknown as History const defaultHashState = { action: 'ph_authorize', desiredHash: '#myhash', projectId: 3, projectOwnerId: 722725, readOnly: false, token: 'test_token', userFlags: { flag_1: 0, flag_2: 1, }, userId: 12345, } const withHashParamsFrom = ( hashState: Record | string = defaultHashState, key: string = 'state' ) => ({ access_token: 'access token', [key]: encodeURIComponent(isString(hashState) ? hashState : JSON.stringify(hashState)), expires_in: 3600, }) const withHash = (hashParams: Record) => { return Object.keys(hashParams) .map((k) => `${k}=${hashParams[k]}`) .join('&') } const aLocation = (hash?: string): Location => { if (isUndefined(hash)) { hash = withHash(withHashParamsFrom()) } return { hash: `#${hash}`, pathname: 'pathname', search: '?search', } as Location } beforeEach(() => { localStorage.getItem.mockImplementation(() => {}) vi.spyOn(toolbar, 'loadToolbar') }) it('should initialize the toolbar when the hash state contains action "ph_authorize"', () => { // the default hash state in the test setup contains the action "ph_authorize" toolbar.maybeLoadToolbar(aLocation(), storage, history) expect(toolbar.loadToolbar).toHaveBeenCalledWith({ ...toolbarParams, ...defaultHashState, source: 'url', }) }) it('should initialize the toolbar when there are editor params in the session', () => { // if the hash state does not contain ph_authorize then look in storage localStorage.getItem.mockImplementation(() => JSON.stringify(toolbarParams)) const hashState = { ...defaultHashState, action: undefined } toolbar.maybeLoadToolbar(aLocation(withHash(withHashParamsFrom(hashState))), storage, history) expect(toolbar.loadToolbar).toHaveBeenCalledWith({ ...toolbarParams, source: 'localstorage', }) }) it('should NOT initialize the toolbar when the activation query param does not exist', () => { expect(toolbar.maybeLoadToolbar(aLocation(''), storage, history)).toEqual(false) expect(toolbar.loadToolbar).not.toHaveBeenCalled() }) it('should return false when parsing invalid JSON from fragment state', () => { expect( toolbar.maybeLoadToolbar(aLocation(withHash(withHashParamsFrom('literally'))), storage, history) ).toEqual(false) expect(toolbar.loadToolbar).not.toHaveBeenCalled() }) it('should work if calling toolbar params `__posthog`', () => { toolbar.maybeLoadToolbar( aLocation(withHash(withHashParamsFrom(defaultHashState, '__posthog'))), storage, history ) expect(toolbar.loadToolbar).toHaveBeenCalledWith({ ...toolbarParams, ...defaultHashState, source: 'url' }) }) it('should use the apiURL in the hash if available', () => { toolbar.maybeLoadToolbar( aLocation(withHash(withHashParamsFrom({ ...defaultHashState, apiURL: 'blabla' }))), storage, history ) expect(toolbar.loadToolbar).toHaveBeenCalledWith({ ...toolbarParams, ...defaultHashState, apiURL: 'blabla', source: 'url', }) }) }) describe('load and close toolbar', () => { it('should persist for next time', () => { expect(toolbar.loadToolbar(toolbarParams)).toBe(true) expect(JSON.parse(window.localStorage.getItem('_postHogToolbarParams') ?? '')).toEqual({ ...toolbarParams, apiURL: 'http://api.example.com', }) }) it('should load if not previously loaded', () => { const loader = vi.mocked(assignableWindow.__PosthogExtensions__!.loadExternalDependency) loader.mockImplementation(() => {}) expect(toolbar.loadToolbar(toolbarParams)).toBe(true) expect(loader).toHaveBeenCalledWith(instance, 'toolbar', expect.any(Function)) expect(assignableWindow.ph_load_toolbar).not.toHaveBeenCalled() loader.mock.calls[0][2]() expect(assignableWindow.ph_load_toolbar).toHaveBeenCalledWith( { ...toolbarParams, apiURL: 'http://api.example.com' }, instance ) }) it('should NOT load if previously loaded', () => { expect(toolbar.loadToolbar(toolbarParams)).toBe(true) expect(toolbar.loadToolbar(toolbarParams)).toBe(false) }) it('should load if previously loaded but closed', () => { expect(toolbar.loadToolbar(toolbarParams)).toBe(true) expect(toolbar.loadToolbar(toolbarParams)).toBe(false) document.body.removeChild(document.getElementById(TOOLBAR_ID)!) expect(toolbar.loadToolbar(toolbarParams)).toBe(true) }) }) describe('load and close toolbar with minimal params', () => { const minimalToolbarParams: ToolbarParams = { token: 'accessToken', } it('should load if not previously loaded', () => { expect(toolbar.loadToolbar(minimalToolbarParams)).toBe(true) expect(assignableWindow.ph_load_toolbar).toHaveBeenCalledWith( { ...minimalToolbarParams, apiURL: 'http://api.example.com', token: 'accessToken', }, instance ) }) it('should NOT load if previously loaded', () => { expect(toolbar.loadToolbar(minimalToolbarParams)).toBe(true) expect(toolbar.loadToolbar(minimalToolbarParams)).toBe(false) }) }) })