diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..91077d0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +/node_modules +*.log +.DS_Store +.env +/.cache +/public/build +/build diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..a4ccd8e --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +DATABASE_URL="file:./data.db?connection_limit=1" +SESSION_SECRET="" +RECAPTCHA_ENABLED=false +RECAPTCHA_MANDATORY=false +RECAPTCHA_SITE_KEY= +RECAPTCHA_SECRET_KEY= + diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..992bd17 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,237 @@ +const inProduction = process.env.NODE_ENV === 'production' +const warnDev = inProduction ? 'error' : 'warn' + +/** @type {import('@types/eslint').Linter.BaseConfig} */ +module.exports = { + env: { + browser: true, // Browser global variables like `window` etc. + commonjs: true, // CommonJS global variables and CommonJS scoping.Allows require, exports and module. + jest: true, // Jest global variables like `it` etc. + node: true, // Defines things like process.env when generating through node + es2021: true, + }, + ignorePatterns: [ + "mocks", + "node_modules", + ".eslintrc.js", + "playwright.config.ts", + "tailwind.config.js", + "postcss.config.js", + "tests-examples/demo-todo-app.spec.ts", + "coverage", + "vitest.config.ts", + "remix.config.js", + "prettier.config.js", + "makeSessionSecret.js" + ], + extends: [ + "@remix-run/eslint-config", + "@remix-run/eslint-config/node", + "@remix-run/eslint-config/jest-testing-library", + 'eslint:recommended', + 'plugin:react/recommended', + 'plugin:react/jsx-runtime', + 'plugin:jsx-a11y/recommended', + 'plugin:react-hooks/recommended', + 'airbnb-typescript', + "prettier", + ], + // we're using vitest which has a very similar API to jest + // (so the linting plugins work nicely), but it means we have to explicitly + // set the jest version. + settings: { + react: { + version: 'detect', // Detect react version + }, + 'import/resolver': { + node: { + moduleDirectory: ['node_modules', 'app/'], + extensions: ['.js', '.jsx', '.ts', '.tsx', '.d.ts'], + }, + }, + jest: { + version: 28, + }, + }, + globals: { + Atomics: 'readonly', + SharedArrayBuffer: 'readonly', + }, + parser: '@typescript-eslint/parser', + parserOptions: { + requireConfigFile: false, + ecmaFeatures: { + jsx: true, + }, + sourceType: 'module', // Allows for the use of imports + ecmaVersion: "latest", + project: ['tsconfig.json'] + }, + plugins: [ + 'react', + 'import', + ], + + // root: true, // For configuration cascading. + rules: { + // Warn but allow console in production + 'no-console': ['warn'], + quotes: ["error", "single"], + "@typescript-eslint/quotes": ["error", "single"], + // At most this should be a warning. For now, since our api is returning + // snake-cased data, just turn it off. + camelcase: ['off'], + /** *************************************************************** + * Development relaxations. + * + * A few things that should be avoided in production, but which + * are useful for playing around in development. These will + * generate an error in production, and a warning in development. + *************************************************************** */ + // 'max-len': ['off'], + 'no-alert': [warnDev], + 'no-debugger': [warnDev], + 'no-unused-vars': ['off'], + "@typescript-eslint/no-unused-vars": "warn", + 'no-restricted-globals': [warnDev], + 'no-constant-condition': [warnDev], + 'react/jsx-props-no-spreading': ['off'], + 'react/jsx-no-useless-fragment': ['off'], + 'react/jsx-no-constructed-context-values': ['warn'], + + 'react/react-in-jsx-scope': ['off'], + + /** *************************************************************** + * Error prevention and best practices. + * + * Important rules for avoiding common errors go here. Many such + * rules are already covered by the "extends:" configs above, so + * only extra ones go here. There are plenty more to choose from + * that aren't included above -- worth exploring further. + **************************************************************** */ + + // Airbnb makes this an error, but since create-react-app and + // react-scripts manages many dependencies for us, the simplest thing + // is to downgrade this to a warning. + 'import/no-extraneous-dependencies': ['warn'], + + // airbnb makes this an error, but having one named export absolutely + // makes sense in some cases, depending on how the module is consumed + // (e.g. modules that export named constants -- sometimes there will only + // be one constant in a given file). + 'import/prefer-default-export': ['off'], + + // custom order of imports split to custom sections. + // groups array contains all predefined group names. Order can be customized. + // can be put together in array like parent and sibling + // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/order.md#groups-array + // pathGroups specify rules of custom patterns position, relative to groups. e.g. react* is before builtin imports + // https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/order.md#pathgroups-array-of-objects + 'import/order': [ + 'error', + { + groups: ['builtin', ['external', 'internal'], ['parent', 'sibling'], 'unknown', 'index', 'object', 'type'], + 'newlines-between': 'always', + pathGroups: [ + { pattern: 'react*', group: 'builtin', position: 'before' }, + { pattern: '@remix*/**', group: 'external', position: 'before' }, + { pattern: 'redux*/**', group: 'external', position: 'before' }, + { pattern: '~/lib/**', group: 'parent', position: 'before' }, + { pattern: '~/modules/**', group: 'parent', position: 'after' }, + { pattern: '~/ui/**', group: 'parent', position: 'after' }, + { pattern: '~/styles/**', group: 'parent', position: 'after' }, + ], + pathGroupsExcludedImportTypes: [], + alphabetize: { + order: 'asc', /* sort in ascending order. Options: ['ignore', 'asc', 'desc'] */ + caseInsensitive: true /* ignore case. Options: [true, false] */ + }, + }, + ], + + // Feels draconian -- sometimes "if (a) { return x } else { return y }" + // does a better job of conveying intention. + 'no-else-return': ['off'], + + // Worth discussing? Prevents use of hoisting (which is good), but I + // think this rule disallows too many things it shouldn't. I.e., + // there's generally nothing wrong with defining a function whose _body_ + // contains a reference to a variable lower down in the file, but this + // rule prevents that. + 'no-use-before-define': ['off'], + + // If we could make an exception for arrow functions, I'd say leave + // this on. But of the following three, the first contains a potential + // bug (if myFunc returns a value), the second is correct but unclear + // (you wouldn't think removing the curly braces would break it) and + // the third is correct and self-documenting. + // 1: useEffect(() => myFunc()) + // 2: useEffect(() => { myFunc() }) + // 3: useEffect(() => void myFunc()) + 'no-void': ['off'], + + // At the very least, code flagged by this rule is tricky to + // reason about, and probably warrants close inspection, even if the + // resolution is just to disable the rule on a case-by-case basis. + 'require-atomic-updates': ['warn'], + + // Allow jsx syntax in .js files. + 'react/jsx-filename-extension': ['error', { 'extensions': ['.js', '.jsx', '.ts', '.tsx'] }], + + // airbnb makes this an error, but seems annoying for now. Possibly + // add this back later? If enabled, prevents things like: + // names.map((name, index) => + // where the component key comes from an array index. + 'react/no-array-index-key': ['off'], + + // airbnb makes this an error, but seems annoying for now. Eventually + // add this back. Requires explicitly setting propTypes on all custom + // components. + 'react/prop-types': ['off'], + + /** ************************************************************** + * Style enforcement rules. + * + * Plenty of room for tweaking here... so add more rules, or adjust + * the existing ones, as needed. Most of these are fixable (meaning + * eslint --fix will automatically correct them), so leaving those + * as 'error' seems reasonable. + **************************************************************** */ + + // Ensure consistent newlines at start/end of array literals. + 'array-bracket-newline': ['error', 'consistent'], + + // Ensure consistent newlines between array literal elements. + 'array-element-newline': ['error', 'consistent'], + + // Allow both "() => { return foo }" and "() => foo". + 'arrow-body-style': ['off'], + + // Prefer no parens for single-argument arrow functions. + 'arrow-parens': ['error', 'as-needed'], + + // Require extra trailing commas in multiline lists and similar contexts, + // but not on last function argument. + 'comma-dangle': [ + 'error', + { + arrays: 'always-multiline', + objects: 'always-multiline', + imports: 'always-multiline', + exports: 'always-multiline', + functions: 'never', + }, + ], + + // Allow newlines either before or after "=>". + 'implicit-arrow-linebreak': ['off'], + + // Consistent newlines in multi-line ternary expressions (single-line still ok). + 'multiline-ternary': ['error', 'always-multiline'], + + 'no-multiple-empty-lines': ['error', { max: 2, maxBOF: 1, maxEOF: 0 }], + + // No semicolons (except single-line) + semi: ['error', 'never'], + }, +} diff --git a/.github/workflows/deploy.bak b/.github/workflows/deploy.bak new file mode 100644 index 0000000..e649a64 --- /dev/null +++ b/.github/workflows/deploy.bak @@ -0,0 +1,215 @@ +name: πŸš€ Deploy +on: + push: + branches: + - main + # - dev + pull_request: {} + +permissions: + actions: write + contents: read + +jobs: + lint: + name: ⬣ ESLint + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: βŽ” Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: πŸ“₯ Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: πŸ”¬ Lint + run: npm run lint + + typecheck: + name: Κ¦ TypeScript + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: βŽ” Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: πŸ“₯ Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: πŸ”Ž Type check + run: npm run typecheck --if-present + + vitest: + name: ⚑ Vitest + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: βŽ” Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: πŸ“₯ Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: ⚑ Run vitest + run: npm run test -- --coverage + + cypress: + name: ⚫️ Cypress + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: πŸ„ Copy test env vars + run: cp .env.example .env + + - name: βŽ” Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: πŸ“₯ Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: πŸ›  Setup Database + run: npx prisma migrate reset --force + + - name: βš™οΈ Build + run: npm run build + + - name: 🌳 Cypress run + uses: cypress-io/github-action@v4 + with: + start: npm run start:mocks + wait-on: "http://localhost:8811" + env: + PORT: "8811" + + build: + name: 🐳 Build + # only build/deploy main branch on pushes + if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push' }} + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: πŸ‘€ Read app name + uses: SebRollen/toml-action@v1.0.2 + id: app_name + with: + file: "fly.toml" + field: "app" + + - name: 🐳 Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + # Setup cache + - name: ⚑️ Cache Docker layers + uses: actions/cache@v3 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- + + - name: πŸ”‘ Fly Registry Auth + uses: docker/login-action@v2 + with: + registry: registry.fly.io + username: x + password: ${{ secrets.FLY_API_TOKEN }} + + - name: 🐳 Docker build + uses: docker/build-push-action@v3 + with: + context: . + push: true + tags: registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }} + build-args: | + COMMIT_SHA=${{ github.sha }} + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,mode=max,dest=/tmp/.buildx-cache-new + + # This ugly bit is necessary if you don't want your cache to grow forever + # till it hits GitHub's limit of 5GB. + # Temp fix + # https://github.com/docker/build-push-action/issues/252 + # https://github.com/moby/buildkit/issues/1896 + - name: 🚚 Move cache + run: | + rm -rf /tmp/.buildx-cache + mv /tmp/.buildx-cache-new /tmp/.buildx-cache + + deploy: + name: πŸš€ Deploy + runs-on: ubuntu-latest + needs: [lint, typecheck, vitest, cypress, build] + # needs: [lint, typecheck, vitest, build] + # only build/deploy main branch on pushes + if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push' }} + + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: πŸ‘€ Read app name + uses: SebRollen/toml-action@v1.0.2 + id: app_name + with: + file: "fly.toml" + field: "app" + + - name: πŸš€ Deploy Staging + if: ${{ github.ref == 'refs/heads/dev' }} + uses: superfly/flyctl-actions@1.3 + with: + args: "deploy --app ${{ steps.app_name.outputs.value }}-staging --image registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }}" + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} + + - name: πŸš€ Deploy Production + if: ${{ github.ref == 'refs/heads/main' }} + uses: superfly/flyctl-actions@1.3 + with: + args: "deploy --image registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }}" + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..894ff0d --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,177 @@ +name: πŸš€ Deploy +on: + push: + branches: + - main + # - dev + pull_request: {} + +permissions: + actions: write + contents: read + +jobs: + lint: + name: ⬣ ESLint + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: βŽ” Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: πŸ“₯ Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: πŸ”¬ Lint + run: npm run lint + + typecheck: + name: Κ¦ TypeScript + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: βŽ” Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: πŸ“₯ Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: πŸ”Ž Type check + run: npm run typecheck --if-present + + vitest: + name: ⚑ Vitest + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: βŽ” Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: πŸ“₯ Download deps + uses: bahmutov/npm-install@v1 + with: + useLockFile: false + + - name: ⚑ Run vitest + run: npm run test -- --coverage + + build: + name: 🐳 Build + # only build/deploy main branch on pushes + if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push' }} + runs-on: ubuntu-latest + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: πŸ‘€ Read app name + uses: SebRollen/toml-action@v1.0.2 + id: app_name + with: + file: "fly.toml" + field: "app" + + - name: 🐳 Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + # Setup cache + - name: ⚑️ Cache Docker layers + uses: actions/cache@v3 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- + + - name: πŸ”‘ Fly Registry Auth + uses: docker/login-action@v2 + with: + registry: registry.fly.io + username: x + password: ${{ secrets.FLY_API_TOKEN }} + + - name: 🐳 Docker build + uses: docker/build-push-action@v3 + with: + context: . + push: true + tags: registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }} + build-args: | + COMMIT_SHA=${{ github.sha }} + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,mode=max,dest=/tmp/.buildx-cache-new + + # This ugly bit is necessary if you don't want your cache to grow forever + # till it hits GitHub's limit of 5GB. + # Temp fix + # https://github.com/docker/build-push-action/issues/252 + # https://github.com/moby/buildkit/issues/1896 + - name: 🚚 Move cache + run: | + rm -rf /tmp/.buildx-cache + mv /tmp/.buildx-cache-new /tmp/.buildx-cache + + deploy: + name: πŸš€ Deploy + runs-on: ubuntu-latest + needs: [lint, typecheck, vitest, build] + # only build/deploy main branch on pushes + if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push' }} + + steps: + - name: πŸ›‘ Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.11.0 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: πŸ‘€ Read app name + uses: SebRollen/toml-action@v1.0.2 + id: app_name + with: + file: "fly.toml" + field: "app" + + - name: πŸš€ Deploy Staging + if: ${{ github.ref == 'refs/heads/dev' }} + uses: superfly/flyctl-actions@1.3 + with: + args: "deploy --app ${{ steps.app_name.outputs.value }}-staging --image registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }}" + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} + + - name: πŸš€ Deploy Production + if: ${{ github.ref == 'refs/heads/main' }} + uses: superfly/flyctl-actions@1.3 + with: + args: "deploy --image registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }}" + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} diff --git a/.github/workflows/playwright.bak b/.github/workflows/playwright.bak new file mode 100644 index 0000000..041160c --- /dev/null +++ b/.github/workflows/playwright.bak @@ -0,0 +1,27 @@ +name: Playwright Tests +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] +jobs: + test: + timeout-minutes: 60 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: 16 + - name: Install dependencies + run: npm ci + - name: Install Playwright Browsers + run: npx playwright install --with-deps + - name: Run Playwright tests + run: npx playwright test + - uses: actions/upload-artifact@v3 + if: always() + with: + name: playwright-report + path: playwright-report/ + retention-days: 30 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..593a5f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +node_modules +.vscode + +/build +/public/build +.env + +/coverage + +/prisma/data.db +/prisma/data.db-journal +/prisma/users.json + +/app/styles + +/test-results/ +/playwright-report/ +/playwright/.cache/ diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile new file mode 100644 index 0000000..e52ca2d --- /dev/null +++ b/.gitpod.Dockerfile @@ -0,0 +1,9 @@ +FROM gitpod/workspace-full + +# Install Fly +RUN curl -L https://fly.io/install.sh | sh +ENV FLYCTL_INSTALL="/home/gitpod/.fly" +ENV PATH="$FLYCTL_INSTALL/bin:$PATH" + +# Install GitHub CLI +RUN brew install gh diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 0000000..f07c562 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,48 @@ +# https://www.gitpod.io/docs/config-gitpod-file + +image: + file: .gitpod.Dockerfile + +ports: + - port: 3000 + onOpen: notify + +tasks: + - name: Restore .env file + command: | + if [ -f .env ]; then + # If this workspace already has a .env, don't override it + # Local changes survive a workspace being opened and closed + # but they will not persist between separate workspaces for the same repo + + echo "Found .env in workspace" + else + # There is no .env + if [ ! -n "${ENV}" ]; then + # There is no $ENV from a previous workspace + # Default to the example .env + echo "Setting example .env" + + cp .env.example .env + else + # After making changes to .env, run this line to persist it to $ENV + # eval $(gp env -e ENV="$(base64 .env | tr -d '\n')") + # + # Environment variables set this way are shared between all your workspaces for this repo + # The lines below will read $ENV and print a .env file + + echo "Restoring .env from Gitpod" + + echo "${ENV}" | base64 -d | tee .env > /dev/null + fi + fi + + - init: npm install + command: npm run setup && npm run dev + +vscode: + extensions: + - ms-azuretools.vscode-docker + - esbenp.prettier-vscode + - dbaeumer.vscode-eslint + - bradlc.vscode-tailwindcss diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..521a9f7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +legacy-peer-deps=true diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..21b66da --- /dev/null +++ b/.prettierignore @@ -0,0 +1,17 @@ +node_modules +.vscode +coverage +/build +/public/build +.env +public +.eslintrc.js +CHANGELOG.md +docker-compose.yml +postcss.config.js +remix.config.js +tailwind.config.js +tsconfig.json +vitest.config.ts +/app/styles/**/*.css +/app/styles/**/*.scss diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e7ed0f4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes and releases will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.0.0] - 2022-12-29 +### Added +- Created CHANGELOG.md +- Created ROADMAP.md + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..aed2a24 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,61 @@ +# base node image +FROM node:18-bullseye-slim as base + +# set for base and all layer that inherit from it +ENV NODE_ENV production + +# Install openssl for Prisma +RUN apt-get update && apt-get install -y openssl sqlite3 + +# Install all node_modules, including dev dependencies +FROM base as deps + +WORKDIR /myapp + +ADD package.json package-lock.json .npmrc ./ +RUN npm install --production=false + +# Setup production node_modules +FROM base as production-deps + +WORKDIR /myapp + +COPY --from=deps /myapp/node_modules /myapp/node_modules +ADD package.json package-lock.json .npmrc ./ +RUN npm prune --production + +# Build the app +FROM base as build + +WORKDIR /myapp + +COPY --from=deps /myapp/node_modules /myapp/node_modules + +ADD prisma . +RUN npx prisma generate + +ADD . . +RUN npm run build + +# Finally, build the production image with minimal footprint +FROM base + +ENV DATABASE_URL=file:/data/sqlite.db +ENV PORT="8080" +ENV NODE_ENV="production" + +# add shortcut for connecting to database CLI +RUN echo "#!/bin/sh\nset -x\nsqlite3 \$DATABASE_URL" > /usr/local/bin/database-cli && chmod +x /usr/local/bin/database-cli + +WORKDIR /myapp + +COPY --from=production-deps /myapp/node_modules /myapp/node_modules +COPY --from=build /myapp/node_modules/.prisma /myapp/node_modules/.prisma + +COPY --from=build /myapp/build /myapp/build +COPY --from=build /myapp/public /myapp/public +COPY --from=build /myapp/package.json /myapp/package.json +COPY --from=build /myapp/start.sh /myapp/start.sh +COPY --from=build /myapp/prisma /myapp/prisma + +ENTRYPOINT [ "./start.sh" ] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..66a55d0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Infonomic Company Limited + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..181981c --- /dev/null +++ b/README.md @@ -0,0 +1,382 @@ +# A Remix Demo App + +A Remix demo app based on the [Remix Indie Stack](https://github.com/remix-run/indie-stack) quick-start project (a simple note-taking application) + +![A Remix Note-taking App](https://github.com/infonomic/remix.infonomic.io/raw/develop/screenshot.png) + +Learn more about [Remix Stacks](https://remix.run/stacks). + +The original README is [further below](#original-indie-stack-quick-start-readme---whats-in-the-stack) (with some modifications) + +## Rationale + +The quick-start [Indie stack example](https://github.com/remix-run/indie-stack) is a great way to get started with Remix, however, we wanted to create a fuller example with a few goals in mind: + +1. We wanted to experiment with headless UI systems, in particular [Radix](https://www.radix-ui.com/) and [Radix with Tailwind CSS](https://tailwindcss-radix.vercel.app/). +2. We wanted to use [Tailwind CSS](https://tailwindcss.com/), but also wanted to configure [postcss](https://postcss.org/) to allow the creation of `.css` sidecar files for any route or component. We've followed the [styling guide](https://remix.run/docs/en/v1/guides/styling#surfacing-styles) at Remix for 'surfacing' component-level styles in routes. +3. With the above, we wanted to create a 'skeletal' UI system with core components styled for our basic light and dark themes (with a theme provider courtesy Matt Stobbs and his excellent [The Complete Guide to Dark Mode with Remix](https://www.mattstobbs.com/remix-dark-mode/) blog post). [Material UI](https://mui.com/), [Bootstrap](https://getbootstrap.com/) and others, represent great value and are a good way to kick start a design system. The MUI team in particular produce an amazing collection of free-to-use components. But we wanted to try and create a 'back to basics' design system, primarily built using CSS (as opposed to CSS-in-JS). Our design system is far from perfect, and far from complete - but it was an interesting exercise in hand picking the best available headless components out there, and adapting them to suit our needs. + +## Getting Started + +1. Clone or fork this repo. +2. Run `npm install` to install dependencies. If you don't want `package-lock.json` to be 'touched', or are planning on submitting a PR - please use `npm ci` instead. +3. Copy the `.env.example` file to `.env` - and optionally fill in your reCAPTCHA keys from [Google reCAPTCHA](https://www.google.com/recaptcha/about/). +4. Run `node makeSessionSecret.js` to generate your session secret and place it in your `.env` file above. +5. Copy the `prisma/users.example.json` file to `prisma/users.json` - these are the seed user accounts, including an admin user. +6. Run `npm run setup` to initialize the local SQLite database and seed users. +7. Run `npm run dev` to start your local development environment. +8. Run `rm -rf build` and `npm run build` and `npm run start` to run a production build. +9. If you'd like to deploy the application to [Fly.io](https://fly.io) - follow the instructions below in the original README. Be sure to rename the application (and unique Fly.io app code) in the `name` section of `package.json`. + +## Approach + +### Remix + +Remix is pretty cool and we admire the [Remix Philosophy](https://remix.run/docs/en/v1/pages/philosophy). We've tried to do things the Remix way - but, obviously we're new to Remix and so suggestions are welcome. There are a lot of good example Remix projects out there - including (but not limited to)... + +[https://github.com/jacob-ebey/remix-dashboard-template](https://github.com/jacob-ebey/remix-dashboard-template)
+[https://github.com/jacob-ebey/remix-ecommerce](https://github.com/jacob-ebey/remix-ecommerce)
+[https://github.com/kentcdodds/kentcdodds.com](https://github.com/kentcdodds/kentcdodds.com)
+[https://github.com/epicweb-dev/rocket-rental](https://github.com/epicweb-dev/rocket-rental)
+ +### Directory Structure + +We've seen a few different ways to organize both routes and the overall Remix directory structure. We've mostly followed the original quick-start structure, with the addition of a `modules` directory (called `route-containers`, or even `components` in other projects). + +For us `modules` represent any functional or feature area of the application associated with a route. It's where route-specific React components live - like the `Hero.tsx` component in the `home` module for the home / index route. + +See the [Style System](#style-system) section below for the directory structure of our style system + +### Data Layer + +As in the original quick-start app, this project uses [Prisma](https://www.prisma.io/) with `User` and `Note` Prisma models for data access. Prisma looks great, and we should probably spent more time with this - but we're new to Prisma as well, having relied on [Knex](https://knexjs.org/) and plain SQL for relational database query building for years now. + +We've updated the Prisma `/prisma/schema.prisma` `User` model to include an `isAdmin` field. We've also created a `/prisma/users.example.json` source user file for seeding users, including an admin account. Follow the [Getting Started](#getting-started) instructions above to rename this file and seed your database. + +Again, as in the original project - we're using SQLite as the database, which makes experimenting with Remix and deploying to Fly.io a breeze. + +### Style System + +The project is configured to use [Tailwind CSS](https://tailwindcss.com/) and plain CSS via [postcss](https://postcss.org/) and [postcss-cli](https://github.com/postcss/postcss-cli). There is a ['SMACSS-like'](http://smacss.com/) CSS bundle in the root level `/shared/css` directory - along with the main `/shared/css/tailwind.css` and `/shared/css/app.css` source stylesheets. The 'root-level' shared CSS files and imports are processed and placed in the 'app level' styles directory with a corresponding directory structure. We've named the root-level styles directory `shared` for a reason. ;-) + +We've configured postcss-cli with the `--base` switch, which will re-create the source directory structure in the target output directory. And we've configured the postcss tasks to look for 'side car' stylesheets sitting next to route or module components (see [Directory Structure](#directory-structure) above). + +So... + +CSS files in the root level `/shared` directory are processed and placed in the `/app/styles/shared` app-level styles directory. Any `.css` files that appear next to components or routes in the routes or modules directories are also processed and placed in the `/app/styles/app` directory. + +The entire system can be illustrated as follows: + +Source +
+/shared
+└── css
+    β”œβ”€β”€ app.css
+    β”œβ”€β”€ base
+    β”‚Β Β  β”œβ”€β”€ autofill.css
+    β”‚Β Β  β”œβ”€β”€ base.css
+    β”‚Β Β  β”œβ”€β”€ fonts.css
+    β”‚Β Β  β”œβ”€β”€ reset.css
+    β”‚Β Β  β”œβ”€β”€ scrollbars.css
+    β”‚Β Β  └── typography.css
+    β”œβ”€β”€ components
+    β”‚Β Β  β”œβ”€β”€ components.css
+    β”‚Β Β  β”œβ”€β”€ icon-element.css
+    β”‚Β Β  └── theme-switcher.css
+    β”œβ”€β”€ layouts
+    β”‚Β Β  β”œβ”€β”€ global.css
+    β”‚Β Β  └── layouts.css
+    └── tailwind.css
+
+ +
+/app
+β”œβ”€β”€ modules
+β”‚Β Β  β”œβ”€β”€ home
+β”‚Β Β  β”‚Β Β  β”œβ”€β”€ hero.css
+β”‚Β Β  β”‚Β Β  β”œβ”€β”€ hero.tsx
+β”‚Β Β  β”‚Β Β  └── index.ts
+└── routes
+ Β Β  β”œβ”€β”€ index.css
+ Β Β  └── index.tsx
+
+ +Output + +
+/app
+└── styles
+ Β Β  β”œβ”€β”€ app
+ Β Β  β”‚Β Β  β”œβ”€β”€ modules
+ Β Β  β”‚Β Β  β”‚Β Β  └── home
+ Β Β  β”‚Β Β  β”‚Β Β      └── hero.css
+ Β Β  β”‚Β Β  └── routes
+ Β Β  β”‚Β Β      └── index.css
+ Β Β  └── shared
+ Β Β      └── css
+ Β Β          β”œβ”€β”€ app.css
+ Β Β          └── tailwind.css
+
+
+ +This means of course that you will need to import stylesheets from the `/app/styles` directory, and not the source route, module or shared CSS directories. In order to 'surface' module-level stylesheets in a route, we followed the [styling guide](https://remix.run/docs/en/v1/guides/styling#surfacing-styles) at Remix. It's not a perfect 'co-located' setup - but it works, and it was the best we could come up with for now. Again - suggestions welcome. You can see an example that combines the `Hero.css` stylesheet with the `index.css` stylesheet here in the [index.tsx route](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/routes/index.tsx). + +### Components and Design System + +Building a complete design system including design language and tokens is not a small task and we've barely scratched the surface. We've mostly relied on Tailwind CSS utility classes and Tailwind plugins for typography, spacing and color. No effort was made to extract a configurable theme system (apart from the light and dark mode switcher). We simply built what worked. We also think there's value in 'intents' - such as 'primary', 'secondary', 'info', 'success', 'warning', 'danger' - and so button, alert and toast components implement an 'intent' system. We may create mapping definitions for these in `tailwind.config.js` to make swapping out a base color theme and color system easier. + +Here's a brief introduction to the core components, where they came from, and how they've been configured. + +[Alert](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/components/notifications/alert.tsx) - supports 'intents', and is based on the Radix `@radix-ui/react-primitive` - which in turn means it supports 'slots' and the `asChild` prop - allowing you to takeover the alert completely, merging default alert styles and props with your own styles and props ('slot' uses `React.cloneElement` and `mergeProps` under the hood. It's very cool). Alerts are animated via [Headless UI Transition](https://headlessui.com/react/transition). + +[BreadcrumbTrail](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/breadcrumbs) - is a 'typed' implementation of Breadcrumbs that used Remix's `useMatches` to match route `handle` methods - looking for Breadcrumbs. You can see an example here in the [Note Delete](https://github.com/infonomic/remix.infonomic.io/blob/22138d74257fc1f71c5ce4d2d8464ccd04d35389/app/routes/notes/%24noteId.delete.tsx#L70) route. We have no idea if this is the best way to implement a BreadcrumbTrail in Remix - but it seems to work. We _think_ - but may be wrong, that with Remix's file-based router, there's no other way to get or annotate route information, such as a route label - hence this approach. Note too that the `handle` method can implement as many `handle` functions as you like by `&&`-ing or `||`-ing additional handle method types (i.e. handle isn't limited to `BreadcrumbHandle` when Breadcrumbs are implemented on a `handle` method). + +[Button](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/button) - supports 'variants' and 'intents', and is also based on the Radix `@radix-ui/react-primitive` - which in turn means it supports 'slots' and the `asChild` prop - allowing you to takeover the button completely, merging default button styles and props with your own styles and props ('slot' uses `React.cloneElement` and `mergeProps` under the hood). This makes it trivial to 'wrap' and customize the Remix router `Link` component as follows: + +```TSX + +``` +The core button style system was adapted from [Sajad Ahmad Nawabi's](https://github.com/sajadevo) excellent [Material Tailwind](https://github.com/creativetimofficial/material-tailwind) project. The Button component supports [Material Ripple Effects](https://github.com/sajadevo/material-ripple-effects) - also from [Sajad Ahmad Nawabi](https://github.com/sajadevo). + +As mentioned in the introduction to this section, we've intentionally removed any advanced theme configuration system for now. We're also aware of Joe Bell's work on [CVA](https://github.com/joe-bell/cva) - but haven't looked closely enough yet to know whether this would be a better approach. + +[Card](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/card) - is a simple `div` component with default 'card' styling - also implementing Radix `asChild`. + +[Container](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/components/container.tsx) - is one of our building-block layout components supporting content-width layout, and 'shy edges' from max widths. + +[FocusTrap](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/elements/focus-trap.client.ts) - is a very cool module for 'trapping' focus within a component - like a modal, dialog, or toast. We're using it in our [Toast](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/components/notifications/toast.tsx) component. We found this in Jacob Ebey's [Remix dashboard app](https://github.com/jacob-ebey/remix-dashboard-template). It was bequeathed to us under the 'Just take it. I do not care.' license. + +[Input](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/input) - inputs include Input, Checkbox, and TextArea components. Input and TextArea support labels, help text and error messages. We've not yet implemented a 'variant' system for these components. CheckBox is a functional component wrapper around the [Radix Tailwind project Checkbox](https://github.com/ecklf/tailwindcss-radix/blob/main/demo/components/checkbox.tsx) component. + +[Pager](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/pager) - is a styled 'placeholder' component for a general purpose pager. It has not been fully implemented - unlike TablePager below. Initial Pager styling courtesy of [Flowbite Pager](https://flowbite.com/docs/components/pagination/). + +[ScrollToTop](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/components/scroll-to-top.tsx) - is a simple and dynamic 'scroll to top' component. It will only appear after scrolling down. This is a CSS-styled component with the component stylesheet located at `/shared/css/components/scroll-to-top.css`. + +[Section](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/components/section.tsx) - like Container above, is one of our building-block layout components. + +[Select](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/select) - is a functional component wrapper around the [Radix Tailwind project Select](https://github.com/ecklf/tailwindcss-radix/blob/main/demo/components/select.tsx) component. + +[Table](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/table) - components include all styled table elements and a TablePager component. The TablePager component is dependent on the excellent [TanStack Table](https://tanstack.com/table/v8) component (formerly React Table), however, this probably isn't the 'Remix way'. A better implementation might be to surround all of the pager controls in a form element with a 'get' method and action that simply submits updated url search params (aka query string parameters). Initial TablePager styling courtesy of [Flowbite Pager](https://flowbite.com/docs/components/pagination/). + +[ThemeSwitch](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/components/theme-switch.tsx) - is our component for changing between light and dark themes via [ThemeProvider](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/ui/theme/theme-provider.tsx) - all based on Matt Stobbs' excellent blog post - [The Complete Guide to Dark Mode with Remix](https://www.mattstobbs.com/remix-dark-mode/). + +[Toast](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/notifications) - is an 'intent'-enabled functional component wrapper around the [Radix Tailwind project Toast](https://github.com/ecklf/tailwindcss-radix/blob/main/demo/components/toast.tsx) component. + +[Tooltip](https://github.com/infonomic/remix.infonomic.io/tree/develop/app/ui/components/tooltip) - is a functional component wrapper around the [Radix Tailwind project Tooltip](https://github.com/ecklf/tailwindcss-radix/blob/main/demo/components/tooltip.tsx) component. + + +### Validation and Errors + +Data input is validated by both client- and server-side [Zod schemas](https://github.com/colinhacks/zod) and [React Hook Form Zod resolvers](https://github.com/react-hook-form/resolvers) - with errors reported either at field-level for form data errors, or via general alerts for any non-field-based errors. We've tried to implement utility methods for server and client errors returned via Zod, as well as other conditions such as unique constraint violations. You can see an example in the [/account/$userId.email.tsx](https://github.com/infonomic/remix.infonomic.io/blob/develop/app/routes/account/%24userId.email.tsx) route. + +### i18n and L10n + +We've yet to implement localization / translations, although another interesting aspect of Remix as a 'first class' SSR framework, is that client preferred language detection can be done via the Accept-Language HTTP header. + +[Sergio XalambrΓ­](https://github.com/sergiodxa) appears to show the way.... + +[https://sergiodxa.com/articles/localizing-remix-apps-with-i18next](https://sergiodxa.com/articles/localizing-remix-apps-with-i18next)
+[https://github.com/sergiodxa/remix-i18next](https://github.com/sergiodxa/remix-i18next) +
+ +This is high on our TODO list + + +### A11y + +We're committed to enabling people with limited abilities to use websites. Many of the components we've used have been built with a11y in mind. We've also tried to include WAI-ARIA compliant roles and labels where appropriate although there is almost certainly more to do here. We've not yet completed a WAI-ARIA review of this project, and so yet again, suggestions, or raised issues related to omissions or errors greatly appreciated. + +### ESLint + +We've included the [eslint-config-airbnb-typescript](https://github.com/iamturns/eslint-config-airbnb-typescript) plugin in our ESLint configuration, along with a handful of custom rules. The rest comes from the quick-start app. + +### Tests + +We removed Cypress and have configured [Playwright](https://playwright.dev/) for end-to-end tests. Vitest is still enabled - which explains the test, tests, tests-examples directories. We'll follow [Kent Dodd's lead here](https://github.com/epicweb-dev/rocket-rental) and er... em... we're going to write some tests Β―\\_(ツ)_/Β― + +Also high on our TODO list + +### Docker + +The Docker image that came with the quick-start app for deployment to Fly.io (and [Firecracker microVMs](https://firecracker-microvm.github.io/)) has been updated to Node v18 LTS. There are also `docker-build.sh`, `docker-compose.yml` and `docker-exec.sh` files that will allow you to build and run the Docker image and container locally if you'd like to test a local Docker environment. Note that we don't currently mount the SQLite data directory, and so starting a new container instance will create a new database. This is also a great start for creating your own deployment pipeline via Docker and say for example [AWS ECS](https://aws.amazon.com/ecs/), or other. + +## Contributions + +Feedback, thoughts and suggestions are most welcome. Issues and even PRs would be super too! + +We've created [TODO list](TODO.md). + +Hope some of this is of help to those of you just getting started with Remix and headless UI component systems (as we are). + +

 

+ +
+ +## Original Indie Stack quick-start README - What's in the stack + +- [Fly app deployment](https://fly.io) with [Docker](https://www.docker.com/) +- Production-ready [SQLite Database](https://sqlite.org) +- Healthcheck endpoint for [Fly backups region fallbacks](https://fly.io/docs/reference/configuration/#services-http_checks) +- [GitHub Actions](https://github.com/features/actions) for deploy on merge to production and staging environments +- Email/Password Authentication with [cookie-based sessions](https://remix.run/docs/en/v1/api/remix#createcookiesessionstorage) +- Database ORM with [Prisma](https://prisma.io) +- Styling with [Tailwind](https://tailwindcss.com/) +- Local third party request mocking with [MSW](https://mswjs.io) +- Unit testing with [Vitest](https://vitest.dev) and [Testing Library](https://testing-library.com) +- Code formatting with [Prettier](https://prettier.io) +- Linting with [ESLint](https://eslint.org) +- Static Types with [TypeScript](https://typescriptlang.org) + +Not a fan of bits of the stack? Fork it, change it, and use `npx create-remix --template your/repo`! Make it your own. + +## Quickstart + +Click this button to create a [Gitpod](https://gitpod.io) workspace with the project set up and Fly pre-installed + +[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/from-referrer/) + +## Development + +- This step only applies if you've opted out of having the CLI install dependencies for you: + + ```sh + npx remix init + ``` + +- Initial setup: _If you just generated this project, this step has been done for you._ + + ```sh + npm run setup + ``` + +- Start dev server: + + ```sh + npm run dev + ``` + +This starts your app in development mode, rebuilding assets on file changes. + +The database seed script creates a new user with some data you can use to get started: + +- Email: `rachel@remix.run` +- Password: `racheliscool` + +### Relevant code: + +This is a pretty simple note-taking app, but it's a good example of how you can build a full stack app with Prisma and Remix. The main functionality is creating users, logging in and out, and creating and deleting notes. + +- creating users, and logging in and out [./app/models/user.server.ts](./app/models/user.server.ts) +- user sessions, and verifying them [./app/session.server.ts](./app/session.server.ts) +- creating, and deleting notes [./app/models/note.server.ts](./app/models/note.server.ts) + +## Deployment + +This Remix Stack comes with two GitHub Actions that handle automatically deploying your app to production and staging environments. + +Prior to your first deployment, you'll need to do a few things: + +- [Install Fly](https://fly.io/docs/getting-started/installing-flyctl/) + +- Sign up and log in to Fly + + ```sh + fly auth signup + ``` + + > **Note:** If you have more than one Fly account, ensure that you are signed into the same account in the Fly CLI as you are in the browser. In your terminal, run `fly auth whoami` and ensure the email matches the Fly account signed into the browser. + +- Create two apps on Fly, one for staging and one for production: + + ```sh + fly apps create remix-infonomic-io-c6b7 + fly apps create remix-infonomic-io-c6b7-staging + ``` + + > **Note:** Make sure this name matches the `app` set in your `fly.toml` file. Otherwise, you will not be able to deploy. + + - Initialize Git. + + ```sh + git init + ``` + +- Create a new [GitHub Repository](https://repo.new), and then add it as the remote for your project. **Do not push your app yet!** + + ```sh + git remote add origin + ``` + +- Add a `FLY_API_TOKEN` to your GitHub repo. To do this, go to your user settings on Fly and create a new [token](https://web.fly.io/user/personal_access_tokens/new), then add it to [your repo secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) with the name `FLY_API_TOKEN`. + +- Add a `SESSION_SECRET` to your fly app secrets, to do this you can run the following commands: + + ```sh + fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app remix-infonomic-io-c6b7 + fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app remix-infonomic-io-c6b7-staging + ``` + + If you don't have openssl installed, you can also use [1password](https://1password.com/password-generator/) to generate a random secret, just replace `$(openssl rand -hex 32)` with the generated secret. + +- Create a persistent volume for the sqlite database for both your staging and production environments. Run the following: + + ```sh + fly volumes create data --size 1 --app remix-infonomic-io-c6b7 + fly volumes create data --size 1 --app remix-infonomic-io-c6b7-staging + ``` + +Now that everything is set up you can commit and push your changes to your repo. Every commit to your `main` branch will trigger a deployment to your production environment, and every commit to your `dev` branch will trigger a deployment to your staging environment. + +### Connecting to your database + +The sqlite database lives at `/data/sqlite.db` in your deployed application. You can connect to the live database by running `fly ssh console -C database-cli`. + +### Getting Help with Deployment + +If you run into any issues deploying to Fly, make sure you've followed all of the steps above and if you have, then post as many details about your deployment (including your app name) to [the Fly support community](https://community.fly.io). They're normally pretty responsive over there and hopefully can help resolve any of your deployment issues and questions. + +## GitHub Actions + +We use GitHub Actions for continuous integration and deployment. Anything that gets into the `main` branch will be deployed to production after running tests/build/etc. Anything in the `dev` branch will be deployed to staging. + +## Testing + +```ts +cy.login(); +// you are now logged in as a new user +``` + +We also have a utility to auto-delete the user at the end of your test. Just make sure to add this in each test file: + +```ts +afterEach(() => { + cy.cleanupUser(); +}); +``` + +That way, we can keep your local db clean and keep your tests isolated from one another. + +### Vitest + +For lower level tests of utilities and individual components, we use `vitest`. We have DOM-specific assertion helpers via [`@testing-library/jest-dom`](https://testing-library.com/jest-dom). + +### Type Checking + +This project uses TypeScript. It's recommended to get TypeScript set up for your editor to get a really great in-editor experience with type checking and auto-complete. To run type checking across the whole project, run `npm run typecheck`. + +### Linting + +This project uses ESLint for linting. That is configured in `.eslintrc.js`. + +### Formatting + +We use [Prettier](https://prettier.io/) for auto-formatting in this project. It's recommended to install an editor plugin (like the [VSCode Prettier plugin](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)) to get auto-formatting on save. There's also a `npm run format` script you can run to format all files in the project. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..0dafd1e --- /dev/null +++ b/TODO.md @@ -0,0 +1,15 @@ +# TODO + +## General + +- [ ] Configure server logger with [Pino](https://github.com/pinojs/pino) +- [ ] Consider form error handling where after receiving server errors, any changes in values of the form reset server errors, and only client form errors are display +- [ ] Implement i18n and L10n - likely via [https://sergiodxa.com/articles/localizing-remix-apps-with-i18next](https://sergiodxa.com/articles/localizing-remix-apps-with-i18next) and +[https://github.com/sergiodxa/remix-i18next](https://github.com/sergiodxa/remix-i18next) +- [ ] A11y audit +- [ ] Tests! Playwright and unit tests + +## Components + +- [ ] Button: add 'busy' state and Loader indicator (as in sign-in.tsx) +- [ ] Pager: implement general purpose pager component \ No newline at end of file diff --git a/app/db.server.ts b/app/db.server.ts new file mode 100644 index 0000000..a9fb111 --- /dev/null +++ b/app/db.server.ts @@ -0,0 +1,24 @@ +import { PrismaClient } from '@prisma/client' + +let prisma: PrismaClient + +declare global { + // eslint-disable-next-line @typescript-eslint/naming-convention + var __db__: PrismaClient +} + +// this is needed because in development we don't want to restart +// the server with every change, but we want to make sure we don't +// create a new connection to the DB with every change either. +// in production we'll have a single connection to the DB. +if (process.env.NODE_ENV === 'production') { + prisma = new PrismaClient() +} else { + if (!global.__db__) { + global.__db__ = new PrismaClient() + } + prisma = global.__db__ + prisma.$connect() +} + +export { prisma } diff --git a/app/entry.client.tsx b/app/entry.client.tsx new file mode 100644 index 0000000..9eb3086 --- /dev/null +++ b/app/entry.client.tsx @@ -0,0 +1,28 @@ +import { startTransition, StrictMode } from 'react' + +import { RemixBrowser } from '@remix-run/react' + +import { hydrateRoot } from 'react-dom/client' + +import { registerFocusTrap } from '~/ui/elements/focus-trap.client' + +registerFocusTrap() + +const hydrate = () => { + startTransition(() => { + hydrateRoot( + document, + + + + ) + }) +} + +if (window.requestIdleCallback) { + window.requestIdleCallback(hydrate) +} else { + // Safari doesn't support requestIdleCallback + // https://caniuse.com/requestidlecallback + window.setTimeout(hydrate, 1) +} diff --git a/app/entry.server.tsx b/app/entry.server.tsx new file mode 100644 index 0000000..f40cb75 --- /dev/null +++ b/app/entry.server.tsx @@ -0,0 +1,51 @@ +import { PassThrough } from 'stream' + +import type { EntryContext } from '@remix-run/node' +import { Response } from '@remix-run/node' +import { RemixServer } from '@remix-run/react' + +import isbot from 'isbot' +import { renderToPipeableStream } from 'react-dom/server' + +const ABORT_DELAY = 5000 + +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext +) { + const callbackName = isbot(request.headers.get('user-agent')) ? 'onAllReady' : 'onShellReady' + + return new Promise((resolve, reject) => { + let didError = false + + const { pipe, abort } = renderToPipeableStream(, { + [callbackName]: () => { + const body = new PassThrough() + + responseHeaders.set('Content-Type', 'text/html') + + resolve( + new Response(body, { + headers: responseHeaders, + status: didError ? 500 : responseStatusCode, + }) + ) + + pipe(body) + }, + onShellError: (err: unknown) => { + reject(err) + }, + onError: (error: unknown) => { + didError = true + // TODO: Configure server-side logger + // eslint-disable-next-line no-console + console.error(error) + }, + }) + + setTimeout(abort, ABORT_DELAY) + }) +} diff --git a/app/hooks/useInterval.js b/app/hooks/useInterval.js new file mode 100644 index 0000000..e27ea94 --- /dev/null +++ b/app/hooks/useInterval.js @@ -0,0 +1,65 @@ +import { useEffect, useState, useRef } from 'react' + +/** + * If always options: always is true, the interval will be active + * irrespective of tab state (i.e. tab is active and focused or not in + * focus or minimized) effectively making useInterval an 'always on' check + * (as long as the component using useInterval is still mounted) + * @param {*} duration - interval in milliseconds + * @param {*} options - { always: bool, running: bool} + * @returns + */ +const useInterval = (duration, options = {}) => { + const defaults = { always: false, running: true } + const settings = { ...defaults, ...options } + const isBrowserTabActiveRef = useRef(true) + + const [count, setCount] = useState(0) + const [running, setRunning] = useState(settings.running) + + const stop = () => { + setRunning(false) + setCount(0) + } + + const start = () => { + setRunning(true) + } + + useEffect(() => { + const onVisibilityChange = () => { + isBrowserTabActiveRef.current = (document.visibilityState === 'visible') + } + + if (!settings.always) { + window.addEventListener('visibilitychange', onVisibilityChange) + } + + if (duration > 0 && running) { + const interval = setInterval(() => { + // will always be true if the always option is true but add the check here + // for readability + if (isBrowserTabActiveRef.current || settings.always) { + setCount(prev => prev + 1) + } + }, duration) + + // Return the 'unmount' callback + return () => { + clearInterval(interval) + if (!settings.always) { + window.removeEventListener('visibilitychange', onVisibilityChange) + } + } + } else { + // Return no 'unmount' callback + return null + } + }, [duration, isBrowserTabActiveRef, settings.always, running]) + + return { + count, stop, start, running, + } +} + +export default useInterval diff --git a/app/hooks/useIsBrowserTabActive.js b/app/hooks/useIsBrowserTabActive.js new file mode 100644 index 0000000..5011179 --- /dev/null +++ b/app/hooks/useIsBrowserTabActive.js @@ -0,0 +1,22 @@ +import { useEffect, useRef } from 'react' + +// Check if the tab is active in the user browser +const useIsBrowserTabActive = () => { + const isBrowserTabActiveRef = useRef(true) + + useEffect(() => { + const onVisibilityChange = () => { + isBrowserTabActiveRef.current = (document.visibilityState === 'visible') + } + + window.addEventListener('visibilitychange', onVisibilityChange) + + return () => { + window.removeEventListener('visibilitychange', onVisibilityChange) + } + }, []) + + return isBrowserTabActiveRef +} + +export default useIsBrowserTabActive diff --git a/app/hooks/useLoaded.js b/app/hooks/useLoaded.js new file mode 100644 index 0000000..0acb957 --- /dev/null +++ b/app/hooks/useLoaded.js @@ -0,0 +1,10 @@ +// https://stackoverflow.com/questions/55271855/react-material-ui-ssr-warning-prop-d-did-not-match-server-m-0-0-h-24-v-2/56525858 +import { useEffect, useState } from 'react' + +export const useLoaded = () => { + const [loaded, setLoaded] = useState(false) + useEffect(() => { + setLoaded(true) + }, []) + return loaded +} diff --git a/app/hooks/useMediaQuery.js b/app/hooks/useMediaQuery.js new file mode 100644 index 0000000..d2dc422 --- /dev/null +++ b/app/hooks/useMediaQuery.js @@ -0,0 +1,18 @@ +import { useEffect, useState } from 'react' + +const useMediaQuery = query => { + const [matches, setMatches] = useState(null) + useEffect(() => { + const mediaMatch = window.matchMedia(query) + if (matches === null) { + setMatches(mediaMatch.matches) + } + const handler = e => setMatches(e.matches) + mediaMatch.addEventListener('change', handler) + return () => mediaMatch.removeEventListener('change', handler) + }, [setMatches, matches, query]) + + return matches +} + +export default useMediaQuery diff --git a/app/hooks/useReCaptcha.js b/app/hooks/useReCaptcha.js new file mode 100644 index 0000000..2720b46 --- /dev/null +++ b/app/hooks/useReCaptcha.js @@ -0,0 +1,51 @@ +import { useEffect } from 'react' + +const SCRIPT_ELEMENT = 'recaptcha-script' +let SITE_KEY, ENABLED, URL + +if (typeof window !== 'undefined') { + SITE_KEY = window.ENV.RECAPTCHA_SITE_KEY + ENABLED = window.ENV.RECAPTCHA_ENABLED + // const URL = `https://www.google.com/recaptcha/api.js?render=${SITE_KEY}` + // recaptcha.net is in theory more accessible for Chinese users. + URL = `https://www.recaptcha.net/recaptcha/api.js?render=${SITE_KEY}` +} + +const defaultOptions = { action: 'default', callback: () => { } } +export const useReCaptcha = (options = defaultOptions) => { + useEffect(() => { + if (ENABLED === 'true') { + const element = document.getElementById(SCRIPT_ELEMENT) + if (!element) { + const script = document.createElement('script') + script.type = 'text/javascript' + script.id = SCRIPT_ELEMENT + script.onload = options.callback + // src must come after onload + script.src = URL + // const head = document.getElementsByTagName('head')[0] + // head.appendChild(script) + document.body.appendChild(script) + } else { + options.callback() + } + } else { + options.callback() + } + }, [options]) +} + +export const reCaptchaExecute = async action => { + return new Promise((resolve, reject) => { + if (ENABLED === 'true') { + window.grecaptcha.ready(() => { + window.grecaptcha.execute(SITE_KEY, { action }) + .then(token => { + resolve(token) + }, reject) + }) + } else { + resolve('') + } + }) +} diff --git a/app/lib.server.node.ts b/app/lib.server.node.ts new file mode 100644 index 0000000..cb7519a --- /dev/null +++ b/app/lib.server.node.ts @@ -0,0 +1,73 @@ + +import { request } from 'undici' + +export class AppError extends Error { + constructor(message: string) { + super(message) + Error.captureStackTrace(this, this.constructor) + } + + // Http status code to return if this error is not caught. + get status() { return 500 } + + // Application-specific error code to help clients identify this error. + get code() { return 'ERROR' } +} + +/** + * Error for reporting general filesystem errors. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +export class HTTP_REQUEST_ERROR extends AppError { + + get status() { return 500 } + + get code() { return 'HTTP_REQUEST_ERROR' } +} + +// eslint-disable-next-line @typescript-eslint/naming-convention +export class RECAPTCHA_VALIDATION_ERROR extends AppError { + get status() { return 400 } + + get code() { return 'RECAPTCA_VALIDATION_ERROR' } +} + +/** + * reCaptchaCheck - perform a server-side reCaptcha validation + * @param secretKey + * @param token + * @param score + * @param ip + * @param headers + * @returns + */ +export const reCaptchaCheck = async (secretKey: string, token: string, score = 0.5, ip = '0.0.0.0', headers = {}) => { + const VERIFY_URL = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${token}` + + try { + const { statusCode, body } = await request(VERIFY_URL, { method: 'POST' }) + + if (statusCode === 200) { + let result = await body.json() + if (result.success && result.score >= score) { + // TODO: Configure server-side logger + // eslint-disable-next-line no-console + console.info({ recaptcha_result: result, ip: ip, headers: headers }) + } else if (!result.success || result.score < score) { + // TODO: Configure server-side logger + // eslint-disable-next-line no-console + console.error({ recaptcha_result: result, ip: ip, headers: headers }) + throw new RECAPTCHA_VALIDATION_ERROR(`Recaptcha verification failed for ip: ${ip}`) + } + } else { + throw new RECAPTCHA_VALIDATION_ERROR(`Error in HTTP response reCaptchaCheck: ${statusCode}.`) + } + } catch (error) { + // TODO: Configure server-side logger + // eslint-disable-next-line no-console + console.log(error) + throw new HTTP_REQUEST_ERROR('Error in making reCaptcha request') + } + + return true +} diff --git a/app/models/note.server.ts b/app/models/note.server.ts new file mode 100644 index 0000000..ba3d10f --- /dev/null +++ b/app/models/note.server.ts @@ -0,0 +1,69 @@ +import { prisma } from '~/db.server' + +import type { User, Note } from '@prisma/client' + +export type { Note } from '@prisma/client' + +export function getNote({ + id, + userId, +}: Pick & { + userId: User['id']; +}) { + return prisma.note.findFirst({ + select: { id: true, title: true, body: true }, + where: { id, userId }, + }) +} + +export function getNoteListItems({ userId }: { userId: User['id'] }) { + return prisma.note.findMany({ + where: { userId }, + select: { id: true, title: true, body: true }, + orderBy: { updatedAt: 'desc' }, + }) +} + +export function createNote({ + title, + body, + userId, +}: Pick & { + userId: User['id']; +}) { + return prisma.note.create({ + data: { + title, + body, + user: { + connect: { + id: userId, + }, + }, + }, + }) +} + +export function editNote({ + id, + title, + body, + userId, +}: Pick & { userId: User['id'] }) { + return prisma.note.updateMany({ + where: { id, userId }, + data: { + title, + body, + }, + }) +} + +export function deleteNote({ + id, + userId, +}: Pick & { userId: User['id'] }) { + return prisma.note.deleteMany({ + where: { id, userId }, + }) +} diff --git a/app/models/user.server.ts b/app/models/user.server.ts new file mode 100644 index 0000000..c48a80d --- /dev/null +++ b/app/models/user.server.ts @@ -0,0 +1,165 @@ +import bcrypt from 'bcryptjs' +import { prisma } from '~/db.server' +import { SEARCH_PARAMS_DEFAULTS } from '~/models/user' + +import type { Password, User } from '@prisma/client' +import type { SearchParams } from '~/models/user' + +export type { User } from '@prisma/client' + +export async function verifyLogin( + email: User['email'], + password: Password['hash'] +) { + const userWithPassword = await prisma.user.findUnique({ + where: { email }, + include: { + password: true, + }, + }) + + if (!userWithPassword || !userWithPassword.password) { + return null + } + + const isValid = await bcrypt.compare( + password, + userWithPassword.password.hash + ) + + if (!isValid) { + return null + } + + // eslint-disable-next-line @typescript-eslint/naming-convention + const { password: _password, ...userWithoutPassword } = userWithPassword + + return userWithoutPassword +} + +export async function getUsers( + { + page = SEARCH_PARAMS_DEFAULTS.page, + pageSize = SEARCH_PARAMS_DEFAULTS.pageSize, + orderBy = SEARCH_PARAMS_DEFAULTS.orderBy, + orderDesc = SEARCH_PARAMS_DEFAULTS.orderDesc, + }: SearchParams +) { + const count = await prisma.user.count() + const meta = { + total: count, + pageSize: pageSize, + pageTotal: Math.ceil(count / pageSize), + currentPage: page, + } + + const users = await prisma.user.findMany({ + select: { id: true, email: true, createdAt: true }, + skip: (page - 1) * pageSize, + take: pageSize, + orderBy: { + [orderBy]: orderDesc ? 'desc' : 'asc', + }, + }) + + return { users, meta } +} + +export async function getUserById(id: User['id']) { + return prisma.user.findUnique({ where: { id } }) +} + +export async function getUserByEmail(email: User['email']) { + return prisma.user.findUnique({ where: { email } }) +} + +export async function getUserWithNotes(id: User['id']) { + return prisma.user.findUnique({ + where: { id }, include: { + notes: true, + }, + }) +} + +export async function createUser(email: User['email'], password: string) { + const hashedPassword = await bcrypt.hash(password, 10) + return prisma.user.create({ + data: { + email, + password: { + create: { + hash: hashedPassword, + }, + }, + }, + }) +} + +export async function updateUserEmail(id: User['id'], email: User['email']) { + + // Check for another user with this email address + const result = await prisma.user.findMany({ + where: { + email, + NOT: { + id: { + equals: id, + }, + }, + }, + select: { + email: true, + }, + }) + + if (result.length > 0) return null + + return prisma.user.update({ + where: { + id, + }, + data: { + email, + }, + }) +} + +export async function updateUserPassword(id: User['id'], currentPassword: string, newPassword: string) { + const hashedNewPassword = await bcrypt.hash(newPassword, 10) + const userWithPassword = await prisma.user.findUnique({ + where: { id }, + include: { + password: true, + }, + }) + + if (!userWithPassword || !userWithPassword.password) { + return null + } + + const isValid = await bcrypt.compare( + currentPassword, + userWithPassword.password.hash + ) + + if (!isValid) { + return null + } + + return prisma.user.update({ + where: { + id, + }, + data: { + password: { + update: { + hash: hashedNewPassword, + }, + }, + }, + }) +} + +export async function deleteUserByEmail(email: User['email']) { + return prisma.user.delete({ where: { email } }) +} diff --git a/app/models/user.ts b/app/models/user.ts new file mode 100644 index 0000000..668a8fb --- /dev/null +++ b/app/models/user.ts @@ -0,0 +1,13 @@ +export interface SearchParams { + page: number, + pageSize: number, + orderBy: string, + orderDesc: boolean +} + +export const SEARCH_PARAMS_DEFAULTS: SearchParams = { + page: 1, + pageSize: 10, + orderBy: 'createdAt', + orderDesc: true, +} diff --git a/app/modules/account/index.ts b/app/modules/account/index.ts new file mode 100644 index 0000000..ab2667d --- /dev/null +++ b/app/modules/account/index.ts @@ -0,0 +1,53 @@ +import { z } from 'zod' +import { zfd } from 'zod-form-data' + +export const emailSchema = zfd.formData({ + email: zfd.text( + z + .string({ + required_error: 'Email address is required.', + invalid_type_error: 'Email must be a string.', + }) + .email({ message: 'Please enter a valid email address.' }) + ), +}) + +export const passwordSchema = zfd.formData({ + currentPassword: zfd.text( + z + .string({ + required_error: 'Password is required.', + invalid_type_error: 'Password must be a string.', + }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Password cannot be empty.') + ), + password: zfd.text( + z + .string({ + required_error: 'Password is required.', + invalid_type_error: 'Password must be a string.', + }) + .min(8, { message: 'Password must be 8 or more characters long.' }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Password cannot be empty.') + ), + confirmPassword: zfd.text( + z + .string({ + required_error: 'Password is required.', + invalid_type_error: 'Password must be a string.', + }) + .min(8, { message: 'Password must be 8 or more characters long.' }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Password cannot be empty.') + ), +}).superRefine(({ confirmPassword, password }, ctx) => { + if (confirmPassword !== password) { + ctx.addIssue({ + code: 'custom', + message: 'Confirmed password does not match new password.', + path: ['confirmPassword'], + }) + } +}) \ No newline at end of file diff --git a/app/modules/admin/index.ts b/app/modules/admin/index.ts new file mode 100644 index 0000000..d72d67f --- /dev/null +++ b/app/modules/admin/index.ts @@ -0,0 +1,6 @@ + +import type { User } from '~/models/user.server' + +export interface UserProps { + user: User +} \ No newline at end of file diff --git a/app/modules/home/hero.css b/app/modules/home/hero.css new file mode 100644 index 0000000..6f11aba --- /dev/null +++ b/app/modules/home/hero.css @@ -0,0 +1,3 @@ +.foo { + background-color: blue; +} \ No newline at end of file diff --git a/app/modules/home/hero.tsx b/app/modules/home/hero.tsx new file mode 100644 index 0000000..d70c4ca --- /dev/null +++ b/app/modules/home/hero.tsx @@ -0,0 +1,89 @@ +import type { LinksFunction } from '@remix-run/node' +import { Link } from '@remix-run/react' + +import { useOptionalUser } from '~/utils' + +import { Button } from '~/ui/components/button' +import { Container } from '~/ui/components/container' +import { Section } from '~/ui/components/section' + +import styles from '~/styles/app/modules/home/hero.css' + +export const links: LinksFunction = () => { + return [{ rel: 'stylesheet', href: styles }] +} + +export function Hero() { + const user = useOptionalUser() + + return ( +
+ +
+ Sonic Youth On Stage +
+
+
+

+ Indie Stack +

+

+ Check the README.md file for instructions on how to get this + project deployed. +

+
+ {user + ? ( +
+ +
+ ) + : ( +
+ + +
+ )} +
+ + Remix + +
+ +
+ ) +} \ No newline at end of file diff --git a/app/modules/home/index.ts b/app/modules/home/index.ts new file mode 100644 index 0000000..47c9857 --- /dev/null +++ b/app/modules/home/index.ts @@ -0,0 +1 @@ +export * from './hero' \ No newline at end of file diff --git a/app/modules/notes/index.ts b/app/modules/notes/index.ts new file mode 100644 index 0000000..92424ed --- /dev/null +++ b/app/modules/notes/index.ts @@ -0,0 +1,54 @@ +import { z } from 'zod' +import { zfd } from 'zod-form-data' + +import type { Note } from '~/models/note.server' + +export interface NoteProps { + note: Note +} + +export const schema = zfd.formData({ + title: zfd.text( + z + .string({ + required_error: 'Title is required.', + invalid_type_error: 'Title must be a string.', + }) + .min(3, { message: 'Title must be 3 or more characters long.' }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Title cannot be empty.') + ), + body: zfd.text( + z + .string({ + required_error: 'Body is required.', + invalid_type_error: 'Body must be a string.', + }) + .min(15, { message: 'Body must be 15 or more characters long.' }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Body cannot be empty.') + ), +}) + +export const badSchema = zfd.formData({ + title: zfd.text( + z + .string({ + required_error: 'Title is required.', + invalid_type_error: 'Title must be a string.', + }) + .min(3, { message: 'Title must be 3 or more characters long.' }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Title cannot be empty.') + ), + body: zfd.text( + z + .string({ + required_error: 'Body is required.', + invalid_type_error: 'Body must be a string.', + }) + .min(5, { message: 'Body must be 5 or more characters long.' }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Body cannot be empty.') + ), +}) \ No newline at end of file diff --git a/app/modules/session/index.ts b/app/modules/session/index.ts new file mode 100644 index 0000000..c234219 --- /dev/null +++ b/app/modules/session/index.ts @@ -0,0 +1,44 @@ +import { z } from 'zod' +import { zfd } from 'zod-form-data' + +// During sign in we don't want to 'leak' password policy +// Email constraints would need to be updated if a user +// can sign in with a username or email +export const signInSchema = zfd.formData({ + email: zfd.text( + z + .string({ + required_error: 'Email address is required.', + invalid_type_error: 'Email must be a string.', + }) + .email({ message: 'Please enter a valid email address.' }) + ), + password: zfd.text( + z + .string({ + required_error: 'Password is required.', + invalid_type_error: 'Password must be a string.', + }) + ), +}) + +export const signUpSchema = zfd.formData({ + email: zfd.text( + z + .string({ + required_error: 'Email address is required.', + invalid_type_error: 'Email must be a string.', + }) + .email({ message: 'Please enter a valid email address.' }) + ), + password: zfd.text( + z + .string({ + required_error: 'Password is required.', + invalid_type_error: 'Password must be a string.', + }) + .min(8, { message: 'Password must be 8 or more characters long.' }) + .transform(s => s.trim()) + .refine(s => s.length > 0, 'Password cannot be empty.') + ), +}) \ No newline at end of file diff --git a/app/root.tsx b/app/root.tsx new file mode 100644 index 0000000..556911c --- /dev/null +++ b/app/root.tsx @@ -0,0 +1,219 @@ + +import type * as React from 'react' + +import type { LinksFunction, LoaderArgs, MetaFunction, LoaderFunction } from '@remix-run/node' +import { json } from '@remix-run/node' +import { useLoaderData } from '@remix-run/react' +import { + Links, + LiveReload, + Meta, + Outlet, + Scripts, + ScrollRestoration, + useCatch, +} from '@remix-run/react' + +import * as ToastPrimitive from '@radix-ui/react-toast' +import cx from 'classnames' + +import { getUser } from './session.server' +import { getThemeSession } from './theme.server' +import ErrorLayout from './ui/layouts/error-layout' + +import { NonFlashOfWrongThemeEls, ThemeProvider, useTheme } from '~/ui/theme/theme-provider' +import type { Theme } from '~/ui/theme/theme-provider' + +import appStyles from '~/styles/shared/css/app.css' +import tailwindStyles from '~/styles/shared/css/tailwind.css' + +import type { User } from '~/models/user.server' + +export type LoaderData = { + theme: Theme | null + user: User | null + ENV: object | null +} + +interface DocumentProps { + children: React.ReactNode + title?: string +} + +/** + * links + * @returns + */ +export const links: LinksFunction = () => { + return [ + { rel: 'stylesheet', href: tailwindStyles }, + { rel: 'stylesheet', href: appStyles }, + ] +} + +/** + * meta + * @returns + */ +export const meta: MetaFunction = () => ({ + title: 'Infonomic Remix Workbench App', +}) + +/** + * loader + * @param param0 + * @returns + */ +export const loader: LoaderFunction = async ({ request }: LoaderArgs) => { + const themeSession = await getThemeSession(request) + const user = await getUser(request) + + const data: LoaderData = { + theme: themeSession.getTheme(), + user: user, + ENV: { + RECAPTCHA_ENABLED: process.env.RECAPTCHA_ENABLED, + RECAPTCHA_SITE_KEY: process.env.RECAPTCHA_SITE_KEY, + }, + } + return json(data) +} + +const Document = ({ children, title }: DocumentProps) => { + const t = useTheme() + const data = useLoaderData() + + return ( + + + + + + + + + + + + + + + + + + + + {title ? {title} : null} + + + + + {children} + +