Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisnajman committed May 25, 2024
0 parents commit 4ead88d
Show file tree
Hide file tree
Showing 27 changed files with 3,761 additions and 0 deletions.
51 changes: 51 additions & 0 deletions .XXXgithub/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Deploy

on:
push:
branches:
- main

jobs:
build:
name: Build
runs-on: ubuntu-latest

steps:
- name: Checkout repo
uses: actions/checkout@v4 # Ensure this is v4 to support Node.js 20

- name: Setup Node
uses: actions/setup-node@v4 # v4 is correct for Node.js 20
with:
node-version: 20

- name: Install dependencies
run: npm install

- name: Build project
run: npm run build

- name: Upload production-ready build files
uses: actions/upload-artifact@v4 # Ensure this is v4
with:
name: production-files
path: ./dist # Reverted to ./dist

deploy:
name: Deploy
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'

steps:
- name: Download artifact
uses: actions/download-artifact@v4 # Ensure this is v4
with:
name: production-files
path: ./dist # Reverted to ./dist

- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v4 # Ensure this is v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./dist # Reverted to ./dist
28 changes: 28 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

# mine
ref/
*copy*
108 changes: 108 additions & 0 deletions App.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import React, { useState, useEffect } from "react"
import Layout from "./layout/Layout"
import Sidebar from "./components/Sidebar"
import Editor from "./components/Editor"
import Split from "react-split"
import { onSnapshot, addDoc, doc, deleteDoc, setDoc } from "firebase/firestore"
import { notesCollection, db } from "./firebase"

function App() {
const [notes, setNotes] = useState([])

const [currentNoteId, setCurrentNoteId] = useState("")

const [tempNoteText, setTempNoteText] = useState("")

const currentNote =
notes.find((note) => note.id === currentNoteId) || notes[0]

const sortedNotes = notes.sort((a, b) => b.updatedAt - a.updatedAt)

useEffect(() => {
const unsubscribe = onSnapshot(notesCollection, function (snapshot) {
// Sync local notes array with snapshot data (firestore)

const notesArr = snapshot.docs.map((doc) => ({
...doc.data(),
id: doc.id,
}))
setNotes(notesArr)
})
return unsubscribe
}, [])

useEffect(() => {
if (!currentNoteId) {
setCurrentNoteId(notes[0]?.id)
}
}, [notes])

useEffect(() => {
if (currentNote) {
setTempNoteText(currentNote.body)
}
}, [currentNote])

useEffect(() => {
const timeoutId = setTimeout(() => {
updateNote(tempNoteText)
}, 500)
return () => clearTimeout(timeoutId)
}, [tempNoteText])

async function createNewNote() {
const newNote = {
body: "# Type your markdown note's title here",
createdAt: Date.now(),
updatedAt: Date.now(),
}
const newNoteRef = await addDoc(notesCollection, newNote)
setCurrentNoteId(newNoteRef.id)
}

async function updateNote(text) {
const docRef = doc(db, "notes", currentNoteId)
await setDoc(docRef, { body: text, updatedAt: Date.now() }, { merge: true })
}

async function deleteNote(noteId) {
const docRef = doc(db, "notes", noteId)
await deleteDoc(docRef)
}

return (
<Layout>
{notes.length > 0 ? (
<Split
sizes={[30, 70]}
direction="horizontal"
className="split"
>
<Sidebar
notes={sortedNotes}
currentNote={currentNote}
setCurrentNoteId={setCurrentNoteId}
newNote={createNewNote}
deleteNote={deleteNote}
/>
<Editor
tempNoteText={tempNoteText}
setTempNoteText={setTempNoteText}
/>
</Split>
) : (
<div className="no-notes">
<h2>You have no notes</h2>
<button
className="first-note"
onClick={createNewNote}
>
Create one now
</button>
</div>
)}
</Layout>
)
}

export default App
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Christopher. Najman

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.
98 changes: 98 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Markdown Notes App (Firestore)

This is the result of the Scrimba Tutorial [Notes App (registration required)](https://v2.scrimba.com/learn-react-c0e), including the setting up of _Firebase / Firestore_.

Much of the code was pre-written. The task was to add functionality to an existing codebase.

## Functionality to Add

1. Sync notes with _Firestore_.
2. Create note titles from a summary of the note.
3. Move modified notes to the top of the list.
4. Delete notes.

---

### Firebase Config

You will need add your own config code to `firebase.js`.

> [!WARNING]
> If you do set up a _firestore_ database, then publish the app as a GitHub Page, anyone will be able to save notes to the database.
> If you decide to do this, make sure you rename the folder, `.XXXgithub` to `.github`.
### Alternative Version using `localstorage` to Save Notes

- [Markdown Notes App (Local Storage): Git Repository](https://github.com/chrisnajman/markdown-notes-app-localstorage)
- [Markdown Notes App (Local Storage): Git Page](https://chrisnajman.github.io/markdown-notes-app-localstorage/)

## React Version

> [!IMPORTANT]
> `react-mde` (the markdown editor) has not been updated for _React V.18_.
> Therefore, _React V.18_ has been used for this project.
---

## Accessibility

In the markdown editor, you can't tab through the toolbar buttons (apart from 'Write' and 'Preview').
This is because `tabindex="-1"` is placed on these buttons, removing them from the tab order.

_ChatGPT_ supplied a solution, which was to give ALL the buttons (including 'Write' and 'Preview') a `tabindex` of zero:

```jsx

function Editor({ currentNote, updateNote }) {

...

useEffect(() => {
// Function to update tabindex of toolbar buttons
const updateTabindex = () => {
const toolbarButtons = document.querySelectorAll(".mde-header button")
toolbarButtons.forEach((button) => {
button.setAttribute("tabindex", "0")
})
}

// Call the function initially after the component mounts
updateTabindex()

// Optional: observe changes to ensure tabindex stays updated
const observer = new MutationObserver(updateTabindex)
const toolbar = document.querySelector(".mde-header")

if (toolbar) {
observer.observe(toolbar, { childList: true, subtree: true })
}

// Cleanup the observer on component unmount
return () => {
observer.disconnect()
}
}, []) // Empty dependency array to run only once on mount

...
}
```

On reflection, however, I have decided **not** to include the code. This is because:

- In order to format the text, you first have to manually select it.
- Then you have to click a formatting button.
- But, if you reverse tab from the selected text to a toolbar button, the text selection disappears, so there is nothing for the button to format.

**Conclusion**: the toolbar formatting buttons are inherently inaccessible to keyboard navigation. (But you can still write and preview markdown code.)

---

## Testing

Tested on Windows 10 with:

- Chrome
- Firefox
- Microsoft Edge

Page tested in both browser and device views.
50 changes: 50 additions & 0 deletions components/BtnTheme.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React, { useState, useEffect } from "react"

function BtnTheme() {
function getStoredTheme() {
try {
const storedTheme = localStorage.getItem("theme")
return storedTheme ? JSON.parse(storedTheme) : false
} catch (error) {
console.error("Error parsing theme from localStorage:", error)
return false
}
}

const [theme, setTheme] = useState(getStoredTheme)

useEffect(() => {
document.documentElement.classList.toggle("lightmode", theme)
localStorage.setItem("theme", theme)
}, [theme])

function handleMode() {
setTheme((prevTheme) => !prevTheme)
}
return (
<div className="theme-toggler">
<p className="light">
Light
<span className="visually-hidden">
{theme ? " theme active" : " theme inactive"}
</span>
</p>
<button
type="button"
onClick={handleMode}
aria-pressed={theme ? "false" : "true"}
aria-label="Toggle theme"
>
<span></span>
</button>
<p className="dark">
Dark
<span className="visually-hidden">
{theme ? " theme inactive" : " theme active"}
</span>
</p>
</div>
)
}

export default BtnTheme
Loading

0 comments on commit 4ead88d

Please sign in to comment.