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.

8.0 KB
Raw Blame
import { createTabLeaderSignal } from '@core/cross-tab/tab-leader';
import { makeEventListener } from '@solid-primitives/event-listener';
import { makePersisted } from '@solid-primitives/storage';
import {
  type Accessor,
  createContext,
  createResource,
  createSignal,
  type JSX,
  type Setter,
  useContext,
} from 'solid-js';
import type {
  PlatformNotificationData,
  PlatformNotificationHandle,
} from '../notification-platform';

type NotGranted = 'not-granted';

/// the context provider value which provides an interface wherein downstream consumers can interact with
// this platforms Notifcation implementation
export interface PlatformNotificationInterface {
  requestPermission: () => Promise<NotificationPermission>;
  getCurrentPermission: () => Promise<NotificationPermission>;
  showNotification: (
    data: PlatformNotificationData
  ) => Promise<PlatformNotificationHandle | NotGranted>;
  unregisterNotifications: () => Promise<void>;
}

export type CreateAppNotificationInterface = (
  setDisabled: () => Promise<void>,
  shouldSend: Accessor<boolean>
) => PlatformNotificationInterface;

export type NotificationUnsupported = 'not-supported';

const ELECTION_NAMESPACE = 'notification-provider';

// create the default browser interface
// this function returns undefined if the browser does not support notifcications
// unregistration is an application detail and isn't actually part of the browser notification api
// which Iis why it is passed in
function createDefaultBrowserInterface(
  unregisterNotifications: () => Promise<void>
): PlatformNotificationInterface | NotificationUnsupported {
  if (!('Notification' in window)) return 'not-supported';

  const isLeader = createTabLeaderSignal(ELECTION_NAMESPACE);

  function getCurrentPermission(): Promise<NotificationPermission> {
    return new Promise((res) => res(window.Notification.permission));
  }

  return {
    requestPermission: () => {
      return window.Notification.requestPermission();
    },
    getCurrentPermission,
    showNotification: async (data: PlatformNotificationData) => {
      if (!isLeader()) {
        // treat as no-op
        return 'not-granted';
      }
      const granted = await getCurrentPermission();
      if (granted !== 'granted') {
        return 'not-granted';
      }

      return createBrowserNotification(data);
    },
    unregisterNotifications,
  };
}

export function createBrowserNotification(
  data: PlatformNotificationData
): PlatformNotificationHandle | NotGranted {
  let notif: Notification;
  try {
    notif = new Notification(data.title, data.options);
  } catch (error) {
    // Chrome on Android only shows notifications through a service worker,
    // which this app does not register.
    if (error instanceof TypeError) return 'not-granted';
    throw error;
  }

  return {
    onClick: (cb) => {
      notif.addEventListener('click', cb);
    },
    onDismiss: (cb) => {
      notif.addEventListener('close', cb);
    },
    close: () => {
      notif.close();
    },
  };
}

const NotificationInterfaceContext = createContext<
  PlatformNotificationInterface | NotificationUnsupported
>('not-supported');

/// this hook gives you access to the raw notification inteferface which is probably not what you want
// you are probably looking for useNotificationState which handles UI disabled notifications
function usePlatformNotifications():
  | PlatformNotificationInterface
  | NotificationUnsupported {
  const platformNotif = useContext(NotificationInterfaceContext);

  if (platformNotif === undefined) {
    throw new Error(
      'usePlatformNotification did not find a parent NoticationProvider. Please verify the structure of the component tree'
    );
  }

  return platformNotif;
}

type UiDisabled = 'disabled-in-ui';
type UserSetting = 'allowed' | UiDisabled;

export interface PlatformNotificationState {
  permission: Accessor<NotificationPermission | UiDisabled>;
  requestPermission: () => Promise<NotificationPermission>;
  unregisterNotification: () => Promise<void>;
  showNotification: (
    data: PlatformNotificationData
  ) => Promise<PlatformNotificationHandle | NotGranted | UiDisabled>;
}

const NotificationStateContext = createContext<
  PlatformNotificationState | NotificationUnsupported | undefined
>(undefined);

export function usePlatformNotificationState():
  | PlatformNotificationState
  | NotificationUnsupported {
  const res = useContext(NotificationStateContext);
  if (res === undefined) {
    console.error(
      new Error(
        'tried to useNotificationState outside of a NotificationStateProvider'
      )
    );
    return 'not-supported';
  }
  return res;
}

function PlatformNotificationState(props: {
  children: JSX.Element;
  manuallyDisabled: Accessor<UserSetting>;
  setManuallyDisabled: Setter<UserSetting>;
}) {
  const platformNotif = usePlatformNotifications();

  // this is not a reactive value (can't change) so we can have conditional hooks
  if (platformNotif === 'not-supported') {
    return props.children;
  }

  const [permission, { refetch }] = createResource(
    props.manuallyDisabled,
    async (disabled) => {
      if (disabled === 'disabled-in-ui') {
        return disabled;
      }
      return await platformNotif.getCurrentPermission();
    }
  );

  function currentPermission(): NotificationPermission | UiDisabled {
    // A failed native read must leave the setting usable so the user can
    // retry. Reading resource.latest directly would throw into the UI.
    if (permission.error !== undefined) return 'denied';
    return permission.latest ?? 'default';
  }

  async function refreshPermission() {
    try {
      await refetch();
    } catch {
      // currentPermission exposes a failed read as denied, without breaking UI.
    }
  }

  // System Settings can change authorization while this app is open.
  makeEventListener(window, 'focus', refreshPermission);

  async function requestPermission() {
    if (platformNotif === 'not-supported') {
      console.warn(
        'requested notification permission on an unsupported platform'
      );
      return 'denied';
    }
    props.setManuallyDisabled('allowed');
    const res = await platformNotif.requestPermission();
    await refetch();
    if (permission.error !== undefined) throw permission.error;
    return res;
  }

  async function showNotification(
    data: PlatformNotificationData
  ): Promise<PlatformNotificationHandle | NotGranted | UiDisabled> {
    const manuallyDisabled = props.manuallyDisabled();
    if (manuallyDisabled === 'disabled-in-ui') {
      return manuallyDisabled;
    }

    if (currentPermission() !== 'granted') {
      await refreshPermission();
    }
    if (props.manuallyDisabled() === 'disabled-in-ui') {
      return 'disabled-in-ui';
    }

    if (
      currentPermission() !== 'granted' ||
      platformNotif === 'not-supported'
    ) {
      return 'not-granted';
    }

    return await platformNotif.showNotification(data);
  }

  return (
    <NotificationStateContext.Provider
      value={{
        permission: currentPermission,
        requestPermission,
        unregisterNotification: platformNotif.unregisterNotifications,
        showNotification,
      }}
    >
      {props.children}
    </NotificationStateContext.Provider>
  );
}

export function PlatformNotificationProvider(props: {
  children: JSX.Element;
  overrideDefault?: CreateAppNotificationInterface;
}) {
  const [manuallyDisabled, setManuallyDisabled] = makePersisted(
    createSignal<UserSetting>('allowed'),
    { name: 'notification-manually-disabled' }
  );

  const setDisabled = async () => {
    setManuallyDisabled('disabled-in-ui');
  };

  const value = (props.overrideDefault ?? createDefaultBrowserInterface)(
    setDisabled,
    () => manuallyDisabled() !== 'disabled-in-ui'
  );

  return (
    <NotificationInterfaceContext.Provider value={value}>
      <PlatformNotificationState
        manuallyDisabled={manuallyDisabled}
        setManuallyDisabled={setManuallyDisabled}
      >
        {props.children}
      </PlatformNotificationState>
    </NotificationInterfaceContext.Provider>
  );
}