Skip to content

Commit

Permalink
Merge pull request #558 from fairDataSociety/feat/optional-matomo
Browse files Browse the repository at this point in the history
Feat/optional matomo
  • Loading branch information
tomicvladan authored Oct 27, 2023
2 parents 30e3640 + 934d452 commit e09ca31
Show file tree
Hide file tree
Showing 16 changed files with 124 additions and 23 deletions.
28 changes: 28 additions & 0 deletions src/components/Forms/LoginForm/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ import { Network } from '@data/networks';
import NetworkDropdown from '@components/Dropdowns/NetworkDropdown/NetworkDropdown';
import { setDefaultNetwork } from '@utils/localStorage';
import { useLocales } from '@context/LocalesContext';
import CustomCheckbox from '@components/Inputs/CustomCheckbox/CustomCheckbox';
import { useMatomoContext } from '@context/Matomo';

const ALLOW_TRACKING_KEY = 'allow-matomo';

function getDefaultTrackingValue(): boolean {
const enabled = localStorage.getItem(ALLOW_TRACKING_KEY);

return enabled === 'true' || enabled === null ? true : false;
}

const LoginForm: FC = () => {
const CREATE_USER_URL = process.env.NEXT_PUBLIC_CREATE_ACCOUNT_REDIRECT;
Expand All @@ -26,8 +36,10 @@ const LoginForm: FC = () => {
const { errors, isValid } = formState;

const { setUser, errorMessage, setErrorMessage } = useContext(UserContext);
const [allowTracking, setAllowTracking] = useState(getDefaultTrackingValue());
const [network, setNetwork] = useState<Network>(getDefaultNetwork());
const [loading, setLoading] = useState<boolean>(false);
const { setEnabled } = useMatomoContext();

const {
fdpClientRef,
Expand All @@ -46,6 +58,7 @@ const LoginForm: FC = () => {
setErrorMessage(null);
const { user_name, password } = data;
setFdpStorageType('native', network.config);
setEnabled(allowTracking);
const wallet = await fdpClientRef.current.account.login(
user_name,
password
Expand All @@ -67,6 +80,12 @@ const LoginForm: FC = () => {
setNetwork(network);
};

const onAllowTrackingClick = () => {
const enabled = !allowTracking;
setAllowTracking(enabled);
localStorage.setItem(ALLOW_TRACKING_KEY, String(enabled));
};

useEffect(() => {
setErrorMessage(null);
}, []);
Expand Down Expand Up @@ -154,6 +173,15 @@ const LoginForm: FC = () => {
error={errors.password}
/>

<CustomCheckbox
className="mb-3 sm:mb-0"
name="confirm"
onChange={onAllowTrackingClick}
checked={allowTracking}
>
{intl.get('ALLOW_TRACKING')}
</CustomCheckbox>

<div className="mt-8 text-center">
<Button
loading={loading}
Expand Down
5 changes: 4 additions & 1 deletion src/components/Inputs/CustomCheckbox/CustomCheckbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ const CustomCheckbox: FC<CheckboxProps> = ({
)}
</div>

<label className="mr-2 font-normal text-color-accents-plum-black dark:text-color-accents-soft-lavender text-xs">
<label
htmlFor={name}
className="mr-2 font-normal text-color-accents-plum-black dark:text-color-accents-soft-lavender text-xs"
>
{children}
</label>
</div>
Expand Down
72 changes: 65 additions & 7 deletions src/context/Matomo.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
import { FC } from 'react';
import { MatomoProvider, createInstance } from '@datapunt/matomo-tracker-react';
/* eslint-disable @typescript-eslint/no-empty-function */
import { createContext, useContext, useState } from 'react';
import {
MatomoProvider as OriginalMatomoProvider,
createInstance,
} from '@datapunt/matomo-tracker-react';

type MatomoTracker = ReturnType<typeof createInstance>;
export interface MatomoProps {
children: React.ReactNode | React.ReactNode[];
}

const Matomo: FC<MatomoProps> = ({ children }) => {
const instance = createInstance({
export interface IMatomoContext {
instance: MatomoTracker;
setEnabled: (enable: boolean) => void;
}

const MatomoContext = createContext<IMatomoContext>({
instance: null,
setEnabled: () => {},
});

function createMatomoTracker() {
return createInstance({
urlBase: 'https://mtm.swarm.foundation/',
siteId: 7,
heartBeat: {
Expand All @@ -20,8 +35,51 @@ const Matomo: FC<MatomoProps> = ({ children }) => {
setRequestMethod: 'POST',
},
});
}

return <MatomoProvider value={instance}>{children}</MatomoProvider>;
};
function createMatomoTrackerMock() {
return {
enableHeartBeatTimer: () => {},
enableLinkTracking: () => {},
trackEvents: () => {},
stopObserving: () => {},
trackEvent: () => {},
trackSiteSearch: () => {},
trackLink: () => {},
trackPageView: () => {},
addEcommerceItem: () => {},
removeEcommerceItem: () => {},
clearEcommerceCart: () => {},
trackEcommerceOrder: () => {},
trackEcommerceCartUpdate: () => {},
setEcommerceView: () => {},
setEcommerceCategoryView: () => {},
track: () => {},
pushInstruction: () => {},
} as unknown as MatomoTracker;
}

export const useMatomoContext = () => useContext(MatomoContext);

export const MatomoProvider = ({ children }: MatomoProps) => {
const [instance, setInstance] = useState<MatomoTracker>(
createMatomoTrackerMock()
);

export default Matomo;
const setEnabled = (enabled: boolean) => {
setInstance(enabled ? createMatomoTracker() : createMatomoTrackerMock());
};

return (
<MatomoContext.Provider
value={{
instance,
setEnabled,
}}
>
<OriginalMatomoProvider value={instance}>
{children}
</OriginalMatomoProvider>
</MatomoContext.Provider>
);
};
3 changes: 2 additions & 1 deletion src/locales/ch-CH.json
Original file line number Diff line number Diff line change
Expand Up @@ -223,5 +223,6 @@
"ROOT_DIRECTORY": "根目录 ",
"INVITES_TOOLTIP": "邀请简化了入门过程!分享邀请链接,让朋友们即时访问预先充值的钱包。",
"INVITES_DESCRIPTION": "我们的邀请制度旨在使新用户的入门过程变得无缝。当您创建邀请时,您实际上是生成了一个嵌入预先充值钱包的私钥的推荐链接。通过与朋友或同事共享此链接,您可以让他们立即访问并开始使用已配置好的服务。这不仅可以帮助他们避免初次设置的麻烦,还可以更快地推动他们使用我们的平台。",
"NEW_FOLDER": "新建文件夹"
"NEW_FOLDER": "新建文件夹",
"ALLOW_TRACKING": "允许该应用以匿名方式跟踪您的活动。"
}
3 changes: 2 additions & 1 deletion src/locales/de-DE.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Stammverzeichnis",
"INVITES_TOOLTIP": "Einladungen erleichtern den Einstieg! Teile einen Einladungslink, um Freunden sofortigen Zugang zu einem vorgefundenen Wallet zu geben.",
"INVITES_DESCRIPTION": "Unser Einladungssystem ist darauf ausgelegt, den Einstieg für neue Benutzer nahtlos zu gestalten. Wenn Sie eine Einladung erstellen, generieren Sie im Wesentlichen einen Empfehlungslink, der mit einem privaten Schlüssel zu einer vorgefundenen Brieftasche versehen ist. Durch das Teilen dieses Links mit Freunden oder Kollegen ermöglichen Sie ihnen den sofortigen Zugang und die sofortige Nutzung unseres Dienstes mit bereits vorhandenen Mitteln. Dies erleichtert nicht nur die Erstkonfiguration, sondern fördert auch die schnellere Nutzung unserer Plattform.",
"NEW_FOLDER": "Neuer Ordner"
"NEW_FOLDER": "Neuer Ordner",
"ALLOW_TRACKING": "Erlauben Sie der App, Ihre Aktivitäten in anonymer Weise zu verfolgen."
}
3 changes: 2 additions & 1 deletion src/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Root directory",
"INVITES_TOOLTIP": "Invites simplify onboarding! Share an invite link to give friends instant access to a pre-funded wallet.",
"INVITES_DESCRIPTION": "Our invitation system is designed to make the onboarding process seamless for new users. When you create an invite, you're essentially generating a referral link embedded with a private key to a pre-funded wallet. By sharing this link with friends or colleagues, you give them immediate access to start using the service with funds already in place. This not only helps them bypass the initial setup hassles but also encourages quicker adoption and usage of our platform.",
"NEW_FOLDER": "New Folder"
"NEW_FOLDER": "New Folder",
"ALLOW_TRACKING": "Allow the app to track your activities in an anonymous manner."
}
3 changes: 2 additions & 1 deletion src/locales/es-ES.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Directorio raíz",
"INVITES_TOOLTIP": "¡Las invitaciones simplifican el proceso de incorporación! Comparte un enlace de invitación para dar a tus amigos acceso instantáneo a una billetera prefinanciada.",
"INVITES_DESCRIPTION": "Nuestro sistema de invitación está diseñado para hacer que el proceso de incorporación sea fluido para los nuevos usuarios. Al crear una invitación, esencialmente estás generando un enlace de referencia incrustado con una clave privada para una billetera prefinanciada. Al compartir este enlace con amigos o colegas, les das acceso inmediato para empezar a usar el servicio con fondos ya establecidos. Esto no solo les ayuda a evitar las complicaciones de la configuración inicial, sino que también fomenta una adopción y uso más rápidos de nuestra plataforma.",
"NEW_FOLDER": "Nueva Carpeta"
"NEW_FOLDER": "Nueva Carpeta",
"ALLOW_TRACKING": "Permita que la aplicación rastree sus actividades de manera anónima."
}
3 changes: 2 additions & 1 deletion src/locales/fr-FR.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Répertoire racine",
"INVITES_TOOLTIP": "Les invitations simplifient l'intégration ! Partagez un lien d'invitation pour offrir à vos amis un accès instantané à un portefeuille préfinancé.",
"INVITES_DESCRIPTION": "Notre système d'invitation est conçu pour faciliter l'intégration des nouveaux utilisateurs. Lorsque vous créez une invitation, vous générez essentiellement un lien de parrainage intégré avec une clé privée pour un portefeuille préfinancé. En partageant ce lien avec des amis ou des collègues, vous leur donnez un accès immédiat pour commencer à utiliser le service avec des fonds déjà en place. Cela les aide non seulement à éviter les tracas de la configuration initiale, mais encourage également une adoption et une utilisation plus rapides de notre plateforme.",
"NEW_FOLDER": "Nouveau Dossier"
"NEW_FOLDER": "Nouveau Dossier",
"ALLOW_TRACKING": "Autorisez l'application à suivre vos activités de manière anonyme."
}
3 changes: 2 additions & 1 deletion src/locales/hu-HU.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Gyökérkönyvtár",
"INVITES_TOOLTIP": "Az meghívók egyszerűsítik a bekapcsolódást! Ossz meg egy meghívó linket, hogy barátaid azonnal hozzáférjenek egy előre finanszírozott tárcához.",
"INVITES_DESCRIPTION": "A meghívó rendszerünk arra lett tervezve, hogy az új felhasználók számára gördülékenyebbé tegye az első lépéseket. Egy meghívó létrehozásakor lényegében egy olyan hivatkozási linket generálsz, amely egy előre finanszírozott tárcához tartozó privát kulccsal van ellátva. Ennek a linknek a megosztásával azonnali hozzáférést és a már meglévő alapokkal történő szolgáltatás használatát teszed lehetővé barátaid vagy kollégáid számára. Ez nem csak az első beállításokkal járó bonyodalmakat hárítja el, de gyorsabbá is teszi platformunk elfogadását és használatát.",
"NEW_FOLDER": "Új Mappa"
"NEW_FOLDER": "Új Mappa",
"ALLOW_TRACKING": "Engedélyezze az alkalmazásnak, hogy anonim módon kövesse nyomon tevékenységeit."
}
3 changes: 2 additions & 1 deletion src/locales/it-IT.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Directory principale",
"INVITES_TOOLTIP": "Gli inviti semplificano l'accesso! Condividi un link di invito per fornire agli amici un accesso immediato a un portafoglio prefinanziato.",
"INVITES_DESCRIPTION": "Il nostro sistema di inviti è progettato per rendere fluido il processo di integrazione per i nuovi utenti. Creando un invito, stai essenzialmente generando un link di riferimento incastonato con una chiave privata per un portafoglio prefinanziato. Condividendo questo link con amici o colleghi, dai loro accesso immediato per iniziare a utilizzare il servizio con fondi già presenti. Questo non solo aiuta a evitare i problemi della configurazione iniziale, ma incoraggia anche una più rapida adozione e utilizzo della nostra piattaforma.",
"NEW_FOLDER": "Nuova Cartella"
"NEW_FOLDER": "Nuova Cartella",
"ALLOW_TRACKING": "Permetti all'app di tracciare le tue attività in modo anonimo."
}
3 changes: 2 additions & 1 deletion src/locales/jp-JP.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "ルートディレクトリ",
"INVITES_TOOLTIP": "招待はオンボーディングを簡単にします!招待リンクを共有して、友達にプレファンデッドのウォレットへの瞬時のアクセスを提供します。",
"INVITES_DESCRIPTION": "当社の招待制度は、新規ユーザーのオンボーディングプロセスをスムーズにするよう設計されています。招待を作成すると、基本的にはプレファンデッドウォレットへのプライベートキーが埋め込まれた紹介リンクを生成します。このリンクを友達や同僚と共有することで、既に用意されている資金でサービスをすぐに利用できるようになります。これは初期設定の手間を省くだけでなく、当社のプラットフォームのより迅速な採用と利用を促進します。",
"NEW_FOLDER": "新しいフォルダ"
"NEW_FOLDER": "新しいフォルダ",
"ALLOW_TRACKING": "アプリが匿名であなたの活動を追跡することを許可します。"
}
3 changes: 2 additions & 1 deletion src/locales/pt-PT.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Diretório raiz",
"INVITES_TOOLTIP": "Convites simplificam a integração! Compartilhe um link de convite para dar aos seus amigos acesso imediato a uma carteira pré-financiada.",
"INVITES_DESCRIPTION": "O nosso sistema de convites foi projetado para tornar o processo de integração transparente para novos usuários. Ao criar um convite, você está essencialmente gerando um link de referência embutido com uma chave privada para uma carteira pré-financiada. Ao compartilhar este link com amigos ou colegas, você lhes dá acesso imediato para começar a usar o serviço com fundos já estabelecidos. Isso não só ajuda a evitar as complicações da configuração inicial, como também incentiva uma adoção e uso mais rápidos da nossa plataforma.",
"NEW_FOLDER": "Nova Pasta"
"NEW_FOLDER": "Nova Pasta",
"ALLOW_TRACKING": "Permita que o aplicativo rastreie suas atividades de forma anônima."
}
3 changes: 2 additions & 1 deletion src/locales/rs-RS.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Koreni direktorijum",
"INVITES_TOOLTIP": "Pozivi olakšavaju početni pristup! Podelite pozivnički link da biste prijateljima omogućili trenutan pristup prethodno finansiranom novčaniku.",
"INVITES_DESCRIPTION": "Naš sistem pozivnica je dizajniran da novim korisnicima olakša proces uključivanja. Kada kreirate pozivnicu, u suštini generišete referalni link sa ugrađenim privatnim ključem za unapred finansiran novčanik. Deljenjem ovog linka sa prijateljima ili kolegama, omogućavate im trenutan pristup i početak korišćenja servisa sa već postojećim sredstvima. Ovo ne samo da im pomaže da izbegnu komplikacije početnog podešavanja, već i podstiče bržu usvajanje i korišćenje naše platforme.",
"NEW_FOLDER": "Novi direktorijum"
"NEW_FOLDER": "Novi direktorijum",
"ALLOW_TRACKING": "Dozvolite aplikaciji da prati vaše aktivnosti na anoniman način."
}
3 changes: 2 additions & 1 deletion src/locales/sl-SI.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Koreninski imenik",
"INVITES_TOOLTIP": "Vabila poenostavijo postopek vključevanja! Delite povezavo za vabilo, da svojim prijateljem omogočite takojšen dostop do prednaložene denarnice.",
"INVITES_DESCRIPTION": "Naš sistem vabil je zasnovan tako, da novim uporabnikom olajša postopek vključevanja. Ko ustvarite vabilo, v bistvu generirate napotnično povezavo, vgrajeno s privatnim ključem za predhodno financirano denarnico. Z deljenjem te povezave s prijatelji ali kolegi jim omogočate takojšen dostop in začetek uporabe storitve z že obstoječimi sredstvi. To ne le olajša začetne težave z nastavitvami, ampak tudi spodbuja hitrejše sprejetje in uporabo naše platforme.",
"NEW_FOLDER": "Nova mapa"
"NEW_FOLDER": "Nova mapa",
"ALLOW_TRACKING": "Dovolite aplikaciji, da sledi vašim dejavnostim na anonimen način."
}
3 changes: 2 additions & 1 deletion src/locales/tr-TR.json
Original file line number Diff line number Diff line change
Expand Up @@ -224,5 +224,6 @@
"ROOT_DIRECTORY": "Kök dizin",
"INVITES_TOOLTIP": "Davetiyeler katılım sürecini kolaylaştırır! Arkadaşlarınıza önceden finanse edilmiş bir cüzdana anında erişim sağlamak için bir davet bağlantısı paylaşın.",
"INVITES_DESCRIPTION": "Davet sistemimiz, yeni kullanıcıların hızlı bir şekilde sisteme dahil olmalarını sağlamak amacıyla tasarlanmıştır. Bir davet oluşturduğunuzda, esasen önceden finanse edilmiş bir cüzdana özel anahtar ile kodlanmış bir referans bağlantısı oluşturmuş olursunuz. Bu bağlantıyı arkadaşlarınızla veya meslektaşlarınızla paylaşarak, hemen kullanmaya başlayabilecekleri ve zaten var olan fonlarla hizmetimizi kullanmalarını sağlarsınız. Bu, sadece ilk kurulumun karmaşıklığını ortadan kaldırmakla kalmaz, aynı zamanda platformumuzu daha hızlı benimsemelerini ve kullanmalarını teşvik eder.",
"NEW_FOLDER": "Yeni Klasör"
"NEW_FOLDER": "Yeni Klasör",
"ALLOW_TRACKING": "Uygulamanın etkinliklerinizi anonim bir şekilde izlemesine izin verin."
}
6 changes: 3 additions & 3 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Head from 'next/head';
import { AppProps } from 'next/app';

import Matomo from '@context/Matomo';
import { MatomoProvider } from '@context/Matomo';
import { ThemeProvider } from '@context/ThemeContext';
import { UserProvider } from '@context/UserContext';
import { SearchProvider } from '@context/SearchContext';
Expand Down Expand Up @@ -47,7 +47,7 @@ function MyApp({ Component, pageProps, router }: AppProps) {
<MetamaskProvider>
<LocalesProvider>
<FdpStorageProvider>
<Matomo>
<MatomoProvider>
<ThemeProvider>
<UserProvider>
<SearchProvider>
Expand All @@ -65,7 +65,7 @@ function MyApp({ Component, pageProps, router }: AppProps) {
</SearchProvider>
</UserProvider>
</ThemeProvider>
</Matomo>
</MatomoProvider>
</FdpStorageProvider>
</LocalesProvider>
</MetamaskProvider>
Expand Down

0 comments on commit e09ca31

Please sign in to comment.