Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(analytics): use new analytics events (#2105)

dev-rbf1e340f3be01
diff --git a/js/app/packages/app/component/GlobalHotkeys.tsx b/js/app/packages/app/component/GlobalHotkeys.tsx
index ed5a7a25e0..be2b7b6733 100644
--- a/js/app/packages/app/component/GlobalHotkeys.tsx
+++ b/js/app/packages/app/component/GlobalHotkeys.tsx
@@ -20,7 +20,11 @@ import {
import { applyTheme } from '../../block-theme/utils/themeUtils';
import { globalSplitManager } from '../signal/splitLayout';
import { CommandState } from './command';
-import { CREATABLE_BLOCKS, setCreateMenuOpen } from './Launcher';
+import {
+ CREATABLE_BLOCKS,
+ createMenuOpen,
+ setCreateMenuOpen,
+} from './Launcher';
import { useSplitLayout } from './split-layout/layout';
import {
openFilePicker,
@@ -29,15 +33,45 @@ import {
} from '@core/util/upload';
import { useHandleFileUpload } from '@app/util/handleFileUpload';
import Upload from '@icon/regular/upload.svg';
+import { useAnalytics } from '@app/component/analytics-context';
+import { useSubscribeToKeypress } from '@app/signal/hotkeyRoot';
+
+function useHotkeyAnalytics(): void {
+ const analytics = useAnalytics();
+
+ useSubscribeToKeypress((context) => {
+ // Only track when a command was actually executed
+ if (!context.commandCaptured) return;
+
+ const command = context.commandCaptured;
+ const description =
+ typeof command.description === 'function'
+ ? command.description()
+ : command.description;
+
+ analytics.track('hotkey_use', {
+ action: description,
+ token: command.hotkeyToken,
+ });
+ });
+}
export default function GlobalShortcuts() {
const canFit = () => globalSplitManager()?.canAppendSplit() ?? true;
+
+ const analytics = useAnalytics();
+
+ useHotkeyAnalytics();
+
const { toggleSettings, openSettings } = useSettingsState();
const logout = useLogout();
const handleFileUpload = useHandleFileUpload();
const handleCommandMenu = () => {
+ if (!CommandState.isOpen()) {
+ analytics.track('command_menu_open', { from: 'global_hotkey' });
+ }
CommandState.toggle();
};
@@ -47,6 +81,12 @@ export default function GlobalShortcuts() {
scopeId: 'global',
description: 'Create',
keyDownHandler: () => {
+ const willOpen = !createMenuOpen();
+
+ if (willOpen) {
+ analytics.track('create_menu_open', { from: 'global_hotkey' });
+ }
+
setCreateMenuOpen((prev) => !prev);
return true;
},
@@ -102,6 +142,7 @@ export default function GlobalShortcuts() {
const { openWithSplit } = useSplitLayout();
const createNewSplit = () => {
+ analytics.track('split_created', { from: 'global_hotkey' });
openWithSplit(
{ type: 'component', id: 'inbox' },
{
@@ -195,6 +236,7 @@ export default function GlobalShortcuts() {
description: `${theme.name}`,
keyDownHandler: () => {
applyTheme(theme.id);
+ analytics.track('theme_changed', { themeId: theme.id });
return true;
},
runWithInputFocused: true,
@@ -217,6 +259,7 @@ export default function GlobalShortcuts() {
description: `${theme.name}`,
keyDownHandler: () => {
setLightModeTheme(theme.id);
+ analytics.track('theme_changed', { themeId: theme.id });
return true;
},
runWithInputFocused: true,
@@ -239,6 +282,7 @@ export default function GlobalShortcuts() {
description: `${theme.name}`,
keyDownHandler: () => {
setDarkModeTheme(theme.id);
+ analytics.track('theme_changed', { themeId: theme.id });
return true;
},
runWithInputFocused: true,
diff --git a/js/app/packages/app/component/Launcher.tsx b/js/app/packages/app/component/Launcher.tsx
index 6d441fe1fb..979abf4fcf 100644
--- a/js/app/packages/app/component/Launcher.tsx
+++ b/js/app/packages/app/component/Launcher.tsx
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import type { BlockAlias, BlockName } from '@core/block';
import { getIconConfig } from '@core/component/EntityIcon';
import { Hotkey } from '@core/component/Hotkey';
@@ -66,6 +67,11 @@ const createBlock = async (spec: {
const id = await createFn();
if (!id) return;
+ analytics.track('create_entity', {
+ entityType: blockName,
+ source: 'launcher',
+ });
+
const block = { type: blockName, id };
openWithSplit(block, {
@@ -89,6 +95,11 @@ const createBlock = async (spec: {
return;
}
+ analytics.track('create_entity', {
+ entityType: blockName,
+ source: 'launcher',
+ });
+
if (split)
split.replace({
next: { type: blockName, id },
diff --git a/js/app/packages/app/component/Onboarding.tsx b/js/app/packages/app/component/Onboarding.tsx
index 6adab576bd..87e2e4b533 100644
--- a/js/app/packages/app/component/Onboarding.tsx
+++ b/js/app/packages/app/component/Onboarding.tsx
@@ -1,5 +1,5 @@
+import { useAnalytics } from '@app/component/analytics-context';
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
-import { withAnalytics } from '@coparse/analytics';
import { updateUserAuth, useIsAuthenticated } from '@core/auth';
import { useHasPaidAccess } from '@core/auth/license';
import { ActionSequence } from '@core/component/FormControls/ActionSequence';
@@ -12,7 +12,7 @@ import { useNavigate, useSearchParams } from '@solidjs/router';
import { createEffect, onCleanup, Show } from 'solid-js';
export default function Onboarding() {
- const { track, TrackingEvents } = withAnalytics();
+ const analytics = useAnalytics();
const authenticated = useIsAuthenticated();
const connected = useEmailLinksStatus();
@@ -39,7 +39,6 @@ export default function Onboarding() {
function complete() {
// Redirect on completion
if (localStorage.getItem('new_user_onboarding')) {
- track(TrackingEvents.ONBOARDING.COMPLETE);
localStorage.removeItem('new_user_onboarding');
}
return navigate(DEFAULT_ROUTE);
@@ -60,7 +59,7 @@ export default function Onboarding() {
createEffect(() => {
const subscriptionSuccess = searchParams.subscriptionSuccess;
if (subscriptionSuccess === 'true') {
- track(TrackingEvents.ONBOARDING.SUBSCRIBE.CHECKOUT_SUCCESS);
+ analytics.track('subscription_success');
updateUserInfo();
}
});
@@ -98,27 +97,26 @@ export default function Onboarding() {
// ALSO AUTHS!
const connectInbox = async () => {
- track(TrackingEvents.ONBOARDING.GMAIL.CONNECT_START);
try {
await connectEmail();
} catch (error) {
- track(TrackingEvents.ONBOARDING.GMAIL.CONNECT_FAILURE, { ...error });
console.error(error);
}
- if (connected()) track(TrackingEvents.ONBOARDING.GMAIL.CONNECT_SUCCESS);
await updateUserAuth();
if (subscribed()) complete();
};
const handlePayment = async () => {
try {
- track(TrackingEvents.ONBOARDING.SUBSCRIBE.CHECKOUT_START);
+ analytics.track('subscription_start', {
+ type: 'new_subscription',
+ customType: 'New subscription',
+ });
const url =
await stripeServiceClient.createCheckoutSession('New subscription');
window.location.href = url;
} catch (error) {
- track(TrackingEvents.ONBOARDING.SUBSCRIBE.CHECKOUT_FAILURE, { ...error });
console.error(error);
}
};
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index 535c57bd3e..a3f1077e8a 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -454,8 +454,8 @@ export function Root() {
return (
<MaybeTauriProvider>
<MetaProvider>
- <PosthogProvider>
- <AnalyticsContextProvider>
+ <AnalyticsContextProvider>
+ <PosthogProvider>
<EntityProvider>
<UserContextProvider>
<QuerySyncProviderWithUserId />
@@ -492,8 +492,8 @@ export function Root() {
</ConfiguredGlobalAppStateProvider>
</UserContextProvider>
</EntityProvider>
- </AnalyticsContextProvider>
- </PosthogProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
</MetaProvider>
</MaybeTauriProvider>
);
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsx
index a04aa2151e..9809129534 100644
--- a/js/app/packages/app/component/SoupChatInput.tsx
+++ b/js/app/packages/app/component/SoupChatInput.tsx
@@ -1,5 +1,5 @@
import { useSoup } from '@app/component/next-soup/soup-context';
-import { withAnalytics } from '@coparse/analytics';
+import { useAnalytics } from '@app/component/analytics-context';
import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
import {
@@ -23,9 +23,8 @@ import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
import { onMount, Show } from 'solid-js';
import { useSplitPanelOrThrow } from './split-layout/layoutUtils';
-const { track, TrackingEvents } = withAnalytics();
-
function SoupChatInputInner() {
+ const analytics = useAnalytics();
let containerRef!: HTMLDivElement;
const splitPanelContext = useSplitPanelOrThrow();
const soup = useSoup();
@@ -35,7 +34,7 @@ function SoupChatInputInner() {
const editor = buildChatEditor().withMentions({
onCreate: (mention) => {
- track(TrackingEvents.CHAT.MENTION.SELECT);
+ analytics.track('mentions_menu_use', { itemType: 'chat' });
const attachment = getAttachmentFromMention(mention);
if (attachment) input.attachments.addAttachment(attachment);
},
diff --git a/js/app/packages/app/component/analytics-context.tsx b/js/app/packages/app/component/analytics-context.tsx
index 27958737fe..9d076bab7e 100644
--- a/js/app/packages/app/component/analytics-context.tsx
+++ b/js/app/packages/app/component/analytics-context.tsx
@@ -1,12 +1,10 @@
-import { createAnalytics } from '@app/lib/analytics';
-import type { AnalyticsInterface } from '@app/lib/analytics/analytics';
+import {
+ analytics,
+ type AnalyticsInterface,
+} from '@app/lib/analytics/analytics';
import { createAssertedContextProvider } from '@core/context/createContext';
export const [AnalyticsContextProvider, useAnalytics] =
createAssertedContextProvider<AnalyticsInterface>('analytics', () => {
- const analytics = createAnalytics({
- disabled: import.meta.env.DEV,
- });
-
return analytics;
});
diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsx
index 377d3b7bdd..37944f194f 100644
--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx
+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx
@@ -21,7 +21,7 @@ import {
type ListView,
} from '@app/constants/list-views';
import { LabelAndHotKey } from '@core/component/Tooltip';
-import { setCreateMenuOpen } from '@app/component/Launcher';
+import { createMenuOpen, setCreateMenuOpen } from '@app/component/Launcher';
import { CommandState } from '@app/component/command';
import { cn } from '@ui/utils/classname';
import { Button } from '@ui/components/Button';
@@ -37,6 +37,7 @@ import { ContextMenu } from '@kobalte/core/context-menu';
import { TOKENS } from '@core/hotkey/tokens';
import { Hotkey } from '@core/component/Hotkey';
+import { useAnalytics } from '@app/component/analytics-context';
import type { HotkeyToken } from '@core/hotkey/tokens';
interface SidebarItem {
@@ -238,14 +239,22 @@ const SidebarActionButton = (props: SidebarActionButtonProps) => {
};
export const AppSidebar = (props: AppSidebarProps) => {
+ const analytics = useAnalytics();
const layout = useSplitLayout();
const { toggleSettings } = useSettingsState();
const handleCommandPaletteClick = () => {
+ if (!CommandState.isOpen()) {
+ analytics.track('command_menu_open', { from: 'sidebar' });
+ }
CommandState.toggle();
};
const handleCreateClick = () => {
+ const willOpen = !createMenuOpen();
+ if (willOpen) {
+ analytics.track('create_menu_open', { from: 'sidebar' });
+ }
setCreateMenuOpen((p) => !p);
};
@@ -256,6 +265,7 @@ export const AppSidebar = (props: AppSidebarProps) => {
const manager = globalSplitManager();
if (!manager || !manager.canAppendSplit()) return;
+ analytics.track('split_created', { from: 'sidebar' });
manager.createNewSplit({
content: {
type: 'component',
@@ -401,6 +411,7 @@ interface SidebarLinkProps extends SidebarItem {
const SidebarLink = (props: SidebarLinkProps) => {
const [isHovering, setIsHovering] = createSignal(false);
+ const analytics = useAnalytics();
const layout = useSplitLayout();
const layoutManager = globalSplitManager();
@@ -439,6 +450,8 @@ const SidebarLink = (props: SidebarLinkProps) => {
const manager = globalSplitManager();
if (!manager || !manager.canAppendSplit()) return;
+ analytics.track('split_created', { from: 'sidebar' });
+
manager.createNewSplit({
content: content(),
activate: true,
@@ -482,6 +495,9 @@ const SidebarLink = (props: SidebarLinkProps) => {
}
onMouseLeave={() => setIsHovering(false)}
onClick={(e) => {
+ analytics.track('sidebar_click', {
+ view: props.id,
+ });
// Middle mouse handling
if (e.button === 1) return;
diff --git a/js/app/packages/app/component/command/CommandMenu.tsx b/js/app/packages/app/component/command/CommandMenu.tsx
index 0f75536140..95ac59bdbd 100644
--- a/js/app/packages/app/component/command/CommandMenu.tsx
+++ b/js/app/packages/app/component/command/CommandMenu.tsx
@@ -35,6 +35,7 @@ import { Hotkey } from '@core/component/Hotkey';
import { InlineEntity, type EntityData } from '@entity';
import { globalSplitManager } from '@app/signal/splitLayout';
import { isListViewID } from '@app/constants/list-views';
+import { useAnalytics } from '@app/component/analytics-context';
const CATEGORIES: { id: CategoryFilter; label: string }[] = [
{ id: 'all', label: 'All' },
@@ -96,6 +97,8 @@ export function CommandMenuInner(props: {
/** Override items source with custom data (e.g. sandbox entities for tutorial) */
items?: () => CommandMenuItem[];
}) {
+ const analytics = useAnalytics();
+
const { openWithSplit } = useSplitLayout();
const [attachHotkeys, hotkeyScope] = useHotkeyDOMScope('command-menu');
@@ -130,6 +133,8 @@ export function CommandMenuInner(props: {
function handleItemAction(item: CommandMenuItem, openInNewSplit = false) {
if (!item) return;
+ analytics.track('command_menu_use', { itemType: item.bucket });
+
if (isCommandItem(item)) {
const command = item.data;
diff --git a/js/app/packages/app/component/mobile/MobileDock.tsx b/js/app/packages/app/component/mobile/MobileDock.tsx
index 5924f3083b..c688266596 100644
--- a/js/app/packages/app/component/mobile/MobileDock.tsx
+++ b/js/app/packages/app/component/mobile/MobileDock.tsx
@@ -19,6 +19,7 @@ import { SearchState } from './mobileSearchState';
import { useSettingsState } from '@core/constant/SettingsState';
import { setCreateMenuOpen } from '../Launcher';
import { useLocation } from '@solidjs/router';
+import { useAnalytics } from '@app/component/analytics-context';
const ICON_ANIMATION_DURATION_MS = 500;
@@ -74,6 +75,7 @@ function MorePopover(props: {
isActive: (id: ListView) => boolean;
onNavigate: (id: ListView) => void;
}) {
+ const analytics = useAnalytics();
const { toggleSettings } = useSettingsState();
const [open, setOpen] = createSignal(false);
const [anchorRef, setAnchorRef] = createSignal<HTMLElement>();
@@ -98,6 +100,7 @@ function MorePopover(props: {
toggleSettings();
setOpen(false);
} else if (id === 'create') {
+ analytics.track('create_menu_open', { from: 'mobile_dock' });
setCreateMenuOpen(true);
setOpen(false);
} else if (isListViewID(id)) {
@@ -161,6 +164,7 @@ function MorePopover(props: {
)}
onClick={() => {
impactFeedback('light');
+ analytics.track('create_menu_open', { from: 'mobile_dock' });
setCreateMenuOpen(true);
setOpen(false);
}}
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx
index acbe4cfe42..8d50542c4b 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-filters-bar.tsx
@@ -11,6 +11,7 @@ import { Button } from './button';
import { AnimatedPreviewIcon } from '@macro-icons/wide/animating/preview';
import { useSoup } from '../../soup-context';
import { registerHotkey } from '@core/hotkey/hotkeys';
+import { useAnalytics } from '@app/component/analytics-context';
export const SoupFiltersBar = () => {
const {
@@ -20,6 +21,9 @@ export const SoupFiltersBar = () => {
replaceFilter,
isOptionActive,
} = useFilterRefinements();
+
+ const analytics = useAnalytics();
+
const [previewBtnHovering, setPreviewBtnHovering] = createSignal(false);
const soup = useSoup();
@@ -36,6 +40,7 @@ export const SoupFiltersBar = () => {
if (!focused) return;
+ analytics.track('preview_panel_use');
soup.setPreviewEntity(focused);
};
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
index e707cc9870..63660c58ed 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-actions-menu.tsx
@@ -15,6 +15,7 @@ import {
} from '../actions';
import type { SoupState } from '../create-soup-state';
import { useUserId } from '@core/context/user';
+import { useAnalytics } from '@app/component/analytics-context';
interface SoupEntityActionsMenuProps {
entities: EntityData[];
@@ -23,6 +24,8 @@ interface SoupEntityActionsMenuProps {
}
export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
+ const analytics = useAnalytics();
+
const userId = useUserId();
const notificationSource = useGlobalNotificationSource();
@@ -77,6 +80,8 @@ export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {
const splitManager = globalSplitManager();
if (!splitManager) return;
+ analytics.track('split_created', { from: 'soup_view_entity_actions_menu' });
+
if (entity.type === 'document') {
const { fileType, id, subType } = entity;
splitManager.createNewSplit({
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx
index d59ed7ec0a..afdeddf48b 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-entity-selection-toolbar.tsx
@@ -1,3 +1,4 @@
+import { useAnalytics } from '@app/component/analytics-context';
import { CommandState } from '@app/component/command/state';
import { EntitySelectionToolbarModal } from '@app/component/EntitySelectionToolbarModal';
import type { EntityData } from '@entity';
@@ -11,6 +12,8 @@ interface SoupEntitySelectionToolbarProps {
export const SoupEntitySelectionToolbar = (
props: SoupEntitySelectionToolbarProps
) => {
+ const analytics = useAnalytics();
+
return (
<EntitySelectionToolbarModal
multiSelectEntities={props.selected}
@@ -22,6 +25,9 @@ export const SoupEntitySelectionToolbar = (
return;
}
+ analytics.track('command_menu_open', {
+ from: 'soup_view_selection_toolbar',
+ });
// Open the command menu in entity action mode, which shows only
// selection modification commands with a preview of the selected entities
CommandState.openForEntityAction(selected);
diff --git a/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts
index 1a9d14e2c0..c29ef2c0b3 100644
--- a/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts
@@ -17,6 +17,7 @@ import type { SoupState } from '../create-soup-state';
import { openEntityInSplitFromUnifiedList } from '@app/component/next-soup/utils';
import { isListViewID, type ListView } from '@app/constants/list-views';
import { VIEW_TAB_PRESETS } from '@app/component/app-sidebar/soup-filter-presets';
+import { useAnalytics } from '@app/component/analytics-context';
type UseSoupViewHotkeysOptions = {
splitId: string;
@@ -44,6 +45,8 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {
applyTabPreset,
} = options;
+ const analytics = useAnalytics();
+
const splitIsUnifiedList = () => isListViewID(splitHandle.content().id);
// escape - Multi-purpose: Clear selection / Close spotlight / Close split / Go home
@@ -241,9 +244,15 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {
const multiSelectEntities = soup.selection.selected();
if (multiSelectEntities.length > 0) {
+ analytics.track('command_menu_open', {
+ from: 'soup_view_entity_action',
+ });
// Open in entity action mode with selection
CommandState.openForEntityAction(multiSelectEntities.slice());
} else {
+ analytics.track('command_menu_open', {
+ from: 'soup_view',
+ });
// Normal toggle
CommandState.toggle();
}
diff --git a/js/app/packages/app/component/paywall/PaywallComponent.tsx b/js/app/packages/app/component/paywall/PaywallComponent.tsx
index 47a5607171..4997912f07 100644
--- a/js/app/packages/app/component/paywall/PaywallComponent.tsx
+++ b/js/app/packages/app/component/paywall/PaywallComponent.tsx
@@ -6,6 +6,7 @@ import Dot from '@phosphor-icons/core/regular/dot.svg?component-solid';
import { useHasTrialed } from '@core/context/user';
import { stripeServiceClient } from '@service-stripe/client';
import { createSignal, For, onMount, Show } from 'solid-js';
+import { useAnalytics } from '@app/component/analytics-context';
const guestFeatures = [
'Limited to 10 files and 10 AI messages',
@@ -30,6 +31,8 @@ interface PaywallComponent {
}
const PaywallComponent = (props: PaywallComponent) => {
+ const analytics = useAnalytics();
+
const hasTrialedQuery = useHasTrialed();
const [hasTrialed, setHasTrialed] = createSignal(false);
const [selectedPlan, setSelectedPlan] = createSignal<'guest' | 'member'>(
@@ -49,6 +52,11 @@ const PaywallComponent = (props: PaywallComponent) => {
const url = await stripeServiceClient.createCheckoutSession(
props.customType ? props.customType : (props.errorKey ?? undefined)
);
+ analytics.track('subscription_start', {
+ type: 'early_member',
+ customType: props.customType,
+ errorKey: props.errorKey,
+ });
window.location.href = url;
} catch (error) {
console.error(error);
diff --git a/js/app/packages/app/component/settings/Account.tsx b/js/app/packages/app/component/settings/Account.tsx
index 530c294ba0..94fc204780 100644
--- a/js/app/packages/app/component/settings/Account.tsx
+++ b/js/app/packages/app/component/settings/Account.tsx
@@ -40,6 +40,7 @@ import {
type SupportedNotificationSettings,
useNotificationSettings,
} from '@notifications';
+import { useAnalytics } from '@app/component/analytics-context';
// NOTE: solid directives
false && fileSelector;
@@ -350,13 +351,21 @@ function NotificationToggle() {
function NotificationSettings(props: {
settings: SupportedNotificationSettings;
}) {
+ const analytics = useAnalytics()
+
+ const handleToggle = () => {
+ analytics.track('notifications_toggled')
+ props.settings.toggle(!props.settings.isEnabled())
+ }
+
+
return (
<div class="flex items-center justify-between mb-[18px]">
<div class="text-sm">Notifications</div>
<DeprecatedTextButton
theme="base"
text={props.settings.isEnabled() ? "Disable" : "Enable"}
- onClick={() => props.settings.toggle(!props.settings.isEnabled())}
+ onClick={handleToggle}
/>
</div>
);
diff --git a/js/app/packages/app/lib/analytics/analytics.ts b/js/app/packages/app/lib/analytics/analytics.ts
index 9b24e87feb..313637ceb9 100644
--- a/js/app/packages/app/lib/analytics/analytics.ts
+++ b/js/app/packages/app/lib/analytics/analytics.ts
@@ -1,14 +1,14 @@
import type { AppEvents, AppEventNames } from '@app/lib/analytics/app-events';
-import { usePosthog } from '@app/lib/analytics/posthog';
import {
initializeGoogleAnalytics,
initializeMetaPixel,
} from '@app/lib/analytics/providers';
+import { PostHog } from 'posthog-js';
import { match } from 'ts-pattern';
type AnalyticsProvider = 'ga' | 'meta-pixel' | 'posthog';
-const DEFAULT_ANALYTICS_PROVIDERS: AnalyticsProvider[] = [];
+const DEFAULT_ANALYTICS_PROVIDERS: AnalyticsProvider[] = ['posthog'];
type EventName = AppEventNames | (string & {});
@@ -23,37 +23,46 @@ interface UserIdentifyInfo {
os: string;
}
-interface CreateAnalyticsOptions {
- initializeOnCreate?: boolean;
- disabled?: boolean;
-}
-
const GA_ID = 'G-52HPEL3FTV';
-export const createAnalytics = (options: CreateAnalyticsOptions) => {
- const posthog = usePosthog();
+const initializePosthog = (instance: PostHog) => {
+ const key = import.meta.env.VITE_POSTHOG_API_KEY;
+ if (!key) return;
+
+ instance.init(key, {
+ api_host: 'https://analytics-proxy.macroverse.workers.dev/ingest/ph',
+ ui_host: 'https://us.posthog.com',
+ defaults: '2026-01-30',
+ });
+};
+
+const tryInitialize = (callback: VoidFunction) => {
+ try {
+ callback();
+ } catch (e) {
+ console.error('[Analytics] Failed to initialize providers:', e);
+ }
+};
+
+export const createAnalytics = () => {
+ const posthog = new PostHog();
+
+ const disabled = import.meta.env.DEV === true;
const initializeProviders = () => {
- if (options.disabled) return;
+ if (disabled) return;
- try {
- initializeGoogleAnalytics();
- initializeMetaPixel();
- } catch (e) {
- console.error('[Analytics] Failed to initialize providers:', e);
- }
+ tryInitialize(initializeGoogleAnalytics);
+ tryInitialize(initializeMetaPixel);
+ tryInitialize(() => initializePosthog(posthog));
};
- if (options.initializeOnCreate !== false && !options.disabled) {
- initializeProviders();
- }
-
const sendEvent = (
provider: AnalyticsProvider,
event: EventName,
data?: Record<string, unknown>
) => {
- if (options.disabled) return;
+ if (disabled) return;
try {
match(provider)
@@ -64,7 +73,7 @@ export const createAnalytics = (options: CreateAnalyticsOptions) => {
fbq('track', event, data ?? {});
})
.with('posthog', () => {
- posthog.instance.capture(event, data);
+ posthog.capture(event, data);
})
.exhaustive();
} catch (e) {
@@ -77,7 +86,7 @@ export const createAnalytics = (options: CreateAnalyticsOptions) => {
data?: Record<string, unknown>,
providersToSendTo: AnalyticsProvider[] = DEFAULT_ANALYTICS_PROVIDERS
) => {
- if (options.disabled) return;
+ if (disabled) return;
for (const provider of providersToSendTo) {
sendEvent(provider, event, data);
@@ -85,7 +94,7 @@ export const createAnalytics = (options: CreateAnalyticsOptions) => {
};
const identify = (userID: string, info: Partial<UserIdentifyInfo>) => {
- if (options.disabled) return;
+ if (disabled) return;
try {
gtag('config', GA_ID, {
@@ -99,25 +108,26 @@ export const createAnalytics = (options: CreateAnalyticsOptions) => {
em: info.email,
});
- posthog.instance.identify(userID, { ...info });
+ posthog.identify(userID, { ...info });
} catch (e) {
console.error('[Analytics] Failed to identify user:', e);
}
};
const reset = () => {
- if (options.disabled) return;
+ if (disabled) return;
try {
gtag('config', GA_ID, { user_id: undefined });
- posthog.instance.reset();
+ posthog.reset();
} catch (e) {
console.error('[Analytics] Failed to reset:', e);
}
};
return {
+ posthog,
initializeProviders,
track,
identify,
@@ -126,7 +136,17 @@ export const createAnalytics = (options: CreateAnalyticsOptions) => {
};
export type AnalyticsInterface = {
+ posthog: PostHog;
track: TrackFn;
identify: (userID: string, info: Partial<UserIdentifyInfo>) => void;
reset: () => void;
};
+
+/**
+ * Singleton analytics instance for use in utility functions that cannot use hooks.
+ *
+ * @deprecated **Do not use in components.** Use `useAnalytics()` hook from
+ * `@app/component/analytics-context` instead. This singleton exists only for
+ * standalone utility functions (e.g., upload.ts) that run outside Solid context.
+ */
+export const analytics = createAnalytics();
diff --git a/js/app/packages/app/lib/analytics/app-events.ts b/js/app/packages/app/lib/analytics/app-events.ts
index 124cb7c5cc..215b204292 100644
--- a/js/app/packages/app/lib/analytics/app-events.ts
+++ b/js/app/packages/app/lib/analytics/app-events.ts
@@ -13,22 +13,35 @@ export type AppEvents = {
sidebar_click: Record<string, unknown>;
notifications_toggled: Record<string, unknown>;
- references_panel_open: Record<string, unknown>;
- notifications_panel_open: Record<string, unknown>;
- properties_panel_open: Record<string, unknown>;
+ references_panel_open: { blockType: string };
+ notifications_panel_open: { blockType: string };
+ properties_panel_open: { blockType: string };
+ share_menu_open: { blockType: string };
copy_share_link: Record<string, unknown>;
download: Record<string, unknown>;
- comment: Record<string, unknown>;
- upload_file: Record<string, unknown>;
+ comment_create: { blockType: string };
+ comment_update: { blockType: string };
+ comment_delete: { blockType: string };
+ upload_file: {
+ fileType?: string;
+ fileName?: string;
+ fileSize?: number;
+ destination: 'dss' | 'static';
+ folder?: boolean;
+ };
+ upload_error: {
+ type: string;
+ destination?: 'dss' | 'static';
+ };
- command_menu_open: Record<string, unknown>;
- command_menu_use: Record<string, unknown>; // payload - selected command or item
- create_menu_open: Record<string, unknown>;
+ command_menu_open: { from: string };
+ command_menu_use: { itemType: string };
+ create_menu_open: { from: string };
hotkey_use: Record<string, unknown>;
preview_panel_use: Record<string, unknown>;
- mentions_menu_use: Record<string, unknown>;
- split_created: Record<string, unknown>;
+ mentions_menu_use: { itemType: string };
+ split_created: { from: string };
share_entity: Record<string, unknown>; // payload - entity type, location
create_entity: Record<string, unknown>; // payload - entity type
@@ -39,7 +52,7 @@ export type AppEvents = {
search: Record<string, unknown>;
- theme_changed: Record<string, unknown>;
+ theme_changed: { themeId: string };
ai_message_sent: Record<string, unknown>;
ai_attachment_add: Record<string, unknown>;
@@ -47,8 +60,10 @@ export type AppEvents = {
email_message_sent: Record<string, unknown>;
channel_message_sent: Record<string, unknown>;
- channel_reaction_sent: Record<string, unknown>;
- channel_thread_reply: Record<string, unknown>;
+ channel_reaction: {
+ emoji: string;
+ action: 'add' | 'remove';
+ };
channel_participant_add: Record<string, unknown>;
channel_participant_remove: Record<string, unknown>;
diff --git a/js/app/packages/app/lib/analytics/index.ts b/js/app/packages/app/lib/analytics/index.ts
index 3463cf4b58..6c657fc23c 100644
--- a/js/app/packages/app/lib/analytics/index.ts
+++ b/js/app/packages/app/lib/analytics/index.ts
@@ -1 +1,6 @@
-export { createAnalytics } from './analytics';
+export {
+ createAnalytics,
+ analytics,
+ type AnalyticsInterface,
+} from './analytics';
+export type { AppEvents, AppEventNames } from './app-events';
diff --git a/js/app/packages/app/lib/analytics/posthog.tsx b/js/app/packages/app/lib/analytics/posthog.tsx
index 7dd51d7eff..03899ec94d 100644
--- a/js/app/packages/app/lib/analytics/posthog.tsx
+++ b/js/app/packages/app/lib/analytics/posthog.tsx
@@ -1,5 +1,6 @@
+import { useAnalytics } from '@app/component/analytics-context';
import { createAssertedContextProvider } from '@core/context/createContext';
-import { PostHog, type JsonType } from 'posthog-js';
+import type { JsonType } from 'posthog-js';
import {
type Accessor,
createMemo,
@@ -9,32 +10,14 @@ import {
Show,
} from 'solid-js';
-export const posthogInstance = new PostHog();
-
export const [PosthogProvider, usePosthog] = createAssertedContextProvider(
'PosthogProvider',
() => {
- const instance = posthogInstance;
-
- const initialize = () => {
- const key = import.meta.env.VITE_POSTHOG_API_KEY;
-
- if (!key) return;
-
- instance.init(key, {
- api_host: 'https://analytics-proxy.macroverse.workers.dev/ingest/ph',
- ui_host: 'https://us.posthog.com', // Keep UI host for session recordings link
- defaults: '2026-01-30',
- });
- };
-
- if (!import.meta.env.DEV) {
- initialize();
- }
+ const analytics = useAnalytics();
const [featureFlags, setFeatureFlags] = createSignal<string[]>([]);
- const unsub = instance.onFeatureFlags((flags, _, ctx) => {
+ const unsub = analytics.posthog.onFeatureFlags((flags, _, ctx) => {
if (ctx?.errorsLoading) return;
setFeatureFlags(flags);
@@ -42,7 +25,7 @@ export const [PosthogProvider, usePosthog] = createAssertedContextProvider(
onCleanup(unsub);
- return { instance, featureFlags };
+ return { instance: analytics.posthog, featureFlags };
}
);
diff --git a/js/app/packages/block-canvas/component/TopBar.tsx b/js/app/packages/block-canvas/component/TopBar.tsx
index 4112e203fe..a8be9f6391 100644
--- a/js/app/packages/block-canvas/component/TopBar.tsx
+++ b/js/app/packages/block-canvas/component/TopBar.tsx
@@ -11,7 +11,7 @@ import {
} from '@app/component/split-layout/components/SplitHeader';
import { BlockItemSplitLabel } from '@app/component/split-layout/components/SplitLabel';
-import { withAnalytics } from '@coparse/analytics';
+import { useAnalytics } from '@app/component/analytics-context';
import { useIsAuthenticated } from '@core/auth';
import { createBlockSignal, useBlockId } from '@core/block';
import {
@@ -47,12 +47,13 @@ import { useToolManager } from '../signal/toolManager';
import { currentSavedFile } from '../store/canvasData';
import { useRenderState } from '../store/RenderState';
-const { track, TrackingEvents } = withAnalytics();
-
export const connectorTypeMenuTriggerSignal = createBlockSignal(false);
export function TopBar() {
+ const analytics = useAnalytics();
+
const isAuth = useIsAuthenticated();
+
const toolManager = useToolManager();
const { getLocation } = useRenderState();
const getCurrentSavedFile = currentSavedFile.get;
@@ -75,7 +76,7 @@ export function TopBar() {
if (!file) return;
downloadFile(file, downloadName());
- track(TrackingEvents.BLOCKCANVAS.FILEMENU.DOWNLOAD);
+ analytics.track('download', { blockType: 'canvas' });
});
const copyLink = () => {
@@ -98,7 +99,7 @@ export function TopBar() {
}
navigator.clipboard.writeText(url);
toast.success('Link copied to clipboard');
- track(TrackingEvents.BLOCKCANVAS.FILEMENU.SHARE);
+ analytics.track('copy_share_link', { blockType: 'canvas' });
};
const ops: FileOperation[] = [
@@ -132,7 +133,15 @@ export function TopBar() {
label: 'Properties',
icon: TagIcon,
action: propertiesControl.toggle,
- buttonComponent: () => <DocumentPropertiesButton buttonSize="sm" />,
+ buttonComponent: () => (
+ <DocumentPropertiesButton
+ buttonSize="sm"
+ onOpenChange={(open) =>
+ open &&
+ analytics.track('properties_panel_open', { blockType: 'canvas' })
+ }
+ />
+ ),
},
{
label: 'Share',
diff --git a/js/app/packages/block-channel/component/Top.tsx b/js/app/packages/block-channel/component/Top.tsx
index ef36d78329..931231960f 100644
--- a/js/app/packages/block-channel/component/Top.tsx
+++ b/js/app/packages/block-channel/component/Top.tsx
@@ -32,6 +32,7 @@ import { useChannelContext } from '@block-channel/hooks/channel';
import { isChannelAdminOrOwner } from '@queries/channel/derived';
import { useChannelModals } from './ModalsProvider';
import { ParticipantManagerButton } from './ParticipantManager';
+import { useAnalytics } from '@app/component/analytics-context';
type TopIconProps = {
channelType: ChannelType;
@@ -97,6 +98,8 @@ export function ChannelTopLeft(props: ChannelTopLeftProps) {
}
export function Top(props: TopProps) {
+ const analytics = useAnalytics();
+
const blockId = useBlockId();
const notificationSource = useGlobalNotificationSource();
const channelContext = useChannelContext();
@@ -142,6 +145,12 @@ export function Top(props: TopProps) {
<NotificationsButton
entity={{ id: blockId, type: 'channel' }}
notificationSource={notificationSource}
+ onOpenChange={(open) =>
+ open &&
+ analytics.track('notifications_panel_open', {
+ blockType: 'channel',
+ })
+ }
/>
),
},
diff --git a/js/app/packages/block-channel/hooks/participants.tsx b/js/app/packages/block-channel/hooks/participants.tsx
index b4cea904ad..8bbb691dc7 100644
--- a/js/app/packages/block-channel/hooks/participants.tsx
+++ b/js/app/packages/block-channel/hooks/participants.tsx
@@ -1,5 +1,4 @@
-import { withAnalytics } from '@coparse/analytics';
-import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
+import { useAnalytics } from '@app/component/analytics-context';
import {
useAddParticipantsMutation,
useRemoveParticipantsMutation,
@@ -10,10 +9,11 @@ import type { Accessor } from 'solid-js';
* Hook to add participants to a channel with optimistic updates
*/
export function useAddParticipantsToChannel(channelId: Accessor<string>) {
- const { track } = withAnalytics();
+ const analytics = useAnalytics();
+
const mutation = useAddParticipantsMutation({
onSuccess: () => {
- track(TrackingEvents.BLOCKCHANNEL.PARTICIPANT.ADD);
+ analytics.track('channel_participant_add');
},
});
@@ -34,7 +34,13 @@ export function useAddParticipantsToChannel(channelId: Accessor<string>) {
* Hook to remove participants from a channel with optimistic updates
*/
export function useRemoveParticipantsFromChannel(channelId: Accessor<string>) {
- const mutation = useRemoveParticipantsMutation();
+ const analytics = useAnalytics();
+
+ const mutation = useRemoveParticipantsMutation({
+ onSuccess: () => {
+ analytics.track('channel_participant_remove');
+ },
+ });
return (participants: string[]) => {
const id = channelId();
diff --git a/js/app/packages/block-channel/hooks/reactions.tsx b/js/app/packages/block-channel/hooks/reactions.tsx
index 0f4ae405fc..c424772cb7 100644
--- a/js/app/packages/block-channel/hooks/reactions.tsx
+++ b/js/app/packages/block-channel/hooks/reactions.tsx
@@ -1,5 +1,3 @@
-import { withAnalytics } from '@coparse/analytics';
-import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
import { useUserId } from '@core/context/user';
import {
useAddReactionMutation,
@@ -7,6 +5,7 @@ import {
} from '@queries/channel/reaction';
import type { Accessor } from 'solid-js';
import type { GetChannelResponseReactions } from '@service-comms/generated/models';
+import { useAnalytics } from '@app/component/analytics-context';
type CountedReaction = {
emoji: string;
@@ -20,7 +19,7 @@ export function useReactToMessage(
channelId: Accessor<string>,
reactions: Accessor<GetChannelResponseReactions>
) {
- const { track } = withAnalytics();
+ const analytics = useAnalytics();
const userId_ = useUserId();
const addReaction = useAddReactionMutation();
@@ -53,10 +52,9 @@ export function useReactToMessage(
});
}
- track(TrackingEvents.BLOCKCHANNEL.MESSAGE.REACTION, {
- channelId: channelIdValue,
+ analytics.track('channel_reaction', {
emoji,
- action: hasReacted ? 'Remove' : 'Add',
+ action: hasReacted ? 'remove' : 'add',
});
};
}
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsx
index 3f75d28c26..82be53192d 100644
--- a/js/app/packages/block-chat/component/Chat.tsx
+++ b/js/app/packages/block-chat/component/Chat.tsx
@@ -39,7 +39,7 @@ import {
} from '@core/signal/blockElement';
import { blockHandleSignal } from '@core/signal/load';
import { useCanEdit } from '@core/signal/permissions';
-import { withAnalytics } from '@coparse/analytics';
+import { useAnalytics } from '@app/component/analytics-context';
import { deriveChatName } from '@core/component/AI/util/deriveName';
import { createRenameDssEntityMutation } from '@macro-entity';
import { invalidateUserQuota } from '@queries/auth';
@@ -47,8 +47,6 @@ import { createCallback } from '@solid-primitives/rootless';
import { ChatInput } from 'core/component/AI/component/input/ChatInput';
import { createEffect, createSignal, Show } from 'solid-js';
-const { track, TrackingEvents } = withAnalytics();
-
export function Chat(props: { data: ChatData }) {
const loadedState = getChatInputStoredState(props.data.chat.id);
@@ -71,6 +69,7 @@ function ChatInner(props: {
data: ChatData;
loadedInputText: string | undefined;
}) {
+ const analytics = useAnalytics();
const input = useChatInputContext();
const chat = useChatContext();
const canEdit = useCanEdit();
@@ -88,7 +87,7 @@ function ChatInner(props: {
const editor = buildChatEditor().withMentions({
onCreate: (mention) => {
- track(TrackingEvents.CHAT.MENTION.SELECT);
+ analytics.track('mentions_menu_use', { itemType: 'chat' });
const attachment = getAttachmentFromMention(mention);
if (attachment) input.attachments.addAttachment(attachment);
},
diff --git a/js/app/packages/block-code/component/TopBar.tsx b/js/app/packages/block-code/component/TopBar.tsx
index 55277d0c28..0cdbfdd372 100644
--- a/js/app/packages/block-code/component/TopBar.tsx
+++ b/js/app/packages/block-code/component/TopBar.tsx
@@ -9,7 +9,7 @@ import type { FileOperation } from '@app/component/split-layout/components/Split
import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
import { BlockItemSplitLabel } from '@app/component/split-layout/components/SplitLabel';
-import { withAnalytics } from '@coparse/analytics';
+import { useAnalytics } from '@app/component/analytics-context';
import { useIsAuthenticated } from '@core/auth';
import { useBlockId } from '@core/block';
import {
@@ -42,14 +42,15 @@ import { Show } from 'solid-js';
import type { CodeBlockMode } from './Block';
import { TabbedControl } from '@ui/components/TabbedControl';
-const { track, TrackingEvents } = withAnalytics();
-
export const TopBar: Component<{
isHtmlFile: boolean;
mode: CodeBlockMode;
onModeChange: (mode: CodeBlockMode) => void;
}> = (props) => {
+ const analytics = useAnalytics();
+
const isAuth = useIsAuthenticated();
+
const blockId = useBlockId();
const text = blockTextSignal.get;
const name = useBlockDocumentName();
@@ -64,7 +65,7 @@ export const TopBar: Component<{
if (!text || !name) return;
const file = new Blob([content ?? ''], { type: 'text/plain' });
downloadFile(file, downloadName());
- track(TrackingEvents.BLOCKCODE.FILEMENU.DOWNLOAD);
+ analytics.track('download', { blockType: 'code' });
});
const ops: FileOperation[] = [
@@ -98,7 +99,15 @@ export const TopBar: Component<{
label: 'Properties',
icon: TagIcon,
action: propertiesControl.toggle,
- buttonComponent: () => <DocumentPropertiesButton buttonSize="sm" />,
+ buttonComponent: () => (
+ <DocumentPropertiesButton
+ buttonSize="sm"
+ onOpenChange={(open) =>
+ open &&
+ analytics.track('properties_panel_open', { blockType: 'code' })
+ }
+ />
+ ),
},
{
label: 'Share',
diff --git a/js/app/packages/block-md/comments/commentOperations.ts b/js/app/packages/block-md/comments/commentOperations.ts
index ae72098f7a..de7cfbb6f0 100644
--- a/js/app/packages/block-md/comments/commentOperations.ts
+++ b/js/app/packages/block-md/comments/commentOperations.ts
@@ -1,5 +1,4 @@
import { mdStore } from '@block-md/signal/markdownBlockData';
-import { withAnalytics } from '@coparse/analytics';
import { useBlockId } from '@core/block';
import type { DeleteCommentInfo } from '@core/comments/commentType';
import { threadMeasureContainerId } from '@core/comments/Thread';
@@ -28,10 +27,11 @@ import {
useDeleteCommentResource,
useEditCommentResource,
} from './commentsResource';
-
-const { track, TrackingEvents } = withAnalytics();
+import { useAnalytics } from '@app/component/analytics-context';
export function useCreateComment() {
+ const analytics = useAnalytics();
+
const deleteNewComments = useDeleteNewComments();
const createHighlightComment = useCreateHighlightCommentResource();
const createThreadReply = useCreateThreadReplyResource();
@@ -42,7 +42,7 @@ export function useCreateComment() {
return createCallback(
async (info: CreateCommentRequest & { threadId: number }) => {
- track(TrackingEvents.BLOCKMARKDOWN.COMMENT.CREATE);
+ analytics.track('comment_create', { blockType: 'md' });
const { threadId, text } = info;
if (threadId === -1) {
@@ -77,10 +77,12 @@ export function useCreateComment() {
}
export function useUpdateComment() {
+ const analytics = useAnalytics();
+
const editComment = useEditCommentResource();
return createCallback((commentId: number, info: EditCommentRequest) => {
- track(TrackingEvents.BLOCKMARKDOWN.COMMENT.UPDATE);
+ analytics.track('comment_update', { blockType: 'md' });
return editComment(commentId, info);
});
@@ -91,13 +93,15 @@ export function useCreatePendingComment() {
}
export function useDeleteComment() {
+ const analytics = useAnalytics();
+
const deleteComment = useDeleteCommentResource();
const deleteNewComments = useDeleteNewComments();
const editor = mdStore.get.editor;
const comments = commentsStore.get;
return createCallback(async (info: DeleteCommentInfo) => {
- track(TrackingEvents.BLOCKMARKDOWN.COMMENT.DELETE);
+ analytics.track('comment_delete', { blockType: 'md' });
editor?.dispatchCommand(DISCARD_DRAFT_COMMENT_COMMAND, undefined);
const commentId = info.commentId;
diff --git a/js/app/packages/block-md/component/TopBar.tsx b/js/app/packages/block-md/component/TopBar.tsx
index 76d133ec2a..56769a0c8c 100644
--- a/js/app/packages/block-md/component/TopBar.tsx
+++ b/js/app/packages/block-md/component/TopBar.tsx
@@ -62,9 +62,13 @@ import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
import { createEffect, For, on, Show, type JSX } from 'solid-js';
import { HISTORY_DRAWER_ID } from './History';
import { DRAWER_ID as PROPERTIES_DRAWER_ID } from './MarkdownPropertiesModal';
+import { useAnalytics } from '@app/component/analytics-context';
export function TopBar() {
+ const analytics = useAnalytics();
+
const isAuth = useIsAuthenticated();
+
const canEdit = useCanEdit();
const blockName = useBlockName();
const blockId = useBlockId();
@@ -162,6 +166,10 @@ export function TopBar() {
<NotificationsButton
entity={{ id: blockId, type: itemType as EntityType }}
notificationSource={notificationSource}
+ onOpenChange={(open) =>
+ open &&
+ analytics.track('notifications_panel_open', { blockType: 'md' })
+ }
/>
),
},
@@ -175,6 +183,10 @@ export function TopBar() {
documentId={blockId}
documentName={name()}
buttonSize="sm"
+ onOpenChange={(open) =>
+ open &&
+ analytics.track('references_panel_open', { blockType: 'md' })
+ }
/>
),
},
diff --git a/js/app/packages/block-pdf/component/PageOverlay.tsx b/js/app/packages/block-pdf/component/PageOverlay.tsx
index 8378e6f627..a593c46b73 100644
--- a/js/app/packages/block-pdf/component/PageOverlay.tsx
+++ b/js/app/packages/block-pdf/component/PageOverlay.tsx
@@ -25,7 +25,6 @@ import { useCreateHighlightCommentAtSelection } from '@block-pdf/store/comments/
import { useCreatePlaceable } from '@block-pdf/store/placeables';
import { PayloadMode, type PayloadType } from '@block-pdf/type/placeables';
import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';
-import { withAnalytics } from '@coparse/analytics';
import { useIsAuthenticated } from '@core/auth';
import { createBlockSignal, useBlockId, useIsNestedBlock } from '@core/block';
import type { Completion } from '@core/client/completion';
@@ -79,6 +78,7 @@ import {
UserHighlight,
useResetUserHighlights,
} from './UserHighlight';
+import { useAnalytics } from '@app/component/analytics-context';
export interface IPageOverlayProps {
pageIndex: number;
@@ -86,8 +86,6 @@ export interface IPageOverlayProps {
pageViewDiv: PDFPageView['div'];
}
-const { track, TrackingEvents } = withAnalytics();
-
export interface IHighlightObj {
left: number;
top: number;
@@ -111,6 +109,8 @@ export const PDFPopupCompletionSignal = createBlockSignal<
// This is where all the page-specifc overlays should reside, like placeables, etc.
export function PageOverlay(props: IPageOverlayProps) {
+ const analytics = useAnalytics();
+
const isNestedBlock = useIsNestedBlock();
let pageOverlayRef!: HTMLDivElement;
const pageViewDivProp = () => props.pageViewDiv;
@@ -183,7 +183,7 @@ export function PageOverlay(props: IPageOverlayProps) {
element: targetNode,
pageWidth: getRootViewer()?.pageDimensions(pageIndex, true)?.width ?? 0,
});
- track(TrackingEvents.BLOCKPDF.DEFINITION.OPEN);
+ analytics.track('block_pdf_definition_open');
} else if (secID) {
// display section popup
e.stopPropagation();
@@ -195,7 +195,7 @@ export function PageOverlay(props: IPageOverlayProps) {
idToSectionMap,
});
- track(TrackingEvents.BLOCKPDF.SECTION.OPEN);
+ analytics.track('block_pdf_section_open');
getPopupViewer()?.scrollTo({ pageNumber: page + 1, yPos: y });
if (!isPopup) getRootViewer()?.showPopupAt(tgt as HTMLElement);
diff --git a/js/app/packages/block-pdf/component/TopBar.tsx b/js/app/packages/block-pdf/component/TopBar.tsx
index 89e275740a..48655072e6 100644
--- a/js/app/packages/block-pdf/component/TopBar.tsx
+++ b/js/app/packages/block-pdf/component/TopBar.tsx
@@ -1,3 +1,4 @@
+import { useAnalytics } from '@app/component/analytics-context';
import { useDrawerControl } from '@app/component/split-layout/components/SplitDrawerContext';
import type { BlockTool } from '@app/component/ResponsiveBlockToolbar';
import type { FileOperation } from '@app/component/split-layout/components/SplitFileMenu';
@@ -58,6 +59,7 @@ import {
} from '@app/component/ResponsiveBlockToolbar';
export function TopBar() {
+ const analytics = useAnalytics();
const isAuth = useIsAuthenticated();
const documentId = useBlockId();
const blockName = useBlockName();
@@ -204,7 +206,15 @@ export function TopBar() {
label: 'Properties',
icon: TagIcon,
action: propertiesControl.toggle,
- buttonComponent: () => <DocumentPropertiesButton buttonSize="sm" />,
+ buttonComponent: () => (
+ <DocumentPropertiesButton
+ buttonSize="sm"
+ onOpenChange={(open) =>
+ open &&
+ analytics.track('properties_panel_open', { blockType: 'pdf' })
+ }
+ />
+ ),
},
{
label: 'Share',
diff --git a/js/app/packages/block-pdf/store/comments/commentOperations.ts b/js/app/packages/block-pdf/store/comments/commentOperations.ts
index 059794748e..568d2ba3c3 100644
--- a/js/app/packages/block-pdf/store/comments/commentOperations.ts
+++ b/js/app/packages/block-pdf/store/comments/commentOperations.ts
@@ -1,7 +1,6 @@
import { useGetRootViewer } from '@block-pdf/signal/pdfViewer';
import { commentsStore } from '@block-pdf/store/comments/commentStore';
import type { PdfRootLayout } from '@block-pdf/type/comments';
-import { withAnalytics } from '@coparse/analytics';
import { useBlockId } from '@core/block';
import { type DeleteCommentInfo, isRoot } from '@core/comments/commentType';
import { threadMeasureContainerId } from '@core/comments/Thread';
@@ -23,10 +22,11 @@ import {
import { highlightsUuidMap } from '../highlight';
import { newThreadPlaceable, useDeleteNewFreeComment } from './freeComments';
import { useDeleteNewHighlightComment } from './highlightComments';
-
-const { track, TrackingEvents } = withAnalytics();
+import { useAnalytics } from '@app/component/analytics-context';
export function useCreateComment() {
+ const analytics = useAnalytics();
+
const deleteNewComments = useDeleteNewComments();
const createFreeComment = useCreateFreeCommentResource();
const createHighlightComment = useCreateHighlightCommentResource();
@@ -35,7 +35,7 @@ export function useCreateComment() {
return createCallback(
async (info: CreateCommentRequest & { threadId: number }) => {
- track(TrackingEvents.BLOCKPDF.COMMENT.CREATE);
+ analytics.track('comment_create', { blockType: 'pdf' });
const { threadId, text } = info;
// new thread + anchor
@@ -91,31 +91,37 @@ export function useCreateComment() {
}
export function useUpdateComment() {
+ const analytics = useAnalytics();
+
const editComment = useEditCommentResource();
return createCallback((commentId: number, info: EditCommentRequest) => {
- track(TrackingEvents.BLOCKPDF.COMMENT.UPDATE);
+ analytics.track('comment_update', { blockType: 'pdf' });
return editComment(commentId, info);
});
}
export function useDeleteComment() {
+ const analytics = useAnalytics();
+
const deleteComment = useDeleteCommentResource();
const deleteNewComments = useDeleteNewComments();
- return createCallback((info: DeleteCommentInfo) => {
+ return createCallback(async (info: DeleteCommentInfo) => {
const commentId = info.commentId;
if (commentId === -1) {
deleteNewComments();
- return;
+ return false;
}
- const success = deleteComment(commentId, {
+ const success = await deleteComment(commentId, {
removeAnchorThreadOnly: info.removeAnchorThreadOnly,
});
- track(TrackingEvents.BLOCKPDF.COMMENT.DELETE);
+ if (success) {
+ analytics.track('comment_delete', { blockType: 'pdf' });
+ }
return success;
});
}
diff --git a/js/app/packages/block-theme/components/ThemeList.tsx b/js/app/packages/block-theme/components/ThemeList.tsx
index 62aa41ff70..a8c29d1b5e 100644
--- a/js/app/packages/block-theme/components/ThemeList.tsx
+++ b/js/app/packages/block-theme/components/ThemeList.tsx
@@ -2,8 +2,11 @@ import { For } from 'solid-js';
import { currentThemeId, isThemeSaved, themes } from '../signals/themeSignals';
import { applyTheme } from '../utils/themeUtils';
import { ColorSwatch } from './ColorSwatch';
+import { useAnalytics } from 'app/component/analytics-context';
export function ThemeList() {
+ const analytics = useAnalytics()
+
return (
<>
<style>{`
@@ -101,7 +104,10 @@ export function ThemeList() {
{(theme) => (
<div
class={`theme-list-item ${theme.id === currentThemeId() && isThemeSaved() ? 'current-theme' : ''}`}
- onPointerDown={() => {applyTheme(theme.id)}}
+ onClick={() => {
+ analytics.track('theme_changed', {themeId: theme.id})
+ applyTheme(theme.id)
+ }}
style="
grid-template-columns: min-content 1fr min-content;
background-color: var(--b1);
diff --git a/js/app/packages/channel/Channel/create-channel-message-actions.ts b/js/app/packages/channel/Channel/create-channel-message-actions.ts
index ed4622f36b..1571241c3d 100644
--- a/js/app/packages/channel/Channel/create-channel-message-actions.ts
+++ b/js/app/packages/channel/Channel/create-channel-message-actions.ts
@@ -13,6 +13,7 @@ import {
DEFAULT_REACTION_EMOJI,
hasReactionFromUser,
} from '../Thread/utils/message-actions';
+import { useAnalytics } from '@app/component/analytics-context';
type AddReactionInput = {
channelId: string;
@@ -79,6 +80,8 @@ const emptyReplyHandler: MessageActionHandler = () => undefined;
export function createChannelMessageActions(
options: CreateChannelMessageActionsOptions
): (message: MessageData) => MessageActions {
+ const analytics = useAnalytics();
+
const effects = {
...createDefaultEffects(),
...options.effects,
@@ -106,6 +109,11 @@ export function createChannelMessageActions(
.thread_id ?? undefined;
const hasReaction = hasReactionFromUser(liveMessage, emoji, userId);
+ analytics.track('channel_reaction', {
+ emoji,
+ action: hasReaction ? 'remove' : 'add',
+ });
+
if (hasReaction) {
options.removeReaction({
channelId,
diff --git a/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts b/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
index 4e58edde26..ddd967cf63 100644
--- a/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
+++ b/js/app/packages/channel/Channel/tests/create-channel-message-actions.test.ts
@@ -2,6 +2,15 @@ import { describe, expect, it, vi } from 'vitest';
import type { MessageData } from '../../Message';
import { createChannelMessageActions } from '../create-channel-message-actions';
+// Mock analytics context
+vi.mock('@app/component/analytics-context', () => ({
+ useAnalytics: () => ({
+ track: vi.fn(),
+ identify: vi.fn(),
+ reset: vi.fn(),
+ }),
+}));
+
type ActionMessage = MessageData & { thread_id?: string | null };
function buildMessage(overrides?: Partial<ActionMessage>): ActionMessage {
diff --git a/js/app/packages/core/auth/logout.ts b/js/app/packages/core/auth/logout.ts
index af9493b68a..1c54c7bd3f 100644
--- a/js/app/packages/core/auth/logout.ts
+++ b/js/app/packages/core/auth/logout.ts
@@ -1,4 +1,3 @@
-import { withAnalytics } from '@coparse/analytics';
import { authServiceClient } from '@service-auth/client';
import { authKeys } from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
@@ -6,8 +5,6 @@ import { SERVER_HOSTS } from '@core/constant/servers';
import { createCallback } from '@solid-primitives/rootless';
import { useAnalytics } from '@app/component/analytics-context';
-const { track, TrackingEvents } = withAnalytics();
-
export function useLogout() {
const analytics = useAnalytics();
@@ -30,9 +27,9 @@ export function useLogout() {
});
await authServiceClient.logout();
+ analytics.track('sign_out');
analytics.reset();
- track(TrackingEvents.AUTH.LOGOUT);
window.location.href = SERVER_HOSTS['auth-logout'];
});
}
diff --git a/js/app/packages/core/component/AI/component/DragDrop.tsx b/js/app/packages/core/component/AI/component/DragDrop.tsx
index e5de3fd5d5..1676a99277 100644
--- a/js/app/packages/core/component/AI/component/DragDrop.tsx
+++ b/js/app/packages/core/component/AI/component/DragDrop.tsx
@@ -1,9 +1,7 @@
-import { withAnalytics } from '@coparse/analytics';
+import { analytics } from '@app/lib/analytics';
import { FileDropOverlay } from '@core/component/FileDropOverlay';
import { fileDrop } from '@core/directive/fileDrop';
-const { track, TrackingEvents } = withAnalytics();
-
import { SUPPORTED_ATTACHMENT_EXTENSIONS } from '@core/component/AI/constant';
import { useChatInputContext } from '@core/component/AI/context';
import type { Accessor, Component, ParentProps } from 'solid-js';
@@ -39,7 +37,7 @@ export const DragDropWrapper: Component<DragDropWrapperProps> = (props) => {
onDragStart: () => setIsFileDragging(true),
onDragEnd: () => setIsFileDragging(false),
onDrop: (files) => {
- track(TrackingEvents.CHAT.ATTACHMENT.DROP);
+ analytics.track('ai_attachment_add');
uploadQueue.upload(files);
},
}}
diff --git a/js/app/packages/core/component/AI/component/input/ChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsx
index 833fcd57c5..37ccc89e45 100644
--- a/js/app/packages/core/component/AI/component/input/ChatInput.tsx
+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx
@@ -1,4 +1,3 @@
-import { withAnalytics } from '@coparse/analytics';
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
import { useChatInputContext } from '@core/component/AI/context';
import type { Model, ToolSet } from '@core/component/AI/types';
@@ -23,8 +22,7 @@ import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';
import { AttachmentList } from './Attachment';
import { ChatAttachMenu } from './ChatAttachMenu';
import { useAiDataConsentGate } from './useAiDataConsent';
-
-const { track, TrackingEvents } = withAnalytics();
+import { useAnalytics } from '@app/component/analytics-context';
export type ChatInputProps = {
onSend: (args: ChatSendInput) => void;
@@ -44,6 +42,8 @@ export type ChatInputComponentProps = {
} & ChatInputProps;
export function ChatInput(props: ChatInputComponentProps) {
+ const analytics = useAnalytics();
+
const input = useChatInputContext();
const uploadQueue = input.uploadQueue;
const attachments = input.attachments;
@@ -64,7 +64,7 @@ export function ChatInput(props: ChatInputComponentProps) {
uploaded
.filter((upload) => upload.type === 'ok')
.forEach((upload) => {
- track(TrackingEvents.CHAT.ATTACHMENT.ADD);
+ analytics.track('ai_attachment_add');
attachments.addAttachment(upload.attachment);
});
});
@@ -194,7 +194,6 @@ export function ChatInput(props: ChatInputComponentProps) {
<AttachmentList
attached={attachments.attached}
removeAttachment={(id) => {
- track(TrackingEvents.CHAT.ATTACHMENT.REMOVE);
attachments.removeAttachment(id);
}}
uploading={() =>
@@ -211,7 +210,7 @@ export function ChatInput(props: ChatInputComponentProps) {
containerRef={containerRef}
open={showAttachMenu()}
onAttach={(attachment) => {
- track(TrackingEvents.CHAT.ATTACHMENT.ADD);
+ analytics.track('ai_attachment_add');
attachments.addAttachment(attachment);
}}
/>
diff --git a/js/app/packages/core/component/AI/component/input/buildRequest.ts b/js/app/packages/core/component/AI/component/input/buildRequest.ts
index 692ad5e831..021029c3b2 100644
--- a/js/app/packages/core/component/AI/component/input/buildRequest.ts
+++ b/js/app/packages/core/component/AI/component/input/buildRequest.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { DEFAULT_MODEL } from '@core/component/AI/constant';
import { useAdditionalInstructions } from '@core/component/AI/constant/prompts';
import type { Attachment, Model, ToolSet } from '@core/component/AI/types';
@@ -55,6 +56,11 @@ export function useSendChatMessage() {
return { error: true };
}
+ analytics.track('ai_message_sent', {
+ model: model ?? DEFAULT_MODEL,
+ attachmentCount: attachments.length,
+ });
+
return {
chat_id,
stream: {
diff --git a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
index 944207b8ea..1966172eca 100644
--- a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx
@@ -8,10 +8,8 @@ import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';
import type { Attachment, Model } from '@core/component/AI/types';
import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
import { ENABLE_SNAPSHOT_NODE } from '@core/constant/featureFlags';
-import { withAnalytics } from '@coparse/analytics';
import { onMount } from 'solid-js';
-
-const { track, TrackingEvents } = withAnalytics();
+import { useAnalytics } from '@app/component/analytics-context';
function EditableChatMessageInner(props: {
chatId: string;
@@ -21,12 +19,14 @@ function EditableChatMessageInner(props: {
onCancel: () => void;
model: Model;
}) {
+ const analytics = useAnalytics();
+
const input = useChatInputContext();
const { getAttachmentFromMention } = useGetChatAttachmentInfo();
const editor = buildChatEditor().withMentions({
onCreate: (mention) => {
- track(TrackingEvents.CHAT.MENTION.SELECT);
+ analytics.track('mentions_menu_use', { itemType: 'chat' });
const attachment = getAttachmentFromMention(mention);
if (attachment) input.attachments.addAttachment(attachment);
},
diff --git a/js/app/packages/core/component/DocumentPropertiesModal.tsx b/js/app/packages/core/component/DocumentPropertiesModal.tsx
index f3c8f01c85..db994eba13 100644
--- a/js/app/packages/core/component/DocumentPropertiesModal.tsx
+++ b/js/app/packages/core/component/DocumentPropertiesModal.tsx
@@ -30,6 +30,7 @@ function DocumentPropertiesContent(props: {
export function DocumentPropertiesButton(props: {
buttonSize?: 'sm' | 'base';
+ onOpenChange?: (open: boolean) => void;
}) {
const drawerControl = useDrawerControl(DRAWER_ID);
return (
@@ -38,7 +39,10 @@ export function DocumentPropertiesButton(props: {
theme={drawerControl.isOpen() ? 'accent' : 'clear'}
size={props.buttonSize ?? 'base'}
tooltip={{ label: 'Properties' }}
- onClick={drawerControl.toggle}
+ onClick={() => {
+ props.onOpenChange?.(!drawerControl.isOpen());
+ drawerControl.toggle();
+ }}
/>
);
}
diff --git a/js/app/packages/core/component/FileList/itemOperations.ts b/js/app/packages/core/component/FileList/itemOperations.ts
index 637e38a088..ace9c884f3 100644
--- a/js/app/packages/core/component/FileList/itemOperations.ts
+++ b/js/app/packages/core/component/FileList/itemOperations.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { usePaywallState } from '@core/constant/PaywallState';
import { isPaymentError } from '@core/util/handlePaymentError';
import { isErr, isOk } from '@core/util/maybeResult';
@@ -471,6 +472,7 @@ export async function permanentlyDelete(args: {
return false;
}
+ analytics.track('delete_entity', { entityType: itemType });
return true;
}
diff --git a/js/app/packages/core/component/ForwardToChannel.tsx b/js/app/packages/core/component/ForwardToChannel.tsx
index 999ed26089..f529b69acf 100644
--- a/js/app/packages/core/component/ForwardToChannel.tsx
+++ b/js/app/packages/core/component/ForwardToChannel.tsx
@@ -1,6 +1,5 @@
import { useChannelMarkdownArea } from '@block-channel/component/MarkdownArea';
-import { withAnalytics } from '@coparse/analytics';
-import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
+import { useAnalytics } from '@app/component/analytics-context';
import { useIsAuthenticated } from '@core/auth';
import {
useMaybeBlockAliasedName,
@@ -61,7 +60,7 @@ interface ForwardToChannelProps {
export function ForwardToChannel(props: ForwardToChannelProps) {
const isAuthenticated = useIsAuthenticated();
- const { track } = withAnalytics();
+ const analytics = useAnalytics();
const [selectedOptions, setSelectedOptions] = createSignal<
WithCustomUserInput<'user' | 'contact' | 'channel'>[]
@@ -187,7 +186,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {
onClick: navigateToChannel,
text: 'View in channel',
});
- track(TrackingEvents.SHARE.FORWARD);
+ analytics.track('share_entity', { location: 'forward_to_channel' });
});
} else {
toast.failure('Message failed to send');
@@ -217,7 +216,9 @@ export function ForwardToChannel(props: ForwardToChannelProps) {
text: 'View in channel',
});
}
- track(TrackingEvents.SHARE.FORWARD);
+ analytics.track('share_entity', {
+ location: 'forward_to_channel',
+ });
}),
]);
} else {
@@ -242,7 +243,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {
text: 'View in channel',
});
}
- track(TrackingEvents.SHARE.FORWARD);
+ analytics.track('share_entity', { location: 'forward_to_channel' });
});
}
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
index 51ae08a7a8..3520b321d9 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -48,6 +48,7 @@ import {
} from './hooks/useEntityMention';
import { useEmailSearchMention } from './hooks/useEmailSearchMention';
import { isMobile } from '@core/mobile/isMobile';
+import { useAnalytics } from '@app/component/analytics-context';
const MAX_ITEMS = 8;
const VIRTUAL_ITEM_HEIGHT = 36;
@@ -84,6 +85,8 @@ export function MentionsMenu(props: MentionsMenuProps) {
}
function MentionsMenuInner(props: MentionsMenuProps) {
+ const analytics = useAnalytics();
+
const searchTerm = debouncedDependent(props.menu.searchTerm, 60);
const hasCustomEntities = () => !!props.entities;
@@ -285,7 +288,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
}
});
- const itemAction = createItemHandler({
+ const itemActionHandler = createItemHandler({
editor: props.editor,
blockName: useMaybeBlockName(),
blockId: useMaybeBlockId(),
@@ -296,6 +299,11 @@ function MentionsMenuInner(props: MentionsMenuProps) {
useSnapshotNode: props.useSnapshotForDocuments,
});
+ const itemAction = async (item: MentionItem) => {
+ analytics.track('mentions_menu_use', { itemType: item.kind });
+ await itemActionHandler(item);
+ };
+
createEffect(() => {
if (props.anchor) return;
if (menuOpen()) {
diff --git a/js/app/packages/core/component/NotificationsModal.tsx b/js/app/packages/core/component/NotificationsModal.tsx
index 70de09edc5..ce70b36f48 100644
--- a/js/app/packages/core/component/NotificationsModal.tsx
+++ b/js/app/packages/core/component/NotificationsModal.tsx
@@ -19,6 +19,7 @@ export function NotificationsButton(props: {
entity: Entity;
notificationSource: NotificationSource;
buttonSize?: 'sm';
+ onOpenChange?: (open: boolean) => void;
}) {
const drawerControl = useDrawerControl(NOTIFICATIONS_DRAWER_ID);
const notifications = useNotificationsForEntity(
@@ -37,7 +38,10 @@ export function NotificationsButton(props: {
'bg-accent/20 hover:bg-accent/30 text-accent-ink'
)}
tooltip="View notifications"
- onClick={() => drawerControl.toggle()}
+ onClick={() => {
+ props.onOpenChange?.(!drawerControl.isOpen());
+ drawerControl.toggle();
+ }}
size="icon-sm"
>
<Bell />
diff --git a/js/app/packages/core/component/ReferencesModal.tsx b/js/app/packages/core/component/ReferencesModal.tsx
index 9975ccbe87..68cd35a0a0 100644
--- a/js/app/packages/core/component/ReferencesModal.tsx
+++ b/js/app/packages/core/component/ReferencesModal.tsx
@@ -18,6 +18,7 @@ export function ReferencesButton(props: {
documentName?: string;
entityType?: ItemType;
buttonSize?: 'sm';
+ onOpenChange?: (open: boolean) => void;
}) {
const drawerControl = useDrawerControl(REFERENCES_DRAWER_ID);
const [referenceCount] = createResource(
@@ -40,7 +41,10 @@ export function ReferencesButton(props: {
<div
class="flex items-center gap-1 py-1 font-mono text-xs text-ink-disabled hover:bg-hover relative"
tabIndex={0}
- onClick={drawerControl.toggle}
+ onClick={() => {
+ props.onOpenChange?.(!drawerControl.isOpen());
+ drawerControl.toggle();
+ }}
role="button"
>
<BracketLeft class="h-4 w-2 text-edge" />
diff --git a/js/app/packages/core/component/TopBar/ShareButton.tsx b/js/app/packages/core/component/TopBar/ShareButton.tsx
index 794b552e54..46eafbb056 100644
--- a/js/app/packages/core/component/TopBar/ShareButton.tsx
+++ b/js/app/packages/core/component/TopBar/ShareButton.tsx
@@ -1,5 +1,3 @@
-import { withAnalytics } from '@coparse/analytics';
-import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
import { useIsAuthenticated } from '@core/auth';
import {
type BlockAlias,
@@ -78,6 +76,7 @@ import { toast } from '../Toast/Toast';
import { Tooltip } from '../Tooltip';
import { openLoginModal } from './LoginButton';
import { ScrollIndicators } from '../VerticalScrollIndicators';
+import { useAnalytics } from '@app/component/analytics-context';
import { Button } from '@ui/components/Button';
import { Dynamic } from 'solid-js/web';
import ChevronDownIcon from '@icon/regular/caret-down.svg';
@@ -174,7 +173,7 @@ interface ShareModalProps {
export function ShareModal(props: ShareModalProps) {
const navigate = useNavigate();
- const { track } = withAnalytics();
+ const analytics = useAnalytics();
const isBlockContext = isInBlock();
const [fallbackPermissionsResource, { refetch: refetchFallback }] =
createResource(
@@ -285,7 +284,6 @@ export function ShareModal(props: ShareModalProps) {
// Function to navigate to a channel
const navigateToChannel = createCallback((channelId: string) => {
navigate(`/channel/${channelId}`);
- track(TrackingEvents.SHARE.CLOSE);
props.setIsSharePermOpen(false); // Close the dialog after navigation
});
@@ -456,6 +454,7 @@ export function ShareModal(props: ShareModalProps) {
});
if (!isErr(result)) {
refetch();
+
if (accessLevel === null) {
toast.success(
'Made chat private',
@@ -466,6 +465,12 @@ export function ShareModal(props: ShareModalProps) {
'Updated public link sharing',
`Anyone with the link can ${accessLevel} this chat`
);
+
+ analytics.track('share_entity', {
+ entityType: 'chat',
+ accessLevel,
+ isPublic: true,
+ });
}
} else {
toast.alert('Failed to change chat access', 'Please try again');
@@ -491,6 +496,12 @@ export function ShareModal(props: ShareModalProps) {
'Updated public link sharing',
`Anyone with the link can ${accessLevel} this document`
);
+
+ analytics.track('share_entity', {
+ entityType: 'document',
+ accessLevel,
+ isPublic: true,
+ });
}
} else {
toast.alert('Failed to change document access', 'Please try again');
@@ -516,6 +527,12 @@ export function ShareModal(props: ShareModalProps) {
'Updated public link sharing',
`Anyone with the link can ${accessLevel} this folder`
);
+
+ analytics.track('share_entity', {
+ entityType: 'project',
+ accessLevel,
+ isPublic: true,
+ });
}
} else {
toast.alert('Failed to change folder access', 'Please try again');
@@ -704,7 +721,7 @@ export function ShareTrigger(props: { copyLink?: () => void }) {
const isAuthenticated = useIsAuthenticated();
const blockType = useBlockAliasedName();
const blockId = useBlockId();
- const { track } = withAnalytics();
+ const analytics = useAnalytics();
onMount(() => {
const blockScopeId = blockHotkeyScopeSignal.get;
@@ -713,7 +730,7 @@ export function ShareTrigger(props: { copyLink?: () => void }) {
if (!isAuthenticated()) {
openLoginModal();
} else {
- track(TrackingEvents.SHARE.OPEN);
+ analytics.track('share_menu_open', { blockType });
shareCtx.open();
}
return true;
@@ -740,6 +757,7 @@ export function ShareTrigger(props: { copyLink?: () => void }) {
const copyLink = createCallback(() => {
if (props.copyLink) return props.copyLink();
navigator.clipboard.writeText(defaultUrl());
+ analytics.track('copy_share_link', { blockType });
toast.success(
'Link copied to clipboard.',
'Sending this link in a Macro message will automatically update permissions to include recipients.'
@@ -791,7 +809,7 @@ export function ShareTrigger(props: { copyLink?: () => void }) {
if (!isAuthenticated()) {
openLoginModal();
} else {
- track(TrackingEvents.SHARE.OPEN);
+ analytics.track('share_menu_open', { blockType });
shareCtx.open();
}
}}
diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.ts
index 057a648cf6..1161a9fd0e 100644
--- a/js/app/packages/core/constant/featureFlags.ts
+++ b/js/app/packages/core/constant/featureFlags.ts
@@ -1,4 +1,4 @@
-import { posthogInstance } from '@app/lib/analytics/posthog';
+import { analytics } from '@app/lib/analytics';
/**
* This constant reflects whether the app is running locally with hot reload enabled
@@ -289,7 +289,7 @@ export function ENABLE_NEW_CHANNELS(): boolean {
return ENABLE_NEW_CHANNELS_OVERRIDE;
}
- return posthogInstance.isFeatureEnabled('enable-new-channels') ?? false;
+ return analytics.posthog.isFeatureEnabled('enable-new-channels') ?? false;
}
export const ENABLE_PROXY_EMAIL_IMAGES = resolveFeatureFlag(
diff --git a/js/app/packages/core/util/branchName.ts b/js/app/packages/core/util/branchName.ts
index 5f6104e7ef..f9d43d44fd 100644
--- a/js/app/packages/core/util/branchName.ts
+++ b/js/app/packages/core/util/branchName.ts
@@ -1,3 +1,4 @@
+import { analytics } from '@app/lib/analytics';
import { toast } from '@core/component/Toast/Toast';
import { isOk } from '@core/util/maybeResult';
import { storageServiceClient } from '@service-storage/client';
@@ -28,5 +29,6 @@ export const copyBranchNameToClipboard = async (
MAX_BRANCH_LENGTH
);
await navigator.clipboard.writeText(branchName);
+ analytics.track('task_copy_branch_name');
toast.success('Branch name copied to clipboard');
};
diff --git a/js/app/packages/core/util/upload.ts b/js/app/packages/core/util/upload.ts
index 0f3d13e1c7..91359f3f2d 100644
--- a/js/app/packages/core/util/upload.ts
+++ b/js/app/packages/core/util/upload.ts
@@ -5,7 +5,7 @@
* with standardized validation, conversion, and error handling.
*/
-import { withAnalytics } from '@coparse/analytics';
+import { analytics } from '@app/lib/analytics';
import {
DirectoryFileCountExceededError,
DirectoryFileSizeExceededError,
@@ -27,8 +27,6 @@ import {
} from '@service-storage/util/upload';
import { toast } from 'core/component/Toast/Toast';
-const { track, TrackingEvents } = withAnalytics();
-
const MAX_FILE_BYTE_SIZE = 2 * 1000 * 1000 * 1000; // 2GB
type UploadDestination = 'dss' | 'static';
@@ -241,9 +239,8 @@ export class FileSizeExceededError extends Error {
this.fileName = fileName;
this.sizeString = sizeString;
- track(TrackingEvents.UPLOAD.ERROR, {
+ analytics.track('upload_error', {
type: this.name,
- error: this.toString(),
});
}
@@ -267,9 +264,8 @@ export class UnsupportedFileTypeError extends Error {
this.fileName = fileName;
this.fileType = fileType;
- track(TrackingEvents.UPLOAD.ERROR, {
+ analytics.track('upload_error', {
type: this.name,
- error: this.toString(),
});
}
}
@@ -291,9 +287,8 @@ export class UploadError extends Error {
this.name = 'UploadError';
- track(TrackingEvents.UPLOAD.ERROR, {
+ analytics.track('upload_error', {
type: this.name,
- error: this.toString(),
destination,
});
}
diff --git a/js/app/packages/queries/channel/message.ts b/js/app/packages/queries/channel/message.ts
index ecfdb12138..5836447eb0 100644
--- a/js/app/packages/queries/channel/message.ts
+++ b/js/app/packages/queries/channel/message.ts
@@ -1,4 +1,3 @@
-import { TrackingEvents, withAnalytics } from '@coparse/analytics';
import { toast } from '@core/component/Toast/Toast';
import { ENABLE_NEW_CHANNELS } from '@core/constant/featureFlags';
import type { DateValue } from '@core/util/date';
@@ -34,6 +33,7 @@ import {
resolveMessageTarget,
type DeleteTargetSnapshot,
} from './reconcile';
+import { useAnalytics } from '@app/component/analytics-context';
/**
* Register nonces for both message and attachment deduplication.
@@ -559,8 +559,6 @@ export function rollbackUpdateChannelMessage(
}
}
-const { track } = withAnalytics();
-
type SendMessageParams = {
channelID: string;
message: PostMessageRequest;
@@ -581,6 +579,8 @@ export function useSendMessageMutation(
SendMessageContext
>
) {
+ const analytics = useAnalytics();
+
return useMutation(() => ({
gcTime: 0,
mutationFn: async (vars: SendMessageParams) => {
@@ -619,11 +619,10 @@ export function useSendMessageMutation(
realId: data.id,
threadId: variables.message.thread_id ?? undefined,
});
- track(TrackingEvents.BLOCKCHANNEL.MESSAGE.SEND, {
- channelId: variables.channelID,
+ analytics.track('channel_message_sent', {
contentLength: variables.message.content?.length ?? 0,
attachmentsLength: variables.message.attachments.length,
- inThread: variables.message.thread_id !== undefined,
+ isThreadReply: variables.message.thread_id !== undefined,
});
},
onError(error, vars, context) {
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index f0e88a997f..bc30f45d8a 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -19,6 +19,7 @@ import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { emailKeys } from './keys';
+import { useAnalytics } from '@app/component/analytics-context';
const THREAD_STALE_TIME = 5 * 60 * 1000;
@@ -269,6 +270,8 @@ type SendMessageParams = { message: ApiDraftInput };
export function useSendMessageMutation(
callbacks?: MutationCallbacks<SendMessageResponse, Error, SendMessageParams>
) {
+ const analytics = useAnalytics();
+
return useMutation(() => ({
mutationFn: async (vars: SendMessageParams) =>
await throwOnErr(
@@ -277,6 +280,7 @@ export function useSendMessageMutation(
...withCallbacks<SendMessageResponse, Error, SendMessageParams>(
{
onSuccess: (data) => {
+ analytics.track('email_message_sent');
const threadID = data.message.thread_db_id;
if (threadID) {
queryClient.invalidateQueries({
diff --git a/js/app/packages/service-clients/service-storage/util/upload.ts b/js/app/packages/service-clients/service-storage/util/upload.ts
index 0b610e5610..d555bb6723 100644
--- a/js/app/packages/service-clients/service-storage/util/upload.ts
+++ b/js/app/packages/service-clients/service-storage/util/upload.ts
@@ -1,4 +1,4 @@
-import { withAnalytics } from '@coparse/analytics';
+import { analytics } from '@app/lib/analytics';
import type { FileTypeString, MimeType } from '@core/block';
import { blockAcceptedMimetypeToFileExtension } from '@core/constant/allBlocks';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
@@ -13,8 +13,6 @@ import { storageWS } from '@service-storage/websocket';
import { createUploadToast, toast } from 'core/component/Toast/Toast';
import { uploadDocx } from './uploadDocx';
-const { track, TrackingEvents } = withAnalytics();
-
const dismissToast = (toastId: number | null) => {
if (toastId !== null) toaster.dismiss(toastId);
};
@@ -105,10 +103,11 @@ export async function upload(
const isZip = fileTypeOrExtension === 'zip';
if (!options?.skipAnalytics) {
- track(TrackingEvents.UPLOAD.FILE, {
+ analytics.track('upload_file', {
fileType: fileTypeOrExtension,
fileName: file.name,
fileSize: file.size,
+ destination: 'dss',
folder: isZip,
});
}