Skip to content

Instantly share code, notes, and snippets.

@sun-sreng
Last active April 11, 2024 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sun-sreng/8337f8ad34c0db61f26f49f961e43b54 to your computer and use it in GitHub Desktop.
Save sun-sreng/8337f8ad34c0db61f26f49f961e43b54 to your computer and use it in GitHub Desktop.
docs

biome

bunx @biomejs/biome init
// package.json
{
  "format": "bunx @biomejs/biome format ./src --write",
  "lint": "bunx @biomejs/biome lint ./src",
  "check": "bunx @biomejs/biome check --apply ./src"
}
biome.json
{
	"$schema": "https://biomejs.dev/schemas/1.6.0/schema.json",
	"organizeImports": {
		"enabled": true
	},
	"linter": {
		"enabled": true,
		"rules": {
			"recommended": true
		}
	},
	"formatter": {
		"lineWidth": 180
	}
}
{
  "$schema": "../packages/@biomejs/biome/configuration_schema.json",
  "linter": {
    "enabled": true,
    "rules": {
      "recommended": true,
      "style": {
        "noNonNullAssertion": "off"
      }
    }
  },
  "organizeImports": {
    "enabled": true
  },
  "files": {
    "ignore": ["dist/**", ".astro/**", "assets/**", "public/**", "**/__snapshots__", "**/undefined/**", "_fonts/**"]
  },
  "formatter": {
    "ignore": ["configuration-schema.json"]
  }
}

awesome-shadcn/ui

A curated list of awesome things related to shadcn/ui

Awesome

Table of contents

Community

Libs and components:

  • auto-form - A React component that automatically creates a shadcn/ui form based on a zod schema.
  • date-range-picker-for-shadcn - Includes multi-month views, text entry, preset ranges, responsive design and date range comparisons.
  • enhanced-button - Easily expand the regular shadcn/ui-button component with new button styles, without the need of creating new additional button components.
  • fancy-multi-select - The Multi Select Component is inspired by campsite.design's and cal.com's settings forms.
  • shadcn-expansions - A shadcn/ui expansions collect lots of useful components which shadcn/ui does not have out of box. All the components are base on shadcn/ui. Just copy and paste. The component is yours.
  • shadcn-phone-input - Customizable phone input component with proper validation for any country.
  • shadcn-table-v2 - A shadcn/ui table component with server-side sorting, filtering, and pagination.
  • shadcn-tag-input - A tag input component built with shadcn/ui.
  • react-dnd-kit-tailwind-shadcn-ui - Drag and drop Accessible kanban board implementing using React, @dnd-kit, tailwind and shadcn/ui.
  • shadcn-chat - Customizable and re-usable chat component for you to use in your projects.
  • otp

Apps

  • shadcn-ui-theme-explorer - A theme explorer for shadcn UI.
  • thr - A clone of Meta's new app using Next.js server components, Vercel Postgres, shadcn UI, Clerk, and Prisma.
  • motion-variants - A collection of handmade Framer Motion variants made for your next project.
  • memomate-notetaker - An app for easy management of notes and topics.
  • gradient-picker - Fancy Gradient Picker, built with Shadcn UI, Radix UI and Tailwind CSS.
  • open-status - The open-source status page.
  • scribbly - Scribbly is a web application built with Next.js and Prisma that allows users to create and manage their digital journal.

Ports

  • svelte - Svelte port of shadcn/ui.
  • vue - Vue port of shadcn/ui.
  • react-native - React Native port of shadcn/ui.
  • swift - Swift port of shadcn/ui.
  • flutter - Flutter port of shadcn/ui.
  • ruby - Ruby port of shadcn/ui.
  • kotlin - Kotlin port of shadcn/ui.

Boilerplates

example

text editor

react-testing

portfolio

Contributing

Discover something fantastic, like a package, article, blog, video, or any other valuable resource? Feel free to contribute by sending a pull request! Simply adhere to our guidelines. Your participation is highly appreciated. Thank you! ❤️

Colors

Contributors

Thanks goes to all these wonderful people:

components

name tags description
shadcn-table shadcn table
shadcn-tag-input shadcn tag input
plate shadcn editor The rich-text editor for React.
gradient-picker shadcn gradient-picker Fancy Gradient Picker built with Shadcn UI, Radix UI and Tailwind CSS.
auto-form shadcn gradient-picker automatically creates a @shadcn/ui form based on a zod schema.
credenza shadcn responsive modal responsive modal
mxkaske.dev shadcn multiselect multiselect
enhanced-button shadcn button button
date-picker shadcn date picker date range picker
shadcn-chat shadcn chat
shadcn-ui-customizer shadcn ui customizer
next-s3-upload next s3 upload
armandsalle/my-site shadcn phone input
matheins/Dorf shadcn form input A free and open source form builder
next.js-drizzle-turso example next drizzle turso
NextAuthTutorial-Video example next next-auth
next-auth-v5-advanced-guide example next next-auth
shadcn-extension shadcn next

docker-nextjs

How to Deploy Next.js Applications with Docker

nextjs

docker

devops Next.js is the modern open source React.js framework officially support by the React team and Vercel. Most developers choose to deploy Next.js through Vercel, but a standalone export option is available for other platforms. Docker is the industry standard for developing, testing, and shipping production software. It's more lightweight than a virtual machine and portable across cloud vendors like AWS, Digital Ocean, Azure, Vercel, Netlify, and much more.

Step 1: Preparation Add the following snippet to your next.config.js file to enable standalone output for Docker.

// next.config.js
module.exports = {
  // ... rest of the configuration.
  output: 'standalone',
};

Test your application as it would be in production using next build and running node server.js in .next/standalone/. This way we can catch any errors before moving our code into a production environment.

Install Docker on your development system.

Step 2: Adding the Dockerfile Create a Dockerfile file at the root of your Next.js application and copy the following code.

Note that if you're using Windows, pnpm won't work properly, because Docker will try to use symlinks in your node_modules folder, so I recommend using Yarn or NPM.

FROM node:18-alpine AS base

Install dependencies only when needed

FROM base AS deps

RUN apk add --no-cache libc6-compat
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi


# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN \
  if [ -f yarn.lock ]; then yarn run build; \
  elif [ -f package-lock.json ]; then npm run build; \
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \
  else echo "Lockfile not found." && exit 1; \
  fi

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public

# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown nextjs:nodejs .next

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"

# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
CMD ["node", "server.js"]

This Dockerfile script will run several stages and cache them appropriately to reduce image build times. FROM base AS deps install your dependencies using whichever package manager's lockfile you've used during development, FROM base AS builder copies your node_modules and builds the application, FROM base as runner will execute on the end server and run your app. You can find an example project here.

Step 3: Building and Testing the Docker Image Now run docker build -t {image-name} . and don't forget the .!

Before you deploy, it's important to test your docker image with the correct environment variables. Run docker run -p 3000:3000 {image-name} to test your application at localhost:3000. If you want to test on a different port, use docker run -p {port}:3000 {image-name}.

If you're deploying to Digital Ocean, your image name will look like registry.digitalocean.com/your-registry/name. See their docker registry documentation for more details.

If you have any questions, comments, or concerns, feel free to comment them!

config

npm install --save-dev --save-exact prettier
node --eval "fs.writeFileSync('.prettierrc','{}\n')"
node --eval "fs.writeFileSync('.prettierignore','{}\n')"
bun i -d prettier
node --eval "fs.writeFileSync('.prettierrc','{}\n')"
node --eval "fs.writeFileSync('.prettierignore','{}\n')"

bun prettier . --write

bun i -d husky lint-staged
bunx husky init
node --eval "fs.writeFileSync('.husky/pre-commit','bunx lint-staged\n')"

npm-workspace

Step 1: Set up a Project

Create a new directory for your project and navigate into it:

mkdir workspace-npm
cd workspace-npm

npm init -w ./packages/a -y
echo "module.exports = 'a';" >> ./packages/a/index.js

npm init -w ./packages/b -y
echo "module.exports = 'b';" >> ./packages/a/index.js

npm init -w ./packages/c -y
npm i ./packages/b --workspace=c
echo "module.exports = 'c'; const moduleA = require('a'); console.log(moduleA);" >> ./packages/a/index.js

npm start --workspace=c

Reference: npm workspaces

Progressive Web App (PWA)

A Progressive Web App (PWA) is a web app that uses progressive enhancement to provide users with a more reliable experience, uses new capabilities to provide a more integrated experience, and can be installed. And, because it's a web app, it can reach anyone, anywhere, on any device, all with a single codebase. Once installed, a PWA looks like any other app, specifically:

It has an icon on the home screen, app launcher, launchpad, or start menu. It appears when you search for apps on the device. It opens in a standalone window, wholly separated from a browser's user interface. It has access to higher levels of integration with the OS, for example, URL handling or title bar customization. It works offline.

What is a PWA?

A Progressive Web App (PWA) is basically just a website with some added features, which enable it to provide an app-like user-experience.

This means it can work practically just like a native iOS or Android app. It can be installed to the home screen of your mobile device, work offline and receive push notifications, among other things.

A well-designed PWA is indistinguishable from a native app, but it also offers some strong added benefits:

  • It's just a website! You don't need to build separate apps anymore. If you have a website, you can easily turn it into and iOS and Android app as well!
  • A PWA is much smaller than a native app. Your users no longer need to install tens of megabytes of code
  • No need to get your app into the App Store or Play Store. Just share the link to your website and users can install it as an app
  • There's no need to get users to install updates anymore. When you release a new version of your app, all your users automatically get the new version
  • By default, PWAs are served over HTTPS and are therefore safe and secure
  • PWAs are lightweight and offer high performance
  • Especially on Android, a PWA can almost do anything a native app can

Reference:

Why Use PWA?

1. Cross-Platform Compatibility

PWAs work seamlessly across different platforms and devices, reducing the need to develop and maintain separate applications for each operating system.

Reference: Google Developers - Progressive Web Apps

2. Cost-Effectiveness

Developing a single PWA that works on multiple platforms can be more cost-effective than building and maintaining separate native apps for each platform.

Reference: Forbes - Why Progressive Web Apps Are The Future Of Web Development

3. Offline Functionality

PWAs can function offline or in areas with limited connectivity, thanks to service workers that cache resources.

Reference: MDN Web Docs - Service Worker API

4. Improved Performance

PWAs often have faster load times and better performance, providing a smoother user experience.

Reference: Google Developers - Performance Best Practices

5. App-Like Experience

PWAs offer an app-like experience with features such as smooth animations, gestures, and transitions, enhancing user engagement.

Reference: Web.dev - App-like

6. Discoverability

PWAs can be discovered through search engines, increasing accessibility for users who may not use traditional app stores.

Reference: Google Developers - SEO Basics for Web Developers

7. Security

PWAs require HTTPS, ensuring secure data transmission and protecting user information.

Reference: Mozilla Developer Network - Web Security

8. Push Notifications

PWAs can utilize push notifications to re-engage users, even when the app is not actively in use.

Reference: Web.dev - Push Notifications

9. App Store Independence

PWAs can be accessed directly through a URL, reducing dependence on app store policies and approval processes.

Reference: Smashing Magazine - PWAs: What Are They And How Do They Work?

10. Easy Updates

PWAs can be updated seamlessly without requiring users to manually update through app stores.

Reference: Google Developers - Update on the Web

Using PWA

1. Create a Web App

Start by developing a web application using standard web technologies (HTML, CSS, and JavaScript). Ensure that your application is responsive and functions well on various devices.

2. Make Your App Progressive

Implement progressive enhancement to ensure that the basic functionality of your web app is accessible to all users, and enhance it for users with modern browsers.

3. Implement Service Workers

Service workers are a crucial component for PWAs, enabling features like offline functionality and push notifications. Implement service workers to manage network requests and caching.

4. Ensure HTTPS

PWAs require a secure connection to ensure the safety of user data. Host your web app over HTTPS to meet security requirements.

5. Create a Web App Manifest

The web app manifest is a JSON file that provides information about your PWA, such as its name, icons, and display preferences. Include this file in your project to enhance the app-like experience.

6. Responsive Design

Ensure that your PWA is designed responsively to provide a seamless user experience across a variety of devices and screen sizes.

7. Testing

Thoroughly test your PWA on different browsers and devices to ensure consistent performance. Test offline functionality and push notifications as well.

8. Register a Service Worker

Register your service worker in your web app. This is typically done in your main JavaScript file using a script tag.

<script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker
      .register('/service-worker.js')
      .then((registration) => {
        console.log('Service Worker registered with scope:', registration.scope);
      })
      .catch((error) => {
        console.error('Service Worker registration failed:', error);
      });
  }
</script>

Security Concerns for PWA

Basically it's web so security is the same too.

1. HTTPS

  • Concern: Lack of HTTPS can expose sensitive data to potential attackers.
  • Mitigation: Ensure your PWA is served over HTTPS to encrypt data in transit.

Reference: MDN Web Docs - Securing your site with HTTPS

2. Service Worker Security

  • Concern: Insecure service worker implementations can be exploited for malicious purposes.
  • Mitigation: Implement and maintain service workers securely, and validate inputs to prevent attacks.

Reference: Google Developers - Service Worker API

3. Content Security Policy (CSP)

  • Concern: Inadequate CSP settings can leave your PWA vulnerable to cross-site scripting (XSS) attacks.
  • Mitigation: Configure a Content Security Policy to restrict the sources of content and mitigate XSS risks.

Reference: Mozilla Developer Network - Content Security Policy (CSP)

4. Data Storage Security

  • Concern: Insecure storage mechanisms (e.g., local storage, IndexedDB) can expose sensitive information.
  • Mitigation: Encrypt sensitive data, validate user inputs, and implement secure storage practices.

Reference: OWASP - Web Storage

5. User Authentication and Authorization

  • Concern: Weak authentication mechanisms can lead to unauthorized access.
  • Mitigation: Implement strong authentication practices, including secure password storage, and use authorization controls to limit access.

Reference: OWASP - Authentication Cheat Sheet

6. Cross-Origin Resource Sharing (CORS)

  • Concern: Incorrect CORS settings can result in unauthorized cross-origin requests.
  • Mitigation: Configure CORS settings appropriately to prevent unauthorized cross-origin requests.

Reference: MDN Web Docs - Cross-Origin Resource Sharing (CORS)

7. Push Notification Security

  • Concern: Insecure handling of push notifications can lead to abuse or unauthorized access.
  • Mitigation: Implement secure authentication and authorization mechanisms for push notifications.

Reference: Google Developers - Push Notifications

8. Offline Data Security

  • Concern: Insecure offline data storage can expose sensitive information.
  • Mitigation: Securely encrypt offline data and implement access controls to protect stored data.

Reference: OWASP - Data at Rest

9. App Shell Security

  • Concern: Insecure app shell architecture may lead to vulnerabilities in the core structure.
  • Mitigation: Implement and maintain a secure app shell to protect against potential security threats.

Reference: Google Developers - App Shell Model

10. Vulnerability Management

  • Concern: Failure to regularly update and patch underlying frameworks, libraries, and dependencies can result in security vulnerabilities.
  • Mitigation: Stay informed about security updates and promptly apply patches to address vulnerabilities.

Reference: OWASP - Patch Management

Conclusion

Always prioritize security in your PWA development. Regular security audits, testing, and staying informed about best practices are crucial to mitigating potential risks.

Benefit for Business

  • No middleman involved in the app download and installation.
  • Independence in the app update process.
  • An undisturbed digital journey even with weak or nonexistent connectivity.
  • A short loading time even in traffic peaks.
  • Higher user engagement and conversion rates.
  • Support in search results thanks to the mobile-first approach.
  • Seamless onboarding from social channels.
  • Higher marketing Return on Investment.
  • Decreased customer acquisition cost.
  • Increased cross-platform conversion.
  • All-in-one processes of development, updates, and product information.

Reference: https://www.divante.com/reports/pwabook/benefits-of-progressive-web-apps

Benefit for User

  • Fast
  • Installable
  • Reliable
  • Engaging

Reference: https://web.dev/articles/drive-business-success

Features

  • Media capture: Media capture allows web apps to use the camera and microphone of a device
  • Geolocation: The Geolocation API enables users to share their location with a web app. Below you will see your current location on a Google Map.
  • Notifications: The Push API and Notifications API enable web apps to receive and display push notifications from a server, even when the app is in the background or not running at all.
  • Contact picker: The Contact Picker API allows apps to select the user's contacts after permission has been granted.
  • Web share: The Web Share API invokes the native share mechanism of the device and allows users to share text, URLs or files.
  • Web Authentication: Web Authentication API (WebAuthn) enables passwordless authentication through iOS FaceID, your device's fingerprint reader or an external USB Security Key.
  • File System Access API: The File System Access API allows apps to access the native file system of a user's device after permission has been granted. The Origin Private File System is an origin-specific virtual filesystem that is highly optimized for performance.
  • Barcode and QR code reader: The Barcode Detection API detects barcodes and QR codes in images
  • Face detection: The Shape Detection API detects faces and in some browsers also features like eyes, mouth, and nose.
  • Vibration: The Vibration API enables web apps to make a mobile device vibrate.
  • Audio recording: This demo captures audio through the device's microphone and enables recording using the MediaRecorder API.
  • Audio: The Media Session API allows an app to display controls for media playback on a device's lock screen.
  • Background Sync API: The Background Sync API enables an app to defer tasks when it's offline so they can be run when the network connection is restored.
  • Background Fetch API: The Background Fetch API enables an app to download large files in the background even when the app is not running. It pauses the downloads when the app is offline and continues to download when the app is back online.
  • Capture handle: Capture Handle enables screen capturing web apps to reliably identify the captured web app if it has opted-in, enabling better collaboration like remote control for example. A great use-case for this is a screen capture web app that can remotely control a presentation inside the web app that is captured.
  • Storage API: The Storage API enables web apps to store structured data in IndexedDB, Cache Storage, LocalStorage, and SessionStorage. The available and used storage space can be obtained through await navigator.storage.estimate() which returns a Promise that resolves to the quota and usage properties that return the available and used storage space respectively.
  • Web Bluetooth API: The Web Bluetooth API enables apps to connect to Bluetooth Low Energy (BLE) devices and read values from or write values to it.
  • Web NFC: The Web NFC API enables web apps to read and write to NFC tags when they are in close proximity to the device, usually 5-10 cm or 2-4 inches support list.
  • Augmented reality: Augmented reality enables apps to place virtual objects in reality. On a supporting device, tap the image below, after which the camera will open and place the robot in the view.
  • Payment: The Payment Request API provides a browser-based method to enable users to make payments on the web, using a credit card, Apple Pay or Google Pay for example.
  • Screen Wake Lock: The Screen Wake Lock API enables web apps to prevent devices from dimming or locking the screen when the app needs to keep running.
  • Sensors: The DeviceOrientationEvent gives information about the physical orientation of the user's device.
  • Device motion: The DeviceMotionEvent gives information about the speed of changes for the position and orientation of the user's device.
  • Network information: The NetworkInformation API provides information about the connection of a device, allowing web apps to adapt functionality based on network quality.
  • Speech synthesis: Speech synthesis provides text-to-speech and allows apps to read out their text content.
  • Speech recognition: Speech recognition is part of the Web Speech API and provides the ability to recognize voice context from an audio input.
  • Multi touch: On a device with touch screen, place two fingers in the square below to see a red circle appear. Move your fingers to change the size and position of the circle.

Reference: https://whatpwacando.today/

Reference:

xcode

  xcode-select -s /Applications/Xcode.app
  xcodebuild -runFirstLaunch
  xcrun simctl runtime add "~/Downloads/iOS_17.4_Simulator_Runtime.dmg"
  # Tip
  # To learn more about additional runtime management features, run xcrun simctl runtime.
  # To download and install all the platforms that the Xcode version you selected supports, use the -downloadAllPlatforms option on xcodebuild.
  xcodebuild -downloadAllPlatforms
  # To download and install Simulator runtimes for a specific platform, use the -downloadPlatform option and specify the platform.
  xcodebuild -downloadPlatform iOS

-reference: download

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment