diff --git a/.changeset/README.md b/.changeset/README.md new file mode 100644 index 0000000..e5b6d8d --- /dev/null +++ b/.changeset/README.md @@ -0,0 +1,8 @@ +# Changesets + +Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works +with multi-package repos, or single-package repos to help you version and publish your code. You can +find the full documentation for it [in our repository](https://github.com/changesets/changesets) + +We have a quick list of common questions to get you started engaging with this project in +[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/.changeset/config.json b/.changeset/config.json new file mode 100644 index 0000000..4911e25 --- /dev/null +++ b/.changeset/config.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@2.2.0/schema.json", + "changelog": "@changesets/cli/changelog", + "commit": false, + "fixed": [], + "linked": [], + "access": "public", + "baseBranch": "main", + "updateInternalDependencies": "patch", + "ignore": ["web", "desktop"] +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..fac40a5 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..a456913 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +github: daltonmenezes +patreon: daltonmenezes +issuehunt: daltonmenezes/interprocess?tab=idle diff --git a/.github/workflows/gh-page.yml b/.github/workflows/gh-page.yml new file mode 100644 index 0000000..f311d4f --- /dev/null +++ b/.github/workflows/gh-page.yml @@ -0,0 +1,90 @@ +name: Release GH Page + +on: + workflow_dispatch: + release: + types: + - "published" + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: "pages" + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Detect package manager + id: detect-package-manager + run: | + if [ -f "${{ github.workspace }}/yarn.lock" ]; then + echo "::set-output name=manager::yarn" + echo "::set-output name=command::install" + echo "::set-output name=runner::yarn" + exit 0 + elif [ -f "${{ github.workspace }}/package.json" ]; then + echo "::set-output name=manager::npm" + echo "::set-output name=command::ci" + echo "::set-output name=runner::npx --no-install" + exit 0 + else + echo "Unable to determine packager manager" + exit 1 + fi + + - name: Setup Node + uses: actions/setup-node@v3 + with: + node-version: "16" + cache: ${{ steps.detect-package-manager.outputs.manager }} + + - name: Setup Pages + uses: actions/configure-pages@v2 + with: + token: ${{ secrets.GITHUB_TOKEN }} + static_site_generator: next + generator_config_file: ./apps/web/next.config.mjs + + - name: Restore cache + uses: actions/cache@v3 + with: + path: | + ./apps/web/.next/cache + key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json', '**/yarn.lock') }}-${{ hashFiles('**.[jt]s', '**.[jt]sx') }} + restore-keys: | + ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json', '**/yarn.lock') }}- + + - name: Install dependencies + run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }} + + - name: Build with Next.js + working-directory: ./apps/web + run: ${{ steps.detect-package-manager.outputs.runner }} next build + + - name: Static HTML export with Next.js + working-directory: ./apps/web + run: ${{ steps.detect-package-manager.outputs.runner }} next export + + - name: Upload artifact + uses: actions/upload-pages-artifact@v1 + with: + path: ./apps/web/out + + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..bb691e1 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,34 @@ +name: Release + +on: + workflow_dispatch: + release: + types: + - "published" + +concurrency: ${{ github.workflow }}-${{ github.ref }} + +jobs: + release: + name: Release + runs-on: ubuntu-latest + steps: + - name: Checkout Repo + uses: actions/checkout@v2 + + - name: Setup Node.js 16.x + uses: actions/setup-node@v2 + with: + node-version: 16.x + + - name: Install Dependencies + run: yarn + + - name: Create Release Pull Request or Publish to npm + id: changesets + uses: changesets/action@v1 + with: + publish: yarn release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d2ad679 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +node_modules/ +.pnp +.pnp.js + +# testing +coverage + +# next.js +.next/ +out/ +build +dist + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# local env files +.env.local +.env.development.local +.env.test.local +.env.production.local + +# turbo +.turbo diff --git a/.husky/.gitignore b/.husky/.gitignore new file mode 100644 index 0000000..31354ec --- /dev/null +++ b/.husky/.gitignore @@ -0,0 +1 @@ +_ diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 0000000..0bd658f --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +npx --no-install commitlint --edit "$1" diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 0000000..36af219 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +npx lint-staged diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2868bf9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 - * Dalton Menezes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..f1f59e6 --- /dev/null +++ b/README.md @@ -0,0 +1,155 @@ +

+ + preview + +

+ +

interprocess: 💬 A scalable and type-safe Electron IPC management tool with enhanced DX

+ +

+ + + github url + + + + patreon url + + + + releases url + + + + license url + +

+ +> Electron IPC is good, but difficult to maintain and scale, either because of the numerous channels you have to remember, or because of the inconsistent API between processes and the absence of inferred types of your channels and handlers. These are some of the things that interprocess comes to solve! + +# 💬 Features +- 🚀 Best-in-class DX with a fully-typed API +- 🧠 Enchanced and consistent API +- 🔥 Type-safe and scalable +- 🪄 Code splitting support +- 🕸️ All edges connected (APIs to handle all processes) +- 💖 `invoke` and `handle` methods in both processes with the same expected behavior + +# 💬 Installation +In your terminal, run: +```bash +yarn add interprocess + +# OR + +npm i interprocess +``` + +# 💬 Usage + +Let's build something simple that can show you some of the interprocess's power! + +First, create the following folders at `src`: + +- `shared/ipcs` (this folder structure is optional) + +Then, create a file named as `index.ts` in the `ipcs` folder with the following content: + +```ts +import { createInterprocess } from 'interprocess' + +const ipcs = createInterprocess({ + main: { + async getPing(_, data: 'ping') { + const message = `from renderer: ${data} on main process` + + console.log(message) + + return message + }, + }, + + renderer: { + async getPong(_, data: 'pong') { + const message = `from main: ${data} on renderer process` + + console.log(message) + + return message + }, + }, +}) + +export const { + ipcMain, + ipcRenderer, + exposeApiToGlobalWindow +} = ipcs +``` + +On the main process: + +```ts +import { BrowserWindow, app } from 'electron' +import { ipcMain } from 'shared/ipcs' + +app.whenReady().then(() => { + const mainWindow = new BrowserWindow({ + webPreferences: { + preload: path.join(__dirname, '../preload/index.js'), + sandbox: false, + }, + }) + + ipcMain.handle.getPing() + + mainWindow.on('ready-to-show', () => { + ipcMain.invoke.getPong(mainWindow, 'pong') + }) +}) +``` + +In the preload script: + +```ts +import { exposeApiToGlobalWindow } from 'shared/ipcs' + +declare global { + interface Window { + [key]: typeof api + } +} + +const { key, api } = exposeApiToGlobalWindow({ + exposeAll: true, // expose handlers and invokers, +}) +``` +On the renderer process: +```ts +const { invoke, handle } = window.api + +invoke.getPing('ping') +handle.getPong() +``` +This is a simple way to work with interprocess, but there's a lot of more cool features you can take advantage, like overrides, code splitting, invoker's response (for renderer and main process 🎉) and more. See the [Knowledge section for more](#-knowledge) + +# 💬 Knowledge +- [Docs](https://daltonmenezes.github.io/interprocess/docs/getting-started/overview) +- [Example (in-depth)](https://github.com/daltonmenezes/interprocess/tree/main/apps/desktop) + + +# 💬 Contributing +> **Note**: contributions are always welcome, but always **ask first**, — please — before work on a PR. + +That said, there's a bunch of ways you can contribute to this project, like by: + +- :beetle: Reporting a bug +- :page_facing_up: Improving the docs +- :rotating_light: Sharing this project and recommending it to your friends +- :dollar: Supporting this project on GitHub Sponsors or Patreon +- :bug: Funding an issue on IssueHunt +- :star2: Giving a star on this repository + +# License + +[MIT © Dalton Menezes](https://github.com/daltonmenezes/interprocess/blob/main/LICENSE) diff --git a/apps/desktop/.eslintrc.json b/apps/desktop/.eslintrc.json new file mode 100644 index 0000000..584242f --- /dev/null +++ b/apps/desktop/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "@daltonmenezes/eslint-config" +} diff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.ts new file mode 100644 index 0000000..d65b192 --- /dev/null +++ b/apps/desktop/electron.vite.config.ts @@ -0,0 +1,25 @@ +import { defineConfig, externalizeDepsPlugin } from 'electron-vite' +import tsconfigPathsPlugin from 'vite-tsconfig-paths' +import { resolve } from 'path' + +const tsconfigPaths = tsconfigPathsPlugin({ + projects: [resolve('tsconfig.json')], +}) + +export default defineConfig({ + main: { + plugins: [tsconfigPaths, externalizeDepsPlugin()], + }, + + preload: { + plugins: [tsconfigPaths, externalizeDepsPlugin()], + }, + + renderer: { + plugins: [tsconfigPaths], + + server: { + port: 4927, + }, + }, +}) diff --git a/apps/desktop/ensureTypesWorking.ts b/apps/desktop/ensureTypesWorking.ts new file mode 100644 index 0000000..73a9bd4 --- /dev/null +++ b/apps/desktop/ensureTypesWorking.ts @@ -0,0 +1,110 @@ +import { combineIpcs, createInterprocess, createIpcSlice } from 'interprocess' + +//////////////////////////////////// +////////// ipcs ////////// +//////////////////////////////////// + +const getPongSlice = createIpcSlice({ + main: { + async getPong(_, data: 'pong') { + return `from renderer: ping ${data} on main process` + }, + }, +}) + +const getPingSlice = createIpcSlice({ + renderer: { + async getPing(_, data: 'ping') { + return `from main: ${data} pong on renderer process` as const + }, + }, +}) + +const getHelloSlice = createIpcSlice({ + main: { + async getHello(_, data: 'pong') { + return `${data}` + }, + }, +}) + +// const { ipcMain, exposeApiToGlobalWindow } = combineIpcs( +// getPongSlice, +// getPingSlice, +// getHelloSlice +// ) + +const ipcs = createInterprocess({ + main: { + async getPing(_, data: 'ping') { + return `from renderer: ${data} on main process` + }, + }, + + renderer: { + async getPong(_, data: 'pong') { + return `from main: ${data} on renderer process` + }, + }, +}) + +export const { ipcMain, ipcRenderer, exposeApiToGlobalWindow } = ipcs + +//////////////////////////////////// +////////// main.ts ////////// +//////////////////////////////////// + +function registerIPCHandlers(window: Electron.BrowserWindow) { + ipcMain.handle.getPing(async (_, { getPing, data }) => { + const result = await getPing(_, data) + + console.log(result) + + ipcMain.invoke.getPong(window, 'pong') + ipcMain.remove.getPing() + + return result + }) +} + +//////////////////////////////////// +////////// preload.ts ////////// +//////////////////////////////////// + +declare global { + interface Window { + [key]: typeof api + } +} + +const { key, api } = exposeApiToGlobalWindow({ + apiKey: 'ensureApi', + exposeAll: true, + + append: { + world: 'world', + sayHello(data: 'hello world!') { + console.log(data) + }, + } as const, +}) + +//////////////////////////////////// +////////// renderer.ts ////////// +//////////////////////////////////// + +const { invoke, handle, remove, sayHello, world } = window.ensureApi + +invoke.getPing('ping') + +sayHello(`hello ${world}!`) + +handle.getPong(async (_, { getPong, data }) => { + const result = await getPong(_, data) + + console.log(result) + + remove.getPong() + + return result +}) diff --git a/apps/desktop/index.d.ts b/apps/desktop/index.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/apps/desktop/index.d.ts @@ -0,0 +1 @@ +/// diff --git a/apps/desktop/package.json b/apps/desktop/package.json new file mode 100644 index 0000000..f7fa6ce --- /dev/null +++ b/apps/desktop/package.json @@ -0,0 +1,40 @@ +{ + "name": "desktop", + "version": "0.1.0", + "private": true, + "main": "./out/main/index.js", + "license": "MIT", + "scripts": { + "start": "electron-vite preview", + "dev": "electron-vite dev --watch" + }, + "devDependencies": { + "@types/node": "^18.11.9", + "@typescript-eslint/eslint-plugin": "^5.42.1", + "@typescript-eslint/parser": "^5.42.1", + "electron": "^21.2.3", + "electron-builder": "^23.6.0", + "electron-vite": "^1.0.12", + "eslint": "^8.27.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^4.2.1", + "prettier": "^2.7.1", + "rollup-plugin-inject-process-env": "^1.3.1", + "typescript": "^4.8.4", + "vite": "^3.2.3", + "vite-tsconfig-paths": "^3.5.2", + "@daltonmenezes/eslint-config": "*", + "@daltonmenezes/ts-config": "*" + }, + "dependencies": { + "@electron-toolkit/preload": "^1.0.2", + "@electron-toolkit/utils": "^1.0.2", + "turbo": "1.5.6", + "interprocess": "*" + }, + "eslintIgnore": [ + "dist", + "out" + ] +} diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts new file mode 100644 index 0000000..64935ae --- /dev/null +++ b/apps/desktop/src/main/index.ts @@ -0,0 +1,54 @@ +import { electronApp, is } from '@electron-toolkit/utils' +import { app, BrowserWindow } from 'electron' +import path from 'path' + +import { registerIpcHandlers } from './ipc' + +function createMainWindow() { + const mainWindow = new BrowserWindow({ + minHeight: 400, + width: 700, + height: 450, + show: false, + backgroundColor: '#191622', + autoHideMenuBar: true, + title: 'Interprocess', + + webPreferences: { + preload: path.join(__dirname, '../preload/index.js'), + sandbox: false, + }, + }) + + registerIpcHandlers(mainWindow) + + mainWindow.on('ready-to-show', () => { + mainWindow.show() + + if (is.dev) { + mainWindow.webContents.openDevTools({ mode: 'detach' }) + } + }) + + if (is.dev && process.env.ELECTRON_RENDERER_URL) { + mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL) + } else { + mainWindow.loadFile(path.join(__dirname, '../renderer/index.html')) + } +} + +app.whenReady().then(() => { + electronApp.setAppUserModelId('com.electron') + + createMainWindow() + + app.on('activate', function () { + if (BrowserWindow.getAllWindows().length === 0) createMainWindow() + }) +}) + +app.on('window-all-closed', () => { + if (process.platform !== 'darwin') { + app.quit() + } +}) diff --git a/apps/desktop/src/main/ipc/index.ts b/apps/desktop/src/main/ipc/index.ts new file mode 100644 index 0000000..0d8d0ac --- /dev/null +++ b/apps/desktop/src/main/ipc/index.ts @@ -0,0 +1,20 @@ +import { ipcMain } from 'shared/ipcs' + +export function registerIpcHandlers(window: Electron.BrowserWindow) { + ipcMain.handle.getPing(async (_, { getPing, data }) => { + const response = await getPing(_, data) + + console.log(response) + + await ipcMain.invoke.getPong(window, 'pong') + ipcMain.remove.getPing() + + return 'The getPong ipc was removed' + }) + + // A simple way to use the registered handler is: + // + // ipcMain.handle.getPing() + // + // it is useful when you don't need to pass any special data from main to the handler +} diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts new file mode 100644 index 0000000..3ff6e4a --- /dev/null +++ b/apps/desktop/src/preload/index.ts @@ -0,0 +1,18 @@ +import { exposeApiToGlobalWindow } from 'shared/ipcs' + +declare global { + interface Window { + [key]: typeof api + } +} + +const { key, api } = exposeApiToGlobalWindow({ + exposeAll: true, + + append: { + hello: 'world', + sayHello(param: 'opa') { + console.log('hello ' + param) + }, + }, +}) diff --git a/apps/desktop/src/renderer/index.html b/apps/desktop/src/renderer/index.html new file mode 100644 index 0000000..5e9b7a0 --- /dev/null +++ b/apps/desktop/src/renderer/index.html @@ -0,0 +1,83 @@ + + + + + + + Interprocess + + + + +

Interprocess

+ + + +

+
+ + + + diff --git a/apps/desktop/src/renderer/index.ts b/apps/desktop/src/renderer/index.ts new file mode 100644 index 0000000..9288ca2 --- /dev/null +++ b/apps/desktop/src/renderer/index.ts @@ -0,0 +1,25 @@ +const Message = document.getElementById('message')! +const Button = document.getElementById('btn')! + +const { invoke, handle, remove } = window.api + +export async function invokeGetPingFromMainProcess() { + try { + const response = await invoke.getPing('ping') + + console.log(response) + } catch { + Message.textContent = 'The getPing ipc was removed' + } +} + +handle.getPong(async (_, { getPong, data }) => { + const response = await getPong(_, data) + + Message.textContent = response + remove.getPong() + + return 'The getPong ipc was removed' +}) + +Button.addEventListener('click', invokeGetPingFromMainProcess) diff --git a/apps/desktop/src/shared/ipcs/index.ts b/apps/desktop/src/shared/ipcs/index.ts new file mode 100644 index 0000000..d0ae1e5 --- /dev/null +++ b/apps/desktop/src/shared/ipcs/index.ts @@ -0,0 +1,9 @@ +import { combineIpcs } from 'interprocess' + +import { getPongIpcSlice } from './renderer' +import { getPingIpcSlice } from './main' + +export const { ipcMain, ipcRenderer, exposeApiToGlobalWindow } = combineIpcs( + getPongIpcSlice, + getPingIpcSlice +) diff --git a/apps/desktop/src/shared/ipcs/main/index.ts b/apps/desktop/src/shared/ipcs/main/index.ts new file mode 100644 index 0000000..b65ac28 --- /dev/null +++ b/apps/desktop/src/shared/ipcs/main/index.ts @@ -0,0 +1,9 @@ +import { createIpcSlice } from 'interprocess' + +export const getPingIpcSlice = createIpcSlice({ + main: { + async getPing(_, data: 'ping') { + return `from renderer: ${data} on main process` + }, + }, +}) diff --git a/apps/desktop/src/shared/ipcs/renderer/index.ts b/apps/desktop/src/shared/ipcs/renderer/index.ts new file mode 100644 index 0000000..096d850 --- /dev/null +++ b/apps/desktop/src/shared/ipcs/renderer/index.ts @@ -0,0 +1,9 @@ +import { createIpcSlice } from 'interprocess' + +export const getPongIpcSlice = createIpcSlice({ + renderer: { + async getPong(_, data: 'pong') { + return `from main: ${data} on renderer process` + }, + }, +}) diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json new file mode 100644 index 0000000..f53deaf --- /dev/null +++ b/apps/desktop/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "@daltonmenezes/ts-config/base.json", + "include": [ + "index.d.ts", + "**/*.ts", + "**/*.tsx" + ], + "compilerOptions": { + "module": "esnext", + "jsx": "preserve", + "noEmit": true, + "baseUrl": "./src" + } +} diff --git a/apps/web/.eslintrc.json b/apps/web/.eslintrc.json new file mode 100644 index 0000000..584242f --- /dev/null +++ b/apps/web/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "@daltonmenezes/eslint-config" +} diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..16ff3dd --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,36 @@ +# interprocess website + +This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file. + +[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`. + +The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. diff --git a/apps/web/docs/code-splitting/combineIpcs.mdx b/apps/web/docs/code-splitting/combineIpcs.mdx new file mode 100644 index 0000000..3cd81e0 --- /dev/null +++ b/apps/web/docs/code-splitting/combineIpcs.mdx @@ -0,0 +1,23 @@ +--- +title: combineIpcs +--- + +# combineIpcs +A function to combine IPCs from different sources created using `createIpcSlice`. + +This function replaces the `createInterprocess`! + +### Example +```ts +import { combineIpcs } from 'interprocess' + +import { getPongIpcSlice } from './renderer' +import { getPingIpcSlice } from './main' + +const combinedIpcs = combineIpcs( + getPongIpcSlice, + getPingIpcSlice +) + +export const { ipcMain, ipcRenderer, exposeApiToGlobalWindow } = combinedIpcs +``` diff --git a/apps/web/docs/code-splitting/createIpcSlice.mdx b/apps/web/docs/code-splitting/createIpcSlice.mdx new file mode 100644 index 0000000..8dd7170 --- /dev/null +++ b/apps/web/docs/code-splitting/createIpcSlice.mdx @@ -0,0 +1,41 @@ +--- +title: createIpcSlice +--- + +# createIpcSlice +A function that creates a slice of IPCs to be used by `combineIpcs`. + +### Example +`shared/ipcs/main/index.ts` + +
+ +```ts +import { createIpcSlice } from 'interprocess' + +export const getPingIpcSlice = createIpcSlice({ + main: { + async getPing(_, data: 'ping') { + return `from renderer: ${data} on main process` + }, + }, +}) +``` + +
+ +`shared/ipcs/renderer/index.ts` + +
+ +```ts +import { createIpcSlice } from 'interprocess' + +export const getPongIpcSlice = createIpcSlice({ + renderer: { + async getPong(_, data: 'pong') { + return `from main: ${data} on renderer process` + }, + }, +}) +``` diff --git a/apps/web/docs/createInterprocess/exposeApiToGlobalWindow.mdx b/apps/web/docs/createInterprocess/exposeApiToGlobalWindow.mdx new file mode 100644 index 0000000..8872160 --- /dev/null +++ b/apps/web/docs/createInterprocess/exposeApiToGlobalWindow.mdx @@ -0,0 +1,67 @@ +--- +title: exposeApiToGlobalWindow +--- + +# exposeApiToGlobalWindow +A function that exposes the IPC handlers to the global window object from the preload script + +
+ +## Params + +It takes a single object as a parameter with the following properties: + +
+ +- **apiKey** - the api key that will be used to access the IPC handlers from the global window object **(optional)** +- **exposeAll** - a boolean that determines whether all the IPC handlers will be exposed to the global window object **(optional)**. When set to true, invoke, handle and remove handlers will be exposed! +- **append** - an object that take any property and value that will be appended to the global window object **(optional)** +- **override** - a method that will override all the initial exposed IPC handler entries and lets you manage what will be exposed manually **(optional)** + +
+ +## Default +```ts +apiKey: 'api' +exposeAll: false // only invoke handlers is exposed +append: {} +override: null +``` + +
+ +## Return + +- **key** - the api key that will be used to access the IPC handlers from the global window object +- **api** - an object that contains all the exposed IPC handlers + +
+ +## Example +```ts +import { exposeApiToGlobalWindow } from 'shared/ipcs' + +declare global { + interface Window { + [key]: typeof api + } +} + +const { key, api } = exposeApiToGlobalWindow({ + override(ipcs) { + return { + removePong() { + ipcs.remove.getPong() + }, + } + }, + + append: { + appName: 'Electron App', + + sayHello() { + return 'Hello World' + }, + } as const, +}) +``` diff --git a/apps/web/docs/createInterprocess/introduction.mdx b/apps/web/docs/createInterprocess/introduction.mdx new file mode 100644 index 0000000..7df4bb7 --- /dev/null +++ b/apps/web/docs/createInterprocess/introduction.mdx @@ -0,0 +1,70 @@ +--- +title: 👋 Introduction +order: 1 +--- + +# Introduction +**createInterprocess** is a function that creates a new interprocess object to manage IPC handlers. + +
+ +## Params + +It takes just a single argument, which is an object containing the following properties: + +
+ +- **main** - the main process IPC handlers **(optional)** +- **renderer** - the renderer process IPC handlers **(optional)** + +
+ +The `main` and `renderer` properties are both objects, and each of them can contain any number of IPC handlers. The keys of these objects will be used as the names of the IPC channels, and the values are the handlers themselves. + +
+ +## Return +It returns an object with the following properties and methods: + +
+ +- **ipcs** - an object containing the IPC handlers +- **ipcMain** - the main process IPC manager +- **ipcRenderer** - the renderer process IPC manager +- **exposeApiToGlobalWindow** - a function that exposes the IPC handlers to the global window object from the preload script + +## Example +```ts +import { createInterprocess } from 'interprocess' + +const ipcs = createInterprocess({ + main: { + async getPing(_, data: 'ping') { + const message = `from renderer: ${data} on main process` + + console.log(message) + + return message + }, + }, + + renderer: { + async getPong(_, data: 'pong') { + const message = `from main: ${data} on renderer process` + + console.log(message) + + return message + }, + }, +}) + +export const { + ipcMain, + ipcRenderer, + exposeApiToGlobalWindow +} = ipcs +``` + + + diff --git a/apps/web/docs/createInterprocess/ipcMain.mdx b/apps/web/docs/createInterprocess/ipcMain.mdx new file mode 100644 index 0000000..7a6bf5a --- /dev/null +++ b/apps/web/docs/createInterprocess/ipcMain.mdx @@ -0,0 +1,71 @@ +--- +title: ipcMain +--- + +# ipcMain +An object that carries `handle`, `invoke` and `remove` methods to manage the asynchronous communication from the main process to renderer processes. + +
+ + +### ipcMain.handle[channel / handler name] + +Register the IPC handler for the given channel. The handler will be called whenever the `ipcRenderer.invoke` method is called with the same channel. + +
+ +It can be simply used as the following example: + +
+ +```ts +ipcMain.handle.getPing() +``` + +
+ +Where `getPing` is the name of the channel (handler) registered in the `createInterprocess` or `createIpcSlice` function. + +
+ +Also, you can pass a callback function to handle the request from the renderer process if you need to do something before sending the response: + +
+```ts + ipcMain.handle.getPing(async (_, { getPing, data }) => { + // call the registered handler if needed + const response = await getPing(_, data) + + await ipcMain.invoke.getPong(mainWindow, 'pong') + + ipcMain.remove.getPing() + + return 'The getPong ipc was removed' + }) +``` + +
+ +### ipcMain.invoke[channel / handler name] + +Send a message to the renderer process and wait for the response if needed: + +
+ +```ts +const response = await ipcMain.invoke.getPong(mainWindow, 'pong') + +console.log(response) +``` + +
+ +### ipcMain.remove[channel / handler name] + +Remove the listener from the main process: + +
+ +```ts +ipcMain.remove.getPing() +``` diff --git a/apps/web/docs/createInterprocess/ipcRenderer.mdx b/apps/web/docs/createInterprocess/ipcRenderer.mdx new file mode 100644 index 0000000..a3fa166 --- /dev/null +++ b/apps/web/docs/createInterprocess/ipcRenderer.mdx @@ -0,0 +1,79 @@ +--- +title: ipcRenderer +--- + +# ipcRenderer +An object that carries `handle`, `invoke` and `remove` methods to manage the asynchronous communication from the renderer process to main processes. + +
+ + +### ipcRenderer.handle[channel / handler name] + +Register the IPC handler for the given channel. The handler will be called whenever the `ipcMain.invoke` method is called with the same channel. + +
+ +It can be simply used as the following example: + +
+ +```ts +const { handle } = window.api + +handle.getPing() +``` + +
+ +Where `getPing` is the name of the channel (handler) registered in the `createInterprocess` or `createIpcSlice` function. + +
+ +Also, you can pass a callback function to handle the request from the main process if you need to do something before sending the response: + +
+```ts +const { handle, remove, invoke } = window.api + +handle.getPing(async (_, { getPing, data }) => { + // call the registered handler if needed + const response = await getPing(_, data) + + await invoke.getPong('pong') + + remove.getPing() + + return 'The getPong ipc was removed' +}) +``` + +
+ +### ipcRenderer.invoke[channel / handler name] + +Send a message to the main process and wait for the response if needed: + +
+ +```ts +const { invoke } = window.api + +const response = await invoke.getPong('pong') + +console.log(response) +``` + +
+ +### ipcRenderer.remove[channel / handler name] + +Remove the listener from the renderer process: + +
+ +```ts +const { remove } = window.api + +remove.getPing() +``` diff --git a/apps/web/docs/createInterprocess/ipcs.mdx b/apps/web/docs/createInterprocess/ipcs.mdx new file mode 100644 index 0000000..c0805bd --- /dev/null +++ b/apps/web/docs/createInterprocess/ipcs.mdx @@ -0,0 +1,11 @@ +--- +title: ipcs +--- + +# ipcs +An object containing the IPC handlers + + + + + diff --git a/apps/web/docs/getting-started/create-a-interprocess.mdx b/apps/web/docs/getting-started/create-a-interprocess.mdx new file mode 100644 index 0000000..183d53c --- /dev/null +++ b/apps/web/docs/getting-started/create-a-interprocess.mdx @@ -0,0 +1,120 @@ +--- +title: Create a interprocess +order: 3 +--- + +# Create a interprocess + +Let's build something simple that can show you some of the interprocess's power! + +
+ +First, create the following folders at `src`: + +
+ +- `shared/ipcs` (this folder structure is optional) + +
+ +Then, create a file named as `index.ts` in the `ipcs` folder with the following content: + +
+ +```ts +import { createInterprocess } from 'interprocess' + +const ipcs = createInterprocess({ + main: { + async getPing(_, data: 'ping') { + const message = `from renderer: ${data} on main process` + + console.log(message) + + return message + }, + }, + + renderer: { + async getPong(_, data: 'pong') { + const message = `from main: ${data} on renderer process` + + console.log(message) + + return message + }, + }, +}) + +export const { + ipcMain, + ipcRenderer, + exposeApiToGlobalWindow +} = ipcs +``` + +
+ +On the main process: + +
+ +```ts +import { BrowserWindow, app } from 'electron' +import { ipcMain } from 'shared/ipcs' + +app.whenReady().then(() => { + const mainWindow = new BrowserWindow({ + webPreferences: { + preload: path.join(__dirname, '../preload/index.js'), + sandbox: false, + }, + }) + + ipcMain.handle.getPing() + + mainWindow.on('ready-to-show', () => { + ipcMain.invoke.getPong(mainWindow, 'pong') + }) +}) +``` + +
+ +In the preload script: + +
+ +```ts +import { exposeApiToGlobalWindow } from 'shared/ipcs' + +declare global { + interface Window { + [key]: typeof api + } +} + +const { key, api } = exposeApiToGlobalWindow({ + exposeAll: true, // expose handlers and invokers, +}) +``` + +
+ +On the renderer process: + +
+ +```ts +const { invoke, handle } = window.api + +invoke.getPing('ping') +handle.getPong() +``` +
+ +This is a simple way to work with interprocess, but there's a lot of more cool features you can take advantage, like `overrides`, `code splitting`, `invoker's response` (for renderer and main process 🎉) and more. Keep reading the docs to get the knowledge to masterize interprocess! + +
+ +Also, you can take a look [this example](https://github.com/daltonmenezes/interprocess/tree/main/apps/desktop) diff --git a/apps/web/docs/getting-started/installation.mdx b/apps/web/docs/getting-started/installation.mdx new file mode 100644 index 0000000..1299091 --- /dev/null +++ b/apps/web/docs/getting-started/installation.mdx @@ -0,0 +1,17 @@ +--- +title: Installation +order: 2 +--- + +# Installation + +### yarn + +```bash +yarn add interprocess +``` + +### npm +```bash +npm i interprocess +``` diff --git a/apps/web/docs/getting-started/overview.mdx b/apps/web/docs/getting-started/overview.mdx new file mode 100644 index 0000000..42a4841 --- /dev/null +++ b/apps/web/docs/getting-started/overview.mdx @@ -0,0 +1,21 @@ +--- +title: Overview +order: 1 +--- + +# Overview + +> The native way to handle Electron IPC is good, but difficult to maintain, either because of the numerous channels you have to remember, or because of the inconsistent API between processes, such as, for example, **invoke** that only exists in the renderer process and the **handle** that only exists in the main process, these are some of the things that interprocess comes to solve! + +
+ +Features: + +
+ +- 🚀 Best-in-class DX with a fully-typed API +- 🧠 Enchanced and consistent API +- 🔥 Type-safe and scalable +- 🪄 Code splitting support +- 🕸️ All edges connected (APIs to handle all processes) +- 💖 `invoke` and `handle` methods in both processes with the same expected behavior diff --git a/apps/web/docs/meta.json b/apps/web/docs/meta.json new file mode 100644 index 0000000..cb48109 --- /dev/null +++ b/apps/web/docs/meta.json @@ -0,0 +1,7 @@ +{ + "order": [ + "getting-started", + "createInterprocess", + "code-splitting" + ] +} diff --git a/apps/web/next-env.d.ts b/apps/web/next-env.d.ts new file mode 100644 index 0000000..4f11a03 --- /dev/null +++ b/apps/web/next-env.d.ts @@ -0,0 +1,5 @@ +/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs new file mode 100644 index 0000000..a466ffa --- /dev/null +++ b/apps/web/next.config.mjs @@ -0,0 +1,31 @@ +const isProd = process.env.NODE_ENV === 'production' + +/** @type {import('next').NextConfig} */ +const nextConfig = { + reactStrictMode: true, + basePath: isProd ? '/interprocess' : '', + assetPrefix: isProd ? '/interprocess/' : '', + + publicRuntimeConfig: { + basePath: isProd ? '/interprocess' : '', + assetPrefix: isProd ? '/interprocess/' : '', + }, + + experimental: { + transpilePackages: ['interprocess'], + }, + + pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'], + + redirects() { + return [ + { + source: '/docs', + destination: '/docs/getting-started/overview', + permanent: false, + }, + ] + }, +} + +export default nextConfig diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..8c9be76 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,48 @@ +{ + "name": "web", + "version": "0.1.0", + "private": true, + "docsFolder": "docs", + "license": "MIT", + "scripts": { + "dev": "next dev", + "build": "next build && next export", + "start": "next start", + "lint": "next lint", + "clean": "rm -rf .turbo && rm -rf node_modules" + }, + "dependencies": { + "@mdx-js/loader": "^2.1.5", + "@mdx-js/react": "^2.1.5", + "@next/mdx": "^12.3.1", + "@radix-ui/react-dialog": "^1.0.0", + "@stitches/react": "^1.2.8", + "framer-motion": "^7.6.4", + "gray-matter": "^4.0.3", + "next": "12.3.2", + "next-mdx-remote": "^4.1.0", + "react": "18.2.0", + "react-dom": "18.2.0", + "react-syntax-highlighter": "^15.5.0", + "rehype-autolink-headings": "^6.1.1", + "rehype-slug": "^5.0.1", + "remark-frontmatter": "^4.0.1", + "remark-gfm": "^3.0.1", + "turbo": "1.5.6", + "use-exit-intent": "latest" + }, + "devDependencies": { + "@babel/core": "^7.0.0", + "@daltonmenezes/eslint-config": "*", + "@daltonmenezes/ts-config": "*", + "@types/node": "^17.0.12", + "@types/react": "18.0.17", + "@types/react-syntax-highlighter": "^15.5.5", + "next-transpile-modules": "9.0.0", + "typescript": "^4.5.3" + }, + "eslintIgnore": [ + ".next", + "out" + ] +} diff --git a/apps/web/public/abstract-background.jpg b/apps/web/public/abstract-background.jpg new file mode 100644 index 0000000..0be50be Binary files /dev/null and b/apps/web/public/abstract-background.jpg differ diff --git a/apps/web/public/background.svg b/apps/web/public/background.svg new file mode 100644 index 0000000..cf4c41c --- /dev/null +++ b/apps/web/public/background.svg @@ -0,0 +1,211 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/public/banner.svg b/apps/web/public/banner.svg new file mode 100644 index 0000000..c7efdf5 --- /dev/null +++ b/apps/web/public/banner.svg @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apps/web/public/bidirectional-arrows.svg b/apps/web/public/bidirectional-arrows.svg new file mode 100644 index 0000000..35e3668 --- /dev/null +++ b/apps/web/public/bidirectional-arrows.svg @@ -0,0 +1,3 @@ + + + diff --git a/apps/web/public/favicon.ico b/apps/web/public/favicon.ico new file mode 100644 index 0000000..6e7a755 Binary files /dev/null and b/apps/web/public/favicon.ico differ diff --git a/apps/web/public/link.svg b/apps/web/public/link.svg new file mode 100644 index 0000000..68f7c8e --- /dev/null +++ b/apps/web/public/link.svg @@ -0,0 +1 @@ + diff --git a/apps/web/public/social.png b/apps/web/public/social.png new file mode 100644 index 0000000..1968a88 Binary files /dev/null and b/apps/web/public/social.png differ diff --git a/apps/web/public/sparkles.png b/apps/web/public/sparkles.png new file mode 100644 index 0000000..a5caff4 Binary files /dev/null and b/apps/web/public/sparkles.png differ diff --git a/apps/web/src/components/Docs/LinkTree/Link/index.tsx b/apps/web/src/components/Docs/LinkTree/Link/index.tsx new file mode 100644 index 0000000..3c430c2 --- /dev/null +++ b/apps/web/src/components/Docs/LinkTree/Link/index.tsx @@ -0,0 +1,11 @@ +import NextLink from 'next/link' + +import { Button, ButtonProps } from './styles' + +export function Link({ href, ...restOfProps }: ButtonProps) { + return ( + + + + ) +} diff --git a/apps/web/src/components/Docs/MDXComponents/CodeBox/styles.ts b/apps/web/src/components/Docs/MDXComponents/CodeBox/styles.ts new file mode 100644 index 0000000..78d3bcc --- /dev/null +++ b/apps/web/src/components/Docs/MDXComponents/CodeBox/styles.ts @@ -0,0 +1,51 @@ +import { BoxStyles } from 'components/Layout' +import { styled } from 'styles' + +export const Button = styled('button', { + opacity: 0, + pointerEvents: 'none', + padding: '0.5rem', + borderRadius: 5, + top: 5, + right: 5, + position: 'absolute', + + svg: { + width: 20, + height: 20, + }, + + '&:disabled': { + color: '', + pointerEvents: 'none', + + 'svg path': { + fill: '', + }, + }, +}) + +export const Box = styled('div', { + position: 'relative', + + code: { + ...BoxStyles, + + display: 'block', + padding: '0.9rem', + borderRadius: 5, + backgroundColor: '$border-primary', + fontSize: '0.8rem', + fontFamily: 'inherit', + lineHeight: '1.5em', + textAlign: 'left', + width: '100%', + maxHeight: 546, + overflow: 'auto', + }, + + [`&:hover > ${Button}, &:focus-within > ${Button}`]: { + opacity: 1, + pointerEvents: 'all', + }, +}) diff --git a/apps/web/src/components/Docs/MDXComponents/index.tsx b/apps/web/src/components/Docs/MDXComponents/index.tsx new file mode 100644 index 0000000..4501eba --- /dev/null +++ b/apps/web/src/components/Docs/MDXComponents/index.tsx @@ -0,0 +1,34 @@ +import { useMDXComponents } from '@mdx-js/react' +import { HTMLAttributes } from 'react' + +import { Description } from 'components' +import { CodeBox } from './CodeBox' + +import { SingleTick, Title } from './styles' + +type MDXComponent = ReturnType + +export function createMDXComponents(): MDXComponent { + return { + h1: Title, + p: Description, + + pre: (props: any) => { + if (!props?.children?.props?.className) { + return )} /> + } + + return
+    },
+
+    code: (props) => {
+      const language = props?.className?.replace('language-', '')
+
+      if (!props?.className) {
+        return 
+      }
+
+      return 
+    },
+  }
+}
diff --git a/apps/web/src/components/Docs/MDXComponents/styles.ts b/apps/web/src/components/Docs/MDXComponents/styles.ts
new file mode 100644
index 0000000..daae36f
--- /dev/null
+++ b/apps/web/src/components/Docs/MDXComponents/styles.ts
@@ -0,0 +1,15 @@
+import { BoxStyles, Title as BaseTitle } from 'components/Layout'
+import { styled } from 'styles'
+
+export const Title = styled(BaseTitle, {
+  textTransform: 'none',
+})
+
+export const SingleTick = styled('span', {
+  ...BoxStyles,
+
+  width: 'fit-content',
+  padding: '0.3rem',
+  backgroundColor: '$border-primary',
+  borderRadius: 4,
+})
diff --git a/apps/web/src/components/Docs/PaginationNavigator/index.tsx b/apps/web/src/components/Docs/PaginationNavigator/index.tsx
new file mode 100644
index 0000000..39b7190
--- /dev/null
+++ b/apps/web/src/components/Docs/PaginationNavigator/index.tsx
@@ -0,0 +1,44 @@
+import Link from 'next/link'
+
+import { NavigatorContainer } from './styles'
+import { Title } from 'templates/Docs/styles'
+
+import type { Pagination } from 'shared/types'
+
+interface PaginationNavigatorProps {
+  pagination: Pagination
+}
+
+export function PaginationNavigator({ pagination }: PaginationNavigatorProps) {
+  return (
+    
+      {pagination.hasPrevious && (
+        
+          
+            Previous
+            
+              {pagination.previous.sections.sanitized.join(' / ')}
+            
+            {pagination.previous.title}
+          
+        
+      )}
+
+      {pagination.hasNext && (
+        
+          
+            Next
+            
+              {pagination.next.sections.sanitized.join(' / ')}
+            
+            {pagination.next.title}
+          
+        
+      )}
+    
+  )
+}
diff --git a/apps/web/src/components/Docs/PaginationNavigator/styles.ts b/apps/web/src/components/Docs/PaginationNavigator/styles.ts
new file mode 100644
index 0000000..1627769
--- /dev/null
+++ b/apps/web/src/components/Docs/PaginationNavigator/styles.ts
@@ -0,0 +1,54 @@
+import { styled } from 'styles'
+
+export const NavigatorContainer = styled('div', {
+  display: 'flex',
+  flexDirection: 'column',
+  gap: '1rem',
+  width: '100%',
+  justifyContent: 'center',
+  alignItems: 'center',
+  marginTop: '2rem',
+  alignSelf: 'center',
+
+  span: {
+    fontSize: '0.9rem',
+    color: '$text-support',
+    maxWidth: 230,
+    overflow: 'hidden',
+    textOverflow: 'ellipsis',
+    whiteSpace: 'nowrap',
+  },
+
+  a: {
+    display: 'flex',
+    flexDirection: 'column',
+    alignItems: 'flex-start',
+    width: '100%',
+    overflowX: 'scroll',
+    overflowY: 'hidden',
+
+    h1: {
+      letterSpacing: 0,
+      fontSize: '2rem',
+      color: '$accent-secondary',
+    },
+
+    '&:hover > h1, &:hover > span': {
+      filter: 'brightness(0.7)',
+    },
+
+    '&:active': {
+      transform: 'scale(0.95)',
+    },
+  },
+
+  '@bp2': {
+    flexDirection: 'row',
+    justifyContent: 'space-between',
+    alignSelf: 'flex-end',
+
+    a: {
+      width: 'auto',
+    },
+  },
+})
diff --git a/apps/web/src/components/Docs/index.ts b/apps/web/src/components/Docs/index.ts
new file mode 100644
index 0000000..82c0a22
--- /dev/null
+++ b/apps/web/src/components/Docs/index.ts
@@ -0,0 +1,3 @@
+export * from './PaginationNavigator'
+export * from './MDXComponents'
+export * from './LinkTree'
diff --git a/apps/web/src/components/ExternalLink/index.tsx b/apps/web/src/components/ExternalLink/index.tsx
new file mode 100644
index 0000000..a44b87a
--- /dev/null
+++ b/apps/web/src/components/ExternalLink/index.tsx
@@ -0,0 +1,7 @@
+import { AnchorHTMLAttributes, PropsWithChildren } from 'react'
+
+export function ExternalLink(
+  props: PropsWithChildren>
+) {
+  return 
+}
diff --git a/apps/web/src/components/FixedHeader/index.tsx b/apps/web/src/components/FixedHeader/index.tsx
new file mode 100644
index 0000000..466fa0a
--- /dev/null
+++ b/apps/web/src/components/FixedHeader/index.tsx
@@ -0,0 +1,9 @@
+import { HeaderContent, HeaderContainer } from './styles'
+
+export function FixedHeader({ children }: { children: React.ReactNode }) {
+  return (
+    
+      {children}
+    
+  )
+}
diff --git a/apps/web/src/components/FixedHeader/styles.ts b/apps/web/src/components/FixedHeader/styles.ts
new file mode 100644
index 0000000..19e71bd
--- /dev/null
+++ b/apps/web/src/components/FixedHeader/styles.ts
@@ -0,0 +1,40 @@
+import { Layout } from 'components/Layout'
+import { styled } from 'styles'
+
+export const HeaderContent = styled(Layout, {
+  flexDirection: 'row',
+  justifyContent: 'flex-end',
+  alignItems: 'center',
+  gap: '1rem',
+  paddingVertical: '1rem',
+
+  a: {
+    transition: 'color 0.2s ease-in-out',
+  },
+
+  'a:nth-of-type(even):hover': {
+    color: '$accent-secondary',
+  },
+
+  svg: {
+    width: '2rem',
+    height: '2rem',
+
+    path: {
+      fill: '$text-support',
+    },
+  },
+})
+
+export const HeaderContainer = styled('div', {
+  display: 'flex',
+  flexDirection: 'row',
+  left: 0,
+  height: 'max-content',
+  width: '100%',
+  alignItems: 'center',
+  paddingVertical: '0.5rem',
+  backdropFilter: 'blur(18px)',
+  position: 'fixed',
+  zIndex: 100,
+})
diff --git a/apps/web/src/components/Footer/index.tsx b/apps/web/src/components/Footer/index.tsx
new file mode 100644
index 0000000..a2a8357
--- /dev/null
+++ b/apps/web/src/components/Footer/index.tsx
@@ -0,0 +1,38 @@
+import React from 'react'
+
+import { ExternalLink, Layout } from 'components'
+import { library } from 'shared/constants'
+
+import {
+  AuthorBox,
+  FooterContent,
+  FooterContainer,
+  LicenseContainer,
+  FooterLinksContainer,
+} from './styles'
+
+export function Footer() {
+  return (
+    
+      
+        
+          
+            
+              
+                Released under the {library.license} License
+              
+
+              
+ Created by + + {library.author.name} + + 💜 +
+
+
+
+
+
+ ) +} diff --git a/apps/web/src/components/Footer/styles.ts b/apps/web/src/components/Footer/styles.ts new file mode 100644 index 0000000..d9cac2d --- /dev/null +++ b/apps/web/src/components/Footer/styles.ts @@ -0,0 +1,74 @@ +import { Box } from 'components/Layout/Box' +import { styled } from 'styles' + +export const FooterContainer = styled('footer', { + display: 'flex', + alignItems: 'center', + minHeight: '7rem', + paddingBottom: '1.5rem', +}) + +export const FooterContent = styled('div', { + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + flexDirection: 'column', + width: '100%', + + img: { + transition: 'opacity 0.2s linear', + + '&:hover': { + opacity: '0.5', + }, + }, + + '@bp4': { + flexDirection: 'row', + }, +}) + +export const FooterLinksContainer = styled('div', { + display: 'flex', + alignItems: 'center', + gap: `2rem`, + width: '100%', + flexDirection: 'column', + paddingTop: '2.5rem', + + a: { + fontWeight: 700, + }, + + '@bp4': { + flexDirection: 'row', + paddingTop: 0, + }, +}) + +export const AuthorBox = styled(Box, { + flexDirection: 'column', + alignItems: 'center', + width: '100%', + justifyContent: 'center', + gap: '0.5rem', + padding: '1rem', + fontSize: '1rem', + lineHeight: '1.625rem', + color: '$accent-secondary', + transition: 'border 0.2s ease', + + div: { + display: 'flex', + gap: '0.5rem', + }, +}) + +export const LicenseContainer = styled('div', { + fontSize: '0.875rem', + color: '$text-support', + + strong: { + color: '$accent-primary', + }, +}) diff --git a/apps/web/src/components/Head/index.tsx b/apps/web/src/components/Head/index.tsx new file mode 100644 index 0000000..260ce3a --- /dev/null +++ b/apps/web/src/components/Head/index.tsx @@ -0,0 +1,39 @@ +import NextHead from 'next/head' + +import { meta } from 'shared/constants' + +interface HeadProps { + children?: React.ReactNode + meta: typeof meta +} + +export function Head({ meta, children }: HeadProps) { + return ( + + {meta.title} + + + + + + + + + + + + + + + + + + + + + + + {children} + + ) +} diff --git a/apps/web/src/components/Header/index.tsx b/apps/web/src/components/Header/index.tsx new file mode 100644 index 0000000..7ef301b --- /dev/null +++ b/apps/web/src/components/Header/index.tsx @@ -0,0 +1,56 @@ +import Link from 'next/link' + +import { library } from 'shared/constants' + +import { + Title, + GitHubIcon, + FixedHeader, + Description, + ExternalLink, + LayoutSpacing, + LibraryVersion, + InstallationBox, +} from 'components' + +import { Layout } from './styles' +import { getPublicPath } from 'shared/utils' + +export function Header() { + return ( + + + + + + +
Docs + + + + Install + + + + + + + + + + + interprocess + + + {' '} + {library.description} + + + + + + + + + ) +} diff --git a/apps/web/src/components/Header/styles.ts b/apps/web/src/components/Header/styles.ts new file mode 100644 index 0000000..d78f102 --- /dev/null +++ b/apps/web/src/components/Header/styles.ts @@ -0,0 +1,6 @@ +import { BaseLayout } from 'components/Layout' +import { styled } from 'styles' + +export const Layout = styled(BaseLayout, { + alignItems: 'center', +}) diff --git a/apps/web/src/components/Icons/Checkmark.tsx b/apps/web/src/components/Icons/Checkmark.tsx new file mode 100644 index 0000000..6a67a0f --- /dev/null +++ b/apps/web/src/components/Icons/Checkmark.tsx @@ -0,0 +1,20 @@ +import { theme } from 'styles' + +export function CheckmarkIcon() { + return ( + + + + ) +} diff --git a/apps/web/src/components/Icons/Clipboard.tsx b/apps/web/src/components/Icons/Clipboard.tsx new file mode 100644 index 0000000..3ca1323 --- /dev/null +++ b/apps/web/src/components/Icons/Clipboard.tsx @@ -0,0 +1,23 @@ +export function ClipboardIcon() { + return ( + + + + + + + + + + + ) +} diff --git a/apps/web/src/components/Icons/GitHub.tsx b/apps/web/src/components/Icons/GitHub.tsx new file mode 100644 index 0000000..e8ec7c7 --- /dev/null +++ b/apps/web/src/components/Icons/GitHub.tsx @@ -0,0 +1,16 @@ +export function GitHubIcon() { + return ( + + + + ) +} diff --git a/apps/web/src/components/Icons/Menu.tsx b/apps/web/src/components/Icons/Menu.tsx new file mode 100644 index 0000000..5bf700b --- /dev/null +++ b/apps/web/src/components/Icons/Menu.tsx @@ -0,0 +1,26 @@ +export function Menu() { + return ( + + + + + + + + + + + ) +} diff --git a/apps/web/src/components/Icons/Spinner/index.tsx b/apps/web/src/components/Icons/Spinner/index.tsx new file mode 100644 index 0000000..82565ec --- /dev/null +++ b/apps/web/src/components/Icons/Spinner/index.tsx @@ -0,0 +1,30 @@ +import { SVG } from './styles' +import { theme } from 'styles' + +export function Spinner() { + return ( + + + + + + + + + + + ) +} diff --git a/apps/web/src/components/Icons/Spinner/styles.ts b/apps/web/src/components/Icons/Spinner/styles.ts new file mode 100644 index 0000000..0d863ed --- /dev/null +++ b/apps/web/src/components/Icons/Spinner/styles.ts @@ -0,0 +1,5 @@ +import { styled, animations } from 'styles' + +export const SVG = styled('svg', { + animation: `${animations.spin} 1s linear infinite`, +}) diff --git a/apps/web/src/components/Icons/index.tsx b/apps/web/src/components/Icons/index.tsx new file mode 100644 index 0000000..96e32dd --- /dev/null +++ b/apps/web/src/components/Icons/index.tsx @@ -0,0 +1,5 @@ +export * from './Checkmark' +export * from './Clipboard' +export * from './Spinner' +export * from './GitHub' +export * from './Menu' diff --git a/apps/web/src/components/InstallationBox/index.tsx b/apps/web/src/components/InstallationBox/index.tsx new file mode 100644 index 0000000..6d4ea65 --- /dev/null +++ b/apps/web/src/components/InstallationBox/index.tsx @@ -0,0 +1,93 @@ +import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter' +import { useState } from 'react' + +import { queueTimeouts } from 'shared/utils' +import { commands } from 'shared/constants' + +import { Separator, CheckmarkIcon, ClipboardIcon, Spinner } from 'components' + +import { Button, PackageButton, PackageManagerList, ShellBox } from './styles' +import { codeTheme } from 'styles' + +const clipboardStateIcons = { + copying: () => , + copied: () => , + default: () => , +} as const + +type ClipboardStateKeys = keyof typeof clipboardStateIcons +type PackageManagerOptions = keyof typeof commands + +export function InstallationBox() { + const [clipboardState, setClipboardState] = + useState('default') + + const [packageManager, setPackageManager] = + useState('yarn') + + const installCommand = commands[packageManager] + + function copyToClipboard() { + navigator.clipboard + .writeText(installCommand) + .then(() => setClipboardState('copying')) + .then(() => + queueTimeouts( + { + delay: 1000, + callback: () => setClipboardState('copied'), + }, + { + delay: 1000, + callback: () => setClipboardState('default'), + } + ) + ) + } + + function handlePackageManagerSelection( + packageManager: PackageManagerOptions + ) { + setPackageManager(() => packageManager) + } + + return ( + <> + +
  • + handlePackageManagerSelection('npm')} + active={packageManager === 'npm'} + > + npm + +
  • + + + +
  • + handlePackageManagerSelection('yarn')} + active={packageManager === 'yarn'} + > + yarn + +
  • +
    + + + + {installCommand} + + + + + + ) +} diff --git a/apps/web/src/components/InstallationBox/styles.ts b/apps/web/src/components/InstallationBox/styles.ts new file mode 100644 index 0000000..40b83f6 --- /dev/null +++ b/apps/web/src/components/InstallationBox/styles.ts @@ -0,0 +1,69 @@ +import { Box } from 'components/Layout/Box' +import { styled } from 'styles' + +export const ShellBox = styled(Box, { + justifyContent: 'space-between', + alignItems: 'center', + width: '100%', + padding: '1rem', + fontSize: '1rem', + lineHeight: '1.625rem', + color: '$accent-primary', + transition: 'border 0.2s ease', + + '&:hover, &:focus-within': { + border: '1px solid $accent-primary', + }, + + 'pre, code': { + width: '100%', + textAlign: 'center !important', + background: 'transparent !important', + margin: '0 !important', + padding: '0 !important', + overflow: 'hidden !important', + }, + + '.token.token': { + color: '$accent-primary !important', + }, + + '@bp4': { + width: '340px', + }, +}) + +export const PackageManagerList = styled('ul', { + display: 'flex', + alignItems: 'baseline', + gap: '0.5rem', +}) + +export const PackageButton = styled('button', { + background: 'transparent', + + '&:hover': { + color: '$accent-primary', + background: 'transparent', + }, + + variants: { + active: { + true: { + color: '$accent-primary', + pointerEvents: 'none', + }, + }, + }, +}) + +export const Button = styled('button', { + '&:disabled': { + color: '', + pointerEvents: 'none', + + 'svg path': { + fill: '', + }, + }, +}) diff --git a/apps/web/src/components/Layout/Box/index.ts b/apps/web/src/components/Layout/Box/index.ts new file mode 100644 index 0000000..1859376 --- /dev/null +++ b/apps/web/src/components/Layout/Box/index.ts @@ -0,0 +1,11 @@ +import { styled, Mixin } from 'styles' + +export const BoxStyles: Mixin = { + display: 'flex', + background: '$shape-primary', + border: '1px solid $border-primary', + boxShadow: '0 2px 2px 1px $colors$shadow-primary', + borderRadius: 15, +} + +export const Box = styled('div', BoxStyles) diff --git a/apps/web/src/components/Layout/Button/index.ts b/apps/web/src/components/Layout/Button/index.ts new file mode 100644 index 0000000..7175412 --- /dev/null +++ b/apps/web/src/components/Layout/Button/index.ts @@ -0,0 +1,70 @@ +import { BoxStyles } from '../Box' +import { styled } from 'styles' + +export const Button = styled('button', { + ...BoxStyles, + + display: 'flex', + flexDirection: 'row', + justifyContent: 'center', + alignItems: 'center', + gap: '0.5rem', + padding: '0.6em 1.2em', + borderRadius: 4, + + transition: 'all 0.2s ease', + + variants: { + variant: { + primary: { + '&:hover': { + background: '$accent-primary', + color: '$text-base', + }, + + '&:active': { + filter: 'brightness(0.5)', + }, + }, + + secondary: { + '&:hover': { + backgroundColor: '$accent-secondary', + color: 'black', + }, + }, + + primaryFilled: { + color: '$shape-primary', + background: '$accent-primary', + + 'svg path': { + fill: '$shape-primary', + }, + + '&:hover': { + color: '$accent-primary', + backgroundColor: '$shape-primary', + }, + }, + + secondaryFilled: { + color: '$shape-primary', + background: '$accent-secondary', + + 'svg path': { + fill: '$shape-primary', + }, + + '&:hover': { + color: '$accent-primary', + backgroundColor: '$shape-primary', + }, + }, + }, + }, + + defaultVariants: { + variant: 'primary', + }, +}) diff --git a/apps/web/src/components/Layout/Description/index.ts b/apps/web/src/components/Layout/Description/index.ts new file mode 100644 index 0000000..269847e --- /dev/null +++ b/apps/web/src/components/Layout/Description/index.ts @@ -0,0 +1,54 @@ +import { styled } from 'styles' + +import { BoxStyles } from '../Box' + +export const Description = styled('p', { + gap: '0.5rem', + color: '$text-support', + textAlign: 'left', + + img: { + display: 'inline-flex', + width: '0.9rem', + }, + + '> code': { + ...BoxStyles, + + display: 'inline-flex', + width: 'fit-content', + padding: '0.3rem', + borderRadius: 4, + backgroundColor: '$border-primary', + }, + + '@bp4': { + alignItems: 'center', + textAlign: 'left', + gap: '0.1rem', + + img: { + display: 'block', + float: 'left', + marginRight: '0.6rem', + width: '1.2rem', + }, + }, + + variants: { + size: { + small: { + fontSize: '0.8rem', + }, + + medium: { + fontSize: '1rem', + }, + + large: { + color: '$accent-primary', + fontSize: '2rem', + }, + }, + }, +}) diff --git a/apps/web/src/components/Layout/OuterClickArea/index.ts b/apps/web/src/components/Layout/OuterClickArea/index.ts new file mode 100644 index 0000000..05ba501 --- /dev/null +++ b/apps/web/src/components/Layout/OuterClickArea/index.ts @@ -0,0 +1,12 @@ +import { styled, animations } from 'styles' + +export const OuterClickArea = styled('div', { + position: 'fixed', + top: 0, + left: 0, + width: '100%', + height: '100%', + zIndex: 998, + background: '$shadow-primary', + animation: `${animations.fadeIn} 0.2s ease`, +}) diff --git a/apps/web/src/components/Layout/RootContainer/index.ts b/apps/web/src/components/Layout/RootContainer/index.ts new file mode 100644 index 0000000..c1644ec --- /dev/null +++ b/apps/web/src/components/Layout/RootContainer/index.ts @@ -0,0 +1,12 @@ +import { styled } from 'styles' + +export const RootContainer = styled('main', { + display: 'flex', + flexDirection: 'column', + justifyContent: 'center', + alignItems: 'stretch', + minWidth: '100vw', + minHeight: '100vh', + gap: '1.5rem', + backgroundSize: 'cover', +}) diff --git a/apps/web/src/components/Layout/Separator/index.ts b/apps/web/src/components/Layout/Separator/index.ts new file mode 100644 index 0000000..5447dbd --- /dev/null +++ b/apps/web/src/components/Layout/Separator/index.ts @@ -0,0 +1,46 @@ +import { styled } from 'styles' + +export const Separator = styled('div', { + background: '$shape-quaternary', + + compoundVariants: [ + { + horizontal: true, + css: { + borderLeft: 0, + borderTop: '1px solid rgba(36, 36, 36, 0.547)', + }, + }, + ], + + variants: { + opacity: { + default: { + borderLeft: '1px solid $shape-tertiary', + }, + + low: { + opacity: 0.4, + }, + }, + + vertical: { + true: { + width: 2, + height: 8, + }, + }, + + horizontal: { + true: { + width: '100%', + height: 1, + }, + }, + }, + + defaultVariants: { + vertical: true, + opacity: 'default', + }, +}) diff --git a/apps/web/src/components/Layout/Title/index.ts b/apps/web/src/components/Layout/Title/index.ts new file mode 100644 index 0000000..6ee6fba --- /dev/null +++ b/apps/web/src/components/Layout/Title/index.ts @@ -0,0 +1,22 @@ +import { styled, animations } from 'styles' + +export const Title = styled('h1', { + fontSize: '2.5rem', + letterSpacing: 2, + fontWeight: 700, + color: '$text-title', + animation: `${animations.reveal} 0.6s ease-in-out`, + backgroundImage: '$text-gradient', + backgroundClip: 'text', + '-webkit-background-clip': 'text', + textFillColor: 'transparent', + '-webkit-text-fill-color': 'transparent', + textTransform: 'capitalize', + + userSelect: 'none', + + '@bp4': { + fontSize: '4rem', + letterSpacing: 5, + }, +}) diff --git a/apps/web/src/components/Layout/index.ts b/apps/web/src/components/Layout/index.ts new file mode 100644 index 0000000..91a1431 --- /dev/null +++ b/apps/web/src/components/Layout/index.ts @@ -0,0 +1,59 @@ +import { styled } from 'styles' + +export * from './OuterClickArea' +export * from './RootContainer' +export * from './Description' +export * from './Separator' +export * from './Button' +export * from './Title' +export * from './Box' + +export const BaseLayout = styled('div', { + display: 'flex', + flexFlow: 'column wrap', + width: '100%', + gap: '1rem', +}) + +export const Layout = styled(BaseLayout, { + alignItems: 'center', + maxWidth: `1250px`, + width: `100%`, + padding: `0 20px`, + margin: '0 auto', + position: 'relative', +}) + +export const LayoutSpacing = styled('div', { + variants: { + size: { + extraSmall: { + height: '0.5rem', + }, + + small: { + paddingBottom: '1rem', + }, + + medium: { + paddingBottom: '2rem', + + '@bp4': { + paddingBottom: '4rem', + }, + }, + + large: { + paddingBottom: '4rem', + + '@bp4': { + paddingBottom: '8rem', + }, + }, + }, + }, + + defaultVariants: { + size: 'large', + }, +}) diff --git a/apps/web/src/components/LibraryVersion/index.tsx b/apps/web/src/components/LibraryVersion/index.tsx new file mode 100644 index 0000000..e63e351 --- /dev/null +++ b/apps/web/src/components/LibraryVersion/index.tsx @@ -0,0 +1,7 @@ +import { library } from 'shared/constants' + +import { LibraryVersionContainer } from './styles' + +export function LibraryVersion() { + return v{library.version} +} diff --git a/apps/web/src/components/LibraryVersion/styles.ts b/apps/web/src/components/LibraryVersion/styles.ts new file mode 100644 index 0000000..a34d3a4 --- /dev/null +++ b/apps/web/src/components/LibraryVersion/styles.ts @@ -0,0 +1,12 @@ +import { styled } from 'styles' + +export const LibraryVersionContainer = styled('div', { + display: 'flex', + fontSize: '0.85rem', + color: '$text-support', + maxWidth: 'fit-content', + padding: '0.5rem', + borderRadius: '0.5rem', + backgroundColor: '$border-primary', + border: '1px solid $border-primary', +}) diff --git a/apps/web/src/components/Modals/ExitIntent/index.tsx b/apps/web/src/components/Modals/ExitIntent/index.tsx new file mode 100644 index 0000000..16bdf68 --- /dev/null +++ b/apps/web/src/components/Modals/ExitIntent/index.tsx @@ -0,0 +1,50 @@ +import * as RadixDialog from '@radix-ui/react-dialog' + +import { ExternalLink, Button } from 'components' +import { getPublicPath } from 'shared/utils' +import { library } from 'shared/constants' + +import { + Tag, + Image, + Title, + Overlay, + Content, + Container, + CloseButton, + ContentGroup, +} from './styles' + +interface ModalProps { + onDismiss: () => void +} + +export function ExitIntentModal({ onDismiss }: ModalProps) { + return ( + + + + event.preventDefault()}> + X + + + + + + Thanks for the visit! + + + If you liked, + <br /> <strong>drop a star</strong> on <strong>GitHub</strong>! + <img src={getPublicPath('/sparkles.png')} alt="" /> + + + + + + + + + + ) +} diff --git a/apps/web/src/components/Modals/ExitIntent/styles.ts b/apps/web/src/components/Modals/ExitIntent/styles.ts new file mode 100644 index 0000000..f4fbe29 --- /dev/null +++ b/apps/web/src/components/Modals/ExitIntent/styles.ts @@ -0,0 +1,208 @@ +import * as Dialog from '@radix-ui/react-dialog' + +import { getPublicPath } from 'shared/utils' + +import { styled, animations } from 'styles' + +export const Overlay = styled(Dialog.Overlay, { + position: 'fixed', + minWidth: '100vw', + minHeight: '100vh', + inset: 0, + background: 'rgba(0, 0, 0, 0.75)', + zIndex: 100, +}) + +export const Container = styled(Dialog.Content, { + display: 'flex', + flexDirection: 'column', + alignItems: 'center', + textAlign: 'center', + width: '100%', + height: '100%', + top: '50%', + left: '50%', + position: 'fixed', + backdropFilter: 'blur(10px)', + transform: 'translate(-50%, -50%)', + overflowX: 'hidden', + zIndex: 9999, + + '@bp4': { + flexDirection: 'row', + justifyContent: 'space-between', + width: '90%', + height: '35.1875rem', + maxWidth: '59.125rem', + borderRadius: 10, + gap: 45.5, + border: '1px solid $colors$shape-tertiary', + boxShadow: '8px 2px 60px -22px $colors$shape-quinary', + overflow: 'hidden', + }, +}) + +export const Content = styled('div', { + display: 'flex', + flex: 1, + flexDirection: 'column', + width: '100%', + height: '100%', + + '@bp4': { + display: 'flex', + flexDirection: 'row', + width: 'auto', + }, +}) + +export const ContentGroup = styled('div', { + display: 'flex', + flexDirection: 'column', + alignItems: 'center', + width: '100%', + + textAlign: 'center', + + paddingHorizontal: '1.5rem', + paddingTop: 'calc(4rem + 1.911rem)', + paddingBottom: '3.10375rem', + + gap: 16, + + p: { + fontSize: '0.875rem', + fontWeight: 400, + textAlign: 'center', + lineHeight: '1.4rem', + + color: '$text-support', + }, + + a: { + marginTop: 16, + }, + + button: { + fontSize: '1rem', + }, + + 'button, a': { + width: '100%', + }, + + '@bp4': { + flex: 1, + width: '100%', + alignItems: 'flex-start', + textAlign: 'left', + marginLeft: '1.46875rem', + + p: { + textAlign: 'left', + }, + }, +}) + +export const Title = styled(Dialog.Title, { + display: 'inline-block', + maxWidth: '20.1875rem', + + fontSize: '1.5rem', + fontWeight: 700, + lineHeight: '1.875rem', + + color: '$text-title', + + span: { + textTransform: 'capitalize', + }, + + strong: { + '&:nth-of-type(odd)': { + color: '$accent-secondary', + }, + + '&:nth-of-type(even)': { + color: '$accent-primary', + }, + }, + + img: { + width: '1.5625rem', + marginLeft: '0.5rem', + }, + + '@bp4': { + maxWidth: '33.3125rem', + + fontSize: '2.5rem', + fontWeight: 700, + textAlign: 'left', + lineHeight: '3.125rem', + + img: { + width: '2.5rem', + marginLeft: '0.5rem', + }, + }, +}) + +export const CloseButton = styled(Dialog.Close, { + fontSize: '1.2rem', + lineHeight: 0, + color: '$text-title', + background: 'transparent', + transform: 'scaleX(1.4)', + top: '1.5rem', + right: '1.5rem', + border: 0, + cursor: 'pointer', + position: 'absolute', + transition: 'color 0.2s ease-in-out', + + '&:hover, &:focus-within': { + color: '$accent-primary', + }, +}) + +export const Tag = styled('h2', { + fontSize: '0.875rem', + fontWeight: 700, + lineHeight: '1.4rem', + textTransform: 'uppercase', + + color: '$accent-primary', + + padding: '4px 8px', + + borderRadius: 3, + + variants: { + type: { + outlined: { + border: '1px solid $accent-primary', + }, + }, + }, + + defaultVariants: { + type: 'outlined', + }, +}) + +export const Image = styled('div', { + display: 'flex', + width: '100%', + height: '3.125rem', + zIndex: -1, + + backgroundImage: `url("${getPublicPath('/abstract-background.jpg')}")`, + backgroundPosition: 'center center', + animation: `${animations.backgroundCover} 40s linear infinite alternate`, + + '@bp4': { + maxWidth: '20rem', + minHeight: '100%', + }, +}) diff --git a/apps/web/src/components/Modals/index.ts b/apps/web/src/components/Modals/index.ts new file mode 100644 index 0000000..c071529 --- /dev/null +++ b/apps/web/src/components/Modals/index.ts @@ -0,0 +1 @@ +export * from './ExitIntent' diff --git a/apps/web/src/components/index.ts b/apps/web/src/components/index.ts new file mode 100644 index 0000000..6a42c0e --- /dev/null +++ b/apps/web/src/components/index.ts @@ -0,0 +1,11 @@ +export * from './InstallationBox' +export * from './LibraryVersion' +export * from './ExternalLink' +export * from './FixedHeader' +export * from './Modals' +export * from './Layout' +export * from './Header' +export * from './Footer' +export * from './Icons' +export * from './Docs' +export * from './Head' diff --git a/apps/web/src/hooks/index.ts b/apps/web/src/hooks/index.ts new file mode 100644 index 0000000..0c14653 --- /dev/null +++ b/apps/web/src/hooks/index.ts @@ -0,0 +1,2 @@ +export * from './useDisclosure' +export * from './useMatchMedia' diff --git a/apps/web/src/hooks/useDisclosure.ts b/apps/web/src/hooks/useDisclosure.ts new file mode 100644 index 0000000..16b8ee5 --- /dev/null +++ b/apps/web/src/hooks/useDisclosure.ts @@ -0,0 +1,18 @@ +import { useCallback, useState } from 'react' + +export function useDisclosure(isOpenDefault = false) { + const [isOpen, setIsOpen] = useState(isOpenDefault) + + const open = useCallback(() => setIsOpen(true), []) + const close = useCallback(() => setIsOpen(false), []) + + const toggle = useCallback((toSet?: boolean) => { + if (typeof toSet === 'undefined') { + setIsOpen((state) => !state) + } else { + setIsOpen(toSet) + } + }, []) + + return { isOpen, open, close, toggle } +} diff --git a/apps/web/src/hooks/useMatchMedia.ts b/apps/web/src/hooks/useMatchMedia.ts new file mode 100644 index 0000000..54681c8 --- /dev/null +++ b/apps/web/src/hooks/useMatchMedia.ts @@ -0,0 +1,27 @@ +import { useEffect, useState } from 'react' + +export function useMatchMedia(condition: string): boolean { + const [matches, setMatches] = useState(false) + + useEffect(() => { + function listener({ matches }: MediaQueryListEvent) { + setMatches(matches) + } + + const matchMedia = window.matchMedia(`(${condition})`) + + setMatches(matchMedia.matches) + + try { + matchMedia.addEventListener('change', listener) + + return () => matchMedia.removeEventListener('change', listener) + } catch (_) { + matchMedia.addListener(listener) + + return () => matchMedia.removeListener(listener) + } + }, []) + + return matches +} diff --git a/apps/web/src/modules/index.ts b/apps/web/src/modules/index.ts new file mode 100644 index 0000000..3718365 --- /dev/null +++ b/apps/web/src/modules/index.ts @@ -0,0 +1 @@ +export * from './server' diff --git a/apps/web/src/modules/server/docs/getAllDocs.ts b/apps/web/src/modules/server/docs/getAllDocs.ts new file mode 100644 index 0000000..fa52605 --- /dev/null +++ b/apps/web/src/modules/server/docs/getAllDocs.ts @@ -0,0 +1,25 @@ +import { readFile } from 'node:fs/promises' +import matter from 'gray-matter' + +import { getParsedDocPaths } from './getParsedDocPaths' + +export async function getAllDocs() { + const paths = await getParsedDocPaths() + + const docs = await Promise.all( + paths.map(async (path) => { + const fileContent = await readFile(path.fullPath, 'utf8') + const { data } = matter(fileContent) + + return { + ...data, + url: path.url, + slug: path.slug, + order: data.order || 0, + title: data.title || path.slug, + } + }) + ) + + return docs +} diff --git a/apps/web/src/modules/server/docs/getAllMDXFilePaths.ts b/apps/web/src/modules/server/docs/getAllMDXFilePaths.ts new file mode 100644 index 0000000..416b9ac --- /dev/null +++ b/apps/web/src/modules/server/docs/getAllMDXFilePaths.ts @@ -0,0 +1,28 @@ +import { readdir, stat } from 'node:fs/promises' +import { resolve } from 'node:path' + +export async function getAllMDXFilePaths(directory: string) { + const filePaths: string[] = [] + + async function getMDXFilePaths(directory: string) { + for (const file of await readdir(directory)) { + const path = resolve(directory, file) + const isMDXFile = /\.mdx?$/.test(file) + const isDirectory = (await stat(path))?.isDirectory() + + if (isDirectory) { + await getMDXFilePaths(path) + } + + if (isMDXFile) { + filePaths.push(path) + } + } + } + + return (async () => { + await getMDXFilePaths(directory) + + return filePaths + })() +} diff --git a/apps/web/src/modules/server/docs/getDoc.ts b/apps/web/src/modules/server/docs/getDoc.ts new file mode 100644 index 0000000..7fbf1ec --- /dev/null +++ b/apps/web/src/modules/server/docs/getDoc.ts @@ -0,0 +1,43 @@ +import { serialize } from 'next-mdx-remote/serialize' +import { readFile } from 'node:fs/promises' +import matter from 'gray-matter' + +import rehypeAutolinkHeadings from 'rehype-autolink-headings' +import rehypeSlug from 'rehype-slug' +import remarkGFM from 'remark-gfm' + +import { getParsedDocPaths } from './getParsedDocPaths' + +import type { Doc } from 'shared/types' + +const fallbackDoc = {} as Doc + +export async function getDoc(path: string): Promise { + if (!path) return fallbackDoc + + const paths = await getParsedDocPaths() + const docPath = paths.find((docPath) => docPath.url === path) + + if (!docPath) return fallbackDoc + + const { data, content } = matter(await readFile(docPath.fullPath, 'utf8')) + + const MDXSource = await serialize(content, { + mdxOptions: { + remarkPlugins: [remarkGFM], + + rehypePlugins: [ + rehypeSlug, + [rehypeAutolinkHeadings, { behavior: 'wrap' }], + ], + }, + }) + + return { + ...data, + url: docPath.url, + slug: docPath.slug, + source: MDXSource, + title: data.title || docPath.slug.replace(/-/g, ' '), + } +} diff --git a/apps/web/src/modules/server/docs/getDocLinks.ts b/apps/web/src/modules/server/docs/getDocLinks.ts new file mode 100644 index 0000000..93e8284 --- /dev/null +++ b/apps/web/src/modules/server/docs/getDocLinks.ts @@ -0,0 +1,55 @@ +import { getMetaFile } from './getMetaFile' +import { getAllDocs } from './getAllDocs' + +import type { LinkKeys, Links } from 'shared/types' + +export async function getDocLinks() { + const paths = await getAllDocs() + const meta = await getMetaFile() + + let links = paths.reduce((acc, path) => { + const [rootSection] = path.url.split('/') as LinkKeys[] + const { title, slug, url, order } = path + const links = acc[rootSection] || [] + + return { + ...acc, + + [rootSection]: [ + ...links, + + { + url, + order, + title: title || slug.replace(/-/g, ' '), + }, + ], + } + }, {} as Links) + + if (meta?.order) { + const metaOrder = meta.order as LinkKeys[] + const orderedKeys = metaOrder.filter((key) => links[key]) + + const keys = [ + ...new Set([...orderedKeys, ...Object.keys(links)]), + ] as LinkKeys[] + + links = keys.reduce((acc, rootSection) => { + const link = links[rootSection] || [] + + return { + ...acc, + + [rootSection]: link?.sort((a, b) => { + const orderA = a.order === 0 ? 999 : a.order + const orderB = b.order === 0 ? 999 : b.order + + return orderA - orderB + }), + } + }, {} as Links) + } + + return links +} diff --git a/apps/web/src/modules/server/docs/getDocPaginationNavigator.ts b/apps/web/src/modules/server/docs/getDocPaginationNavigator.ts new file mode 100644 index 0000000..c422f78 --- /dev/null +++ b/apps/web/src/modules/server/docs/getDocPaginationNavigator.ts @@ -0,0 +1,48 @@ +import { getDocLinks } from './getDocLinks' + +import type { Pagination } from 'shared/types' + +export async function getDocPaginationNavigator( + currentDoc: string +): Promise { + const docLinks = await getDocLinks() + const links = Object.values(docLinks).flat() + + const index = links.findIndex((path) => path.url === currentDoc) + + const previousDoc = links[index - 1] || {} + const nextDoc = links[index + 1] || {} + + const hasPreviousDoc = !!previousDoc.url + const hasNextDoc = !!nextDoc.url + + const previousSectionPathNames = previousDoc?.url?.split('/').slice(0, -1) + const nextSectionPathNames = nextDoc?.url?.split('/').slice(0, -1) + + function unslugifySectionPathNames(sectionPathNames: string[]) { + return sectionPathNames?.map((pathName) => pathName.replace('-', ' ')) || [] + } + + return { + next: { + ...nextDoc, + + sections: { + raw: nextSectionPathNames || [], + sanitized: unslugifySectionPathNames(nextSectionPathNames), + }, + }, + + previous: { + ...previousDoc, + + sections: { + raw: previousSectionPathNames || [], + sanitized: unslugifySectionPathNames(previousSectionPathNames), + }, + }, + + hasNext: hasNextDoc, + hasPrevious: hasPreviousDoc, + } +} diff --git a/apps/web/src/modules/server/docs/getDocsFolder.ts b/apps/web/src/modules/server/docs/getDocsFolder.ts new file mode 100644 index 0000000..c85ecd9 --- /dev/null +++ b/apps/web/src/modules/server/docs/getDocsFolder.ts @@ -0,0 +1,7 @@ +import { resolve } from 'node:path' + +import packageJSON from '../../../../package.json' + +export function getDocsFolder() { + return resolve(packageJSON?.docsFolder || 'docs') +} diff --git a/apps/web/src/modules/server/docs/getMetaFile.ts b/apps/web/src/modules/server/docs/getMetaFile.ts new file mode 100644 index 0000000..146519d --- /dev/null +++ b/apps/web/src/modules/server/docs/getMetaFile.ts @@ -0,0 +1,11 @@ +import { readFile } from 'node:fs/promises' +import { resolve } from 'node:path' + +import { getDocsFolder } from './getDocsFolder' + +export async function getMetaFile() { + const metaFilePath = resolve(getDocsFolder(), 'meta.json') + const metaFileContent = await readFile(metaFilePath, 'utf8').catch(() => '{}') + + return JSON.parse(metaFileContent) +} diff --git a/apps/web/src/modules/server/docs/getParsedDocPaths.ts b/apps/web/src/modules/server/docs/getParsedDocPaths.ts new file mode 100644 index 0000000..bbf272f --- /dev/null +++ b/apps/web/src/modules/server/docs/getParsedDocPaths.ts @@ -0,0 +1,18 @@ +import { parse } from 'node:path' + +import { getAllMDXFilePaths } from './getAllMDXFilePaths' +import { getDocsFolder } from './getDocsFolder' + +export async function getParsedDocPaths() { + const docsFolder = getDocsFolder() + const filePaths = await getAllMDXFilePaths(docsFolder) + + const parsedDocPaths = filePaths.map((file) => ({ + path: file.replace(docsFolder, ''), + fullPath: file, + url: file.replace(`${docsFolder}/`, '').replace(/.mdx$/, ''), + slug: parse(file).name, + })) + + return parsedDocPaths +} diff --git a/apps/web/src/modules/server/docs/index.ts b/apps/web/src/modules/server/docs/index.ts new file mode 100644 index 0000000..524cb85 --- /dev/null +++ b/apps/web/src/modules/server/docs/index.ts @@ -0,0 +1,7 @@ +export * from './getDocPaginationNavigator' +export * from './getAllMDXFilePaths' +export * from './getDocLinks' +export * from './getParsedDocPaths' +export * from './getMetaFile' +export * from './getAllDocs' +export * from './getDoc' diff --git a/apps/web/src/modules/server/index.ts b/apps/web/src/modules/server/index.ts new file mode 100644 index 0000000..69ed1cf --- /dev/null +++ b/apps/web/src/modules/server/index.ts @@ -0,0 +1 @@ +export * from './docs' diff --git a/apps/web/src/pages/_app.tsx b/apps/web/src/pages/_app.tsx new file mode 100644 index 0000000..b58716c --- /dev/null +++ b/apps/web/src/pages/_app.tsx @@ -0,0 +1,53 @@ +import { motion, AnimatePresence } from 'framer-motion' +import * as RadixDialog from '@radix-ui/react-dialog' +import { useExitIntent } from 'use-exit-intent' + +import { RootContainer, Footer, ExitIntentModal } from 'components' +import { useDisclosure } from 'hooks' + +import type { AppProps } from 'next/app' + +import 'styles/global' + +export default function MyApp({ Component, pageProps, router }: AppProps) { + const { isOpen, open, toggle } = useDisclosure(false) + const { unsubscribe, registerHandler } = useExitIntent() + + registerHandler({ + id: 'openModal', + handler: () => open(), + }) + + function handleCloseModalUnsubscription() { + toggle(false) + unsubscribe() + } + + return ( + + + + +