Skip to content

Commit

Permalink
Merge pull request #28 from knovator/widget-setup
Browse files Browse the repository at this point in the history
Widget Architecture setup
  • Loading branch information
chavda-bhavik authored Oct 25, 2022
2 parents a120bad + 9c6f75d commit ce1a76b
Show file tree
Hide file tree
Showing 63 changed files with 12,480 additions and 4,017 deletions.
38 changes: 38 additions & 0 deletions apps/widget/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
module.exports = {
rules: {
'func-names': 'off',
'react/jsx-props-no-spreading': 'off',
'react/no-array-index-key': 'off',
'no-empty-pattern': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'react/no-unescaped-entities': 'off',
'react/jsx-closing-bracket-location': 'off',
'@typescript-eslint/ban-types': 'off',
'react/jsx-wrap-multilines': 'off',
'jsx-a11y/anchor-is-valid': 'off',
'promise/catch-or-return': 'off',
'react/jsx-one-expression-per-line': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'jsx-a11y/aria-role': 'off',
'jsx-a11y/no-static-element-interactions': 'off',
'react/require-default-props': 'off',
'react/no-danger': 'off',
'jsx-a11y/click-events-have-key-events': 'off',
'@typescript-eslint/naming-convention': [
'error',
{
filter: '_',
selector: 'variableLike',
leadingUnderscore: 'allow',
format: ['PascalCase', 'camelCase', 'UPPER_CASE'],
},
],
},
ignorePatterns: ['craco.config.js'],
extends: ['../../.eslintrc.js'],
parserOptions: {
project: './tsconfig.json',
ecmaVersion: 2020,
sourceType: 'module',
},
};
5 changes: 5 additions & 0 deletions apps/widget/craco.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
babel: {
plugins: [],
},
};
55 changes: 55 additions & 0 deletions apps/widget/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "@impler/widget",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "craco start",
"start:dev": "cross-env PORT=3500 pnpm start",
"preinstall": "pnpm build",
"prebuild": "rimraf build",
"build": "craco build",
"test": "craco test",
"precommit": "lint-staged",
"eject": "craco eject",
"lint": "eslint src"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint"
]
},
"dependencies": {
"@craco/craco": "^6.4.5",
"@impler/shared": "workspace:^1.0.0",
"@mantine/core": "^5.6.1",
"axios": "^1.1.3",
"cross-env": "^7.0.3",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-router-dom": "^6.4.2",
"react-scripts": "5.0.1",
"rimraf": "^3.0.2",
"styled-components": "^5.3.6",
"web-vitals": "^3.0.4",
"webfontloader": "^1.6.28",
"webpack-dev-server": "^4.11.1"
},
"devDependencies": {
"@types/react": "^18.0.21",
"@types/react-dom": "^18.0.6",
"@types/styled-components": "^5.1.26",
"typescript": "^4.8.3"
}
}
Binary file added apps/widget/public/favicon.ico
Binary file not shown.
45 changes: 45 additions & 0 deletions apps/widget/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Impler Widget</title>
<!-- <script src="%PUBLIC_URL%/env-config.js"></script> -->
</head>

<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<!-- <script type="text/javascript" src="%PUBLIC_URL%/iframeResizer.contentWindow.js" defer></script> -->
</body>

</html>
Binary file added apps/widget/public/logo192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/widget/public/logo512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions apps/widget/public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "Impler",
"name": "Impler",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
3 changes: 3 additions & 0 deletions apps/widget/public/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
15 changes: 15 additions & 0 deletions apps/widget/src/client/api.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { HttpClient } from './http-client';

export class ApiService {
private httpClient: HttpClient;

isAuthenticated = false;

constructor(private backendUrl: string) {
this.httpClient = new HttpClient(backendUrl);
}

async getProjectTemplates(projectId: string) {
return this.httpClient.get(`/template/${projectId}`);
}
}
35 changes: 35 additions & 0 deletions apps/widget/src/client/http-client/api.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import axios, { AxiosInstance } from 'axios';

export interface IParamObject {
[key: string]: string | string[] | number | boolean;
}

export class HttpClient {
private axiosClient: AxiosInstance;

constructor(private backendUrl: string) {
this.axiosClient = axios.create({
baseURL: backendUrl + '/v1',
});
}

async get(url: string, params?: IParamObject) {
return await this.axiosClient
.get(url, {
params,
})
.then((response) => response.data.data);
}

async post(url: string, body = {}) {
return await this.axiosClient.post(url, body).then((response) => response.data.data);
}

async patch(url: string, body = {}) {
return await this.axiosClient.patch(url, body).then((response) => response.data.data);
}

async delete(url: string) {
return await this.axiosClient.delete(url).then((response) => response.data.data);
}
}
1 change: 1 addition & 0 deletions apps/widget/src/client/http-client/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './api.client';
1 change: 1 addition & 0 deletions apps/widget/src/client/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { ApiService } from './api.service';
22 changes: 22 additions & 0 deletions apps/widget/src/components/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { WidgetShell } from './ApplicationShell';
import { NotificationCenterWidgetContainer } from './widget';
import { CONTEXT_PATH } from '../config';

export function App() {
return (
<Router basename={CONTEXT_PATH}>
<Routes>
<Route
path="/:projectId"
element={
<WidgetShell>
<NotificationCenterWidgetContainer />
</WidgetShell>
}
/>
</Routes>
</Router>
);
}
51 changes: 51 additions & 0 deletions apps/widget/src/components/ApplicationShell.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React, { useEffect } from 'react';
import styled, { createGlobalStyle } from 'styled-components';

export function WidgetShell({ children }: { children: JSX.Element }) {
const WrapperComponent = inIframe() ? TransparentShell : MockPreviewShell;

return <WrapperComponent>{children}</WrapperComponent>;
}

function TransparentShell({ children }: { children: JSX.Element }) {
return <div style={{ padding: 7 }}>{children}</div>;
}

function MockPreviewShell({ children }: { children: JSX.Element }) {
useEffect(() => {
if (document.querySelector('body')) {
(document.querySelector('body') as HTMLBodyElement).style.width = 'auto';
}
}, []);

return (
<ShellWrapper>
<GlobalStyle />
{children}
</ShellWrapper>
);
}

function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}

const ShellWrapper = styled.div`
background: lightgrey;
height: 100vh;
padding: 7px;
color: #333737;
`;
const GlobalStyle = createGlobalStyle`
body {
padding: 0;
margin: 0;
}
* {
box-sizing: border-box;
}
`;
81 changes: 81 additions & 0 deletions apps/widget/src/components/widget/Widget.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { useEffect, useState } from 'react';
import * as WebFont from 'webfontloader';
import { API_URL } from '../../config';
import { createGlobalStyle } from 'styled-components';
import { WidgetProvider } from './WidgetProvider';
import { IUserDataPayload } from '@impler/shared';

interface IWidgetProps {
projectId: string;
}

export function Widget(props: IWidgetProps) {
const [userDataPayload, setUserDataPayload] = useState<IUserDataPayload>();
const [backendUrl, setBackendUrl] = useState(API_URL);
// const [theme, setTheme] = useState<>({});
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
const [fontFamily, setFontFamily] = useState<string>('Lato');
const [frameInitialized, setFrameInitialized] = useState(false);

useEffect(() => {
WebFont.load({
google: {
families: [fontFamily],
},
});
}, [fontFamily]);

useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handler = ({ data }: any) => {
if (data && data.type === 'INIT_IFRAME') {
setUserDataPayload(data.value);

if (data.value.backendUrl) {
setBackendUrl(data.value.backendUrl);
}

setFrameInitialized(true);
}
};

if (process.env.NODE_ENV === 'test') {
// eslint-disable-next-line
(window as any).initHandler = handler;
}

window.addEventListener('message', handler);

window.parent.postMessage({ type: 'WIDGET_READY' }, '*');

return () => window.removeEventListener('message', handler);
}, []);

if (!userDataPayload) return null;

return (
<>
<GlobalStyle fontFamily={fontFamily} />
{frameInitialized ? (
<WidgetProvider
// api
backendUrl={backendUrl}
// impler-context
projectId={props.projectId}
template={userDataPayload.template}
accessToken={userDataPayload.accessToken}
authHeaderValue={userDataPayload.authHeaderValue}
extra={userDataPayload.extra}
>
<h1>Widget</h1>
</WidgetProvider>
) : null}
</>
);
}

const GlobalStyle = createGlobalStyle<{ fontFamily: string }>`
body {
font-family: ${({ fontFamily }) => fontFamily}, Helvetica, sans-serif;
}
`;
8 changes: 8 additions & 0 deletions apps/widget/src/components/widget/WidgetContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Widget } from './Widget';
import { useParams } from 'react-router-dom';

export function NotificationCenterWidgetContainer() {
const { projectId = '' } = useParams<{ projectId: string }>();

return <Widget projectId={projectId} />;
}
Loading

0 comments on commit ce1a76b

Please sign in to comment.