Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎉 V2 project init #3

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__DEV__="true"
30 changes: 30 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["react", "@typescript-eslint"],
"rules": {
"react/react-in-jsx-scope": "off"
},
"globals": {
"chrome": "readonly"
},
"ignorePatterns": ["watch.js", "dist/**"]
}
23 changes: 23 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Build And Test

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
cache: 'yarn'
- run: yarn install
- run: yarn build:hmr
- run: yarn test
- run: yarn build
16 changes: 16 additions & 0 deletions .github/workflows/greetings.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: Greetings

on: [pull_request_target, issues]

jobs:
greeting:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/first-interaction@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message: 'Thank you for your contribution. We will check and reply to you as soon as possible.'
pr-message: 'Thank you for your contribution. We will check and reply to you as soon as possible.'
18 changes: 17 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,17 @@
.env
# dependencies
/node_modules

# testing
/coverage

# build
/dist

# etc
.DS_Store
.env.local
.idea

# compiled
utils/reload/*.js
utils/reload/injections/*.js
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
18.12.0
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"singleQuote": false,
"trailingComma": "es5",
"arrowParens": "always"
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2022 Seo Jong Hak

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.
161 changes: 53 additions & 108 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,127 +1,72 @@
<h2 align="center">DJ Grauchi Chrome Extension</h2>
<div align="center">
<img src="v1/icon128.png" alt="logo"/>
<h1> Grauchi Chrome Ext V2</h1>

### The Problem
All mixes under ```The Good Company``` youtube channel are not well named. There is no way to tell whether a video is a HipHop/Afrobeats/Reggae/Pop mix. All you can do is start listening and cross your fingers and hope you'll like it.
![](https://img.shields.io/badge/React-61DAFB?style=flat-square&logo=react&logoColor=black)
![](https://img.shields.io/badge/Typescript-3178C6?style=flat-square&logo=typescript&logoColor=white)
![](https://badges.aleen42.com/src/vitejs.svg)

> This project is bootstrapped with the template [Chrome Ext Biolerplate](https://github.com/Jonghakseo/chrome-extension-boilerplate-react-vite) by [Jonghakseo](https://github.com/Jonghakseo)

### The Solution
A chrome extension that renames all of the mixes appropriately. This way, if you are in the mood for some Amapiano, you don't have to go through 7 videos just to find the perfect one.
</div>

### How the solution works
Simple, sort of. I know you must be wondering, "Who is renaming the titles?", good question. I am the one renaming the titles (as of the first solution). The way it works is, When you click on a video, I make sure it is a video under "The Good Company", then I get the video-ID(watch id) that uniquely identifies a YT video. I then use this ID to get all the comments for that video, find my comment from the list and then set my comment as the video title.
## Table of Contents

[log 1] Getting my (Steve Kibuika's) comment was easy and it worked very well. But I needed a solution that could be easily adopted by other users.
- [Intro](#intro)
- [Features](#features)
- [Installation](#installation)
- [Procedures](#procedures)
- [Screenshots](#screenshots)
- [Popup](#popup)
- [Documents](#documents)

Solution: Fetch the current user's username then use that username to get the user's comment and use that as the title.
This sounds good and it made sense. But it came with a new problem. I could not access the cuurent user's username since the username exists in a popup.
The issue was that, popups do not exist in the DOM unless they are clicked (opened). So I had to hack a solution that would add the popup to the DOM by clicking it to open and then clicking it to close.
## Intro <a name="intro"></a>


document.querySelector("ytd-popup-container").style['display'] = "none"; // hides the popup
document.getElementById("avatar-btn")?.click() // clicks the avatar to open the pop up, this way it will be added to the DOM without being visible
document.getElementById("avatar-btn")?.click()
userName = document.querySelector("#account-name")?.innerText
document.querySelector("ytd-popup-container").style['display'] = "block";

This boilerplate is made for creating chrome extensions using React and Typescript.

This block of code helped me achieve this effect.
> The focus was on improving the build speed and development experience with Vite.

- Clicks the popup twice to show and hide and then from there I can access the username.
## Features <a name="features"></a>

It worked!!
- [React 18](https://reactjs.org/)
- [TypeScript](https://www.typescriptlang.org/)
- [Jest](https://jestjs.io/)
- [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/)
- [Vite](https://vitejs.dev/)
- [SASS](https://sass-lang.com/)
- [ESLint](https://eslint.org/)
- [Prettier](https://prettier.io/)
- [Chrome Extension Manifest Version 3](https://developer.chrome.com/docs/extensions/mv3/intro/)
- HMR(incomplete)
- [Refresh PR](https://github.com/Jonghakseo/chrome-extension-boilerplate-react-vite/pull/25)

### Bottlenecks
## Installation <a name="installation"></a>

- The main idea is to rename Grauchi's mixes so you don't have to click a video. This means, I need to design a script that will run on the main youtube page and not just when a video is clicked. I have not put much thought into this, I am hoping to get one of those ```eureka``` moments.

[update] - I learn't of Mutation Observer that would listen to DOM mutations and run a script that would find The Good Company KE's videos, fetch comments, look for the user's comment and update it to the title
### Procedures <a name="procedures"></a>

The Mutation Observer keeps track of changes in the DOM. In this case, the change we want to keep track of is the list of "child nodes" (video items) that are in the DOM. Ideally, when you are scrolling down, the number of child nodes is increasing and it is important to keep track of that. This way, when new nodes (video items) are added to the DOM, we can check for ```The Good Company KE```'s videos and find the title we want to replace the title with.
1. Clone this repository.
2. Change `name` and `description` in package.json => **Auto synchronize with manifest**
3. Run `yarn install` or `npm i` (check your node version >= 16.6, recommended >= 18)
4. Run `yarn dev` or `npm run dev`
5. Load Extension on Chrome
1. Open - Chrome browser
2. Access - chrome://extensions
3. Check - Developer mode
4. Find - Load unpacked extension
5. Select - `dist` folder in this project (after dev or build)
6. If you want to build in production, Just run `yarn build` or `npm run build`.

This was the most fascinating thing in this project. It was a very spot-on solution that put everything together and allowed things to work in a way I would not have anticipated.
## Screenshots <a name="screenshots"></a>

I even wrote about it in my blog - [MutationObserver saved my weekend build](https://kibuika.com/posts/Mutation-Observer)
### Popup <a name="popup"></a>

<img width="314" alt="popup" src="https://user-images.githubusercontent.com/53500778/203561728-23517d46-12e3-4139-8a4f-e0b2f22a6ab3.png">

## Documents <a name="documents"></a>

### The atomics of Chrome extensions
Chrome extensions rely on the ```manifest.json``` file. This is essentially what tells the extension which pages to work on and which scripts to run.
```js
{
"manifest_version": 3,
"name": "DJ Grauchi",
"version": "1.0.0",
"description": "An extension that renames The Good Company KE's mixes according to the comments you add to the videos.",
"content_scripts": [
{
"matches": ["https://www.youtube.com/*"],
"js": ["js/content.js"],
"all_frames": true,
"run_at": "document_idle"
},
{
"matches": ["https://www.youtube.com/watch*"],
"js": ["js/innerContent.js"],
"all_frames": true,
"run_at": "document_end"
}
],
"icons": {
"16": "icon16.png",
"32": "icon32.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
```
```content_scripts``` is where everything lies. ```matches``` defines the urls in which the extension will run on, in this case, it only works on Youtube. ```js``` points to the script to be executed. ```manifest_version``` has to be ```3``` if you are working with the latest chrome versions.
- [Vite Plugin](https://vitejs.dev/guide/api-plugin.html)
- [ChromeExtension](https://developer.chrome.com/docs/extensions/mv3/)
- [Rollup](https://rollupjs.org/guide/en/)
- [Rollup-plugin-chrome-extension](https://www.extend-chrome.dev/rollup-plugin)


```js/content.js``` is the main script. Here, the only thing you'll need is a ```Google API``` with ```Youtube Data API``` enabled.

```js/content.js``` runs on the Youtube homepage while ```js/innerContent.js``` runs on the inner Youtube video page (this script is however not properly loading at the moment, if you can, please create a PR 😄)

The ```run_at``` property defines when the script is executed. Ideally, we want our scripts to be executed when the page document has loaded. However, since we are making use of [Mutation Observers](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver), it doesn't matter much when our script is executed.

You can learn more about ```content_scripts``` [here](https://developer.chrome.com/docs/extensions/mv3/content_scripts/)

### Running the project

Once you've cloned the project, get a Google API with ```Youtube Data API``` enabled and replace it on the url requests. To run it on the browser, open ```manage extensions``` on chrome, make sure Developer mode is on, click on ```Load Unpacked``` and upload the whole project directory. Open Youtube and viola!!! It should work.


To learn more about developing Chrome Extensions, read their very good docs [here](https://developer.chrome.com/docs/extensions/mv3/)


#### Fancy optional things

I find it fun to add "cute" features to my code, simply because I want to enjoy reading the code.
For this project, the cute feature was ```useState```.

This is a "hook" in React that provides a state value (state being a snapshot of data at a particular moment) and a setter function which is used to update the state.

Here, I decided to use this concept to store the username, this way, instead of having a variable that may need to be mutated in the course of the script execution, I can just access the username from the state value and update it using the setter function.

```js
function useState(initialState) {
let _val = initialState;
const state = () => _val;
const setState = newVal => {
_val = newVal;
};
return [state, setState];
}
```

This is how I wrote that useState function. It is not exactly how it is in React but this is a much simpler way to write it especially when you only want to keep track of a single state value. It uses the concept of ```closures``` to keep a reference to the value.

A couple of things to note:

- The returned methods are a getter(state) and a setter(setState)
- This will only work with a single state value, for multiple values, you need to make use of arrays and indexes
- This problem could have been better solved by the Storage API in chrome (a possible PR)




In case you need me, dm me on [twitter](https://twitter.com/the_kibuika) or email me ```[email protected]```
---
Loading