Add Forgejo-backed editor
This commit is contained in:
parent
59b5807601
commit
3d95b867c0
6 changed files with 976 additions and 1 deletions
317
quartz/components/Editor.tsx
Normal file
317
quartz/components/Editor.tsx
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types";
|
||||
import editorScript from "./scripts/editor.inline";
|
||||
import path from "path";
|
||||
|
||||
const Editor: QuartzComponent = ({ fileData, allFiles, displayClass }: QuartzComponentProps) => {
|
||||
if (!fileData.filePath) return null;
|
||||
|
||||
const dIndex = process.argv.findIndex(arg => arg === "-d" || arg === "--directory");
|
||||
const baseDir = dIndex !== -1 ? process.argv[dIndex + 1] : "content";
|
||||
|
||||
const absoluteBase = path.resolve(process.cwd(), baseDir);
|
||||
const absoluteFile = path.resolve(process.cwd(), fileData.filePath);
|
||||
const repoFilePath = path.relative(absoluteBase, absoluteFile);
|
||||
|
||||
const directories = new Set<string>();
|
||||
for (const file of allFiles) {
|
||||
if (file.slug) {
|
||||
const parts = file.slug.split("/");
|
||||
if (parts.length > 1) {
|
||||
parts.pop();
|
||||
directories.add(parts.join("/"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div class={`editor-container ${displayClass ?? ""}`}>
|
||||
|
||||
<div id="fab-container">
|
||||
<button id="new-button" class="fab" aria-label="New Note" title="New Note">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
|
||||
<polyline points="14 2 14 8 20 8"></polyline>
|
||||
<line x1="12" y1="18" x2="12" y2="12"></line>
|
||||
<line x1="9" y1="15" x2="15" y2="15"></line>
|
||||
</svg>
|
||||
</button>
|
||||
<button id="edit-button" class="fab" data-filepath={repoFilePath} aria-label="Edit Note" title="Edit Note">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
|
||||
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="editor-layout" style="display: none;">
|
||||
<div id="file-path-controls">
|
||||
<div class="input-group">
|
||||
<label for="file-directory">Directory</label>
|
||||
<input type="text" id="file-directory" placeholder="e.g. thoughts/daily" list="folder-list" />
|
||||
<datalist id="folder-list">
|
||||
{Array.from(directories).sort().map(dir => (
|
||||
<option value={dir}></option>
|
||||
))}
|
||||
</datalist>
|
||||
</div>
|
||||
<div class="input-group">
|
||||
<label for="file-name">Note Name</label>
|
||||
<input type="text" id="file-name" placeholder="e.g. My Idea" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="editor-wrapper"></div>
|
||||
<div id="editor-controls">
|
||||
<input type="text" id="commit-subject" placeholder="Commit message..." maxlength={72} />
|
||||
<details id="commit-details">
|
||||
<summary>Add extended description...</summary>
|
||||
<textarea id="commit-body" rows={4} placeholder="Extended description..."></textarea>
|
||||
</details>
|
||||
<div class="editor-buttons">
|
||||
<button id="delete-button">Delete Note</button>
|
||||
<div class="editor-buttons-right">
|
||||
<button id="cancel-button">Cancel</button>
|
||||
<button id="save-button">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Editor.afterDOMLoaded = editorScript;
|
||||
Editor.css = `
|
||||
#fab-container {
|
||||
position: fixed;
|
||||
bottom: 2rem;
|
||||
right: 2rem;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 1rem;
|
||||
z-index: 999;
|
||||
}
|
||||
|
||||
.fab {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
border-radius: 50%;
|
||||
background: var(--secondary);
|
||||
color: var(--light);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: transform 0.2s ease, background-color 0.2s ease;
|
||||
}
|
||||
|
||||
.fab:hover:not(:disabled) {
|
||||
background: var(--tertiary);
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.fab:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#editor-layout {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-top: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
#editor-layout.is-new-note {
|
||||
margin-top: 6rem;
|
||||
}
|
||||
|
||||
#file-path-controls {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
#editor-layout.is-new-note {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
#file-path-controls {
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.input-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.input-group label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--gray);
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
|
||||
.input-group input {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid var(--gray);
|
||||
border-radius: 4px;
|
||||
background: var(--light);
|
||||
color: var(--dark);
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.input-group input:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#editor-wrapper {
|
||||
width: 100%;
|
||||
border: 1px solid var(--darkgray);
|
||||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
background: #2a2a2a;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.cm-editor {
|
||||
min-height: 60vh;
|
||||
height: auto;
|
||||
background-color: #2a2a2a;
|
||||
}
|
||||
|
||||
.cm-scroller {
|
||||
height: 100% !important;
|
||||
min-height: 60vh;
|
||||
}
|
||||
|
||||
.cm-content {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
#editor-controls {
|
||||
margin-top: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
#commit-subject, #commit-body {
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid var(--gray);
|
||||
border-radius: 4px;
|
||||
background: var(--light);
|
||||
color: var(--dark);
|
||||
font-family: inherit;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#commit-subject:disabled, #commit-body:disabled {
|
||||
opacity: 0.7;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#commit-details {
|
||||
margin-top: 0.2rem;
|
||||
margin-bottom: 1.5rem; /* Increased vertical spacing above the buttons */
|
||||
}
|
||||
|
||||
#commit-details summary {
|
||||
cursor: pointer;
|
||||
color: var(--gray);
|
||||
font-size: 0.9rem;
|
||||
user-select: none;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#commit-details summary:hover {
|
||||
color: var(--darkgray);
|
||||
}
|
||||
|
||||
#commit-body {
|
||||
margin-top: 0.5rem;
|
||||
resize: vertical;
|
||||
min-height: 4rem;
|
||||
}
|
||||
|
||||
.editor-buttons {
|
||||
display: flex;
|
||||
justify-content: space-between; /* Pushes Delete to left, Save/Cancel to right */
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.editor-buttons-right {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.editor-buttons button {
|
||||
padding: 0.5rem 1rem;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.editor-buttons button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#save-button {
|
||||
background: var(--secondary);
|
||||
color: var(--light);
|
||||
}
|
||||
|
||||
#save-button:hover:not(:disabled) {
|
||||
background: var(--tertiary);
|
||||
}
|
||||
|
||||
#cancel-button {
|
||||
background: var(--lightgray);
|
||||
color: var(--dark);
|
||||
}
|
||||
|
||||
#cancel-button:hover:not(:disabled) {
|
||||
background: var(--gray);
|
||||
}
|
||||
|
||||
#delete-button {
|
||||
background: transparent;
|
||||
color: #e06c75; /* A distinct red color for destructive actions */
|
||||
border: 1px solid #e06c75;
|
||||
}
|
||||
|
||||
#delete-button:hover:not(:disabled) {
|
||||
background: rgba(224, 108, 117, 0.1);
|
||||
}
|
||||
|
||||
#delete-button:disabled {
|
||||
border-color: var(--gray);
|
||||
color: var(--gray);
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
#fab-container {
|
||||
bottom: 1.5rem;
|
||||
right: 1.5rem;
|
||||
}
|
||||
|
||||
.fab {
|
||||
width: 3rem;
|
||||
height: 3rem;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export default (() => Editor) satisfies QuartzComponentConstructor;
|
||||
395
quartz/components/scripts/editor.inline.ts
Normal file
395
quartz/components/scripts/editor.inline.ts
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
import { EditorState, Compartment } from "@codemirror/state";
|
||||
import { EditorView, basicSetup } from "codemirror";
|
||||
import { markdown } from "@codemirror/lang-markdown";
|
||||
import { syntaxHighlighting, HighlightStyle } from "@codemirror/language";
|
||||
import { tags as t } from "@lezer/highlight";
|
||||
|
||||
const FORGEJO_URL = "https://code.c.devon.lol";
|
||||
const REPO_OWNER = "Devon";
|
||||
const REPO_NAME = "knowledgebase";
|
||||
const BRANCH = "main";
|
||||
|
||||
const customHighlightStyle = HighlightStyle.define([
|
||||
{ tag: t.heading, color: "#61afef", fontWeight: "bold" },
|
||||
{ tag: t.keyword, color: "#c678dd" },
|
||||
{ tag: t.url, color: "#56b6c2" },
|
||||
{ tag: t.link, color: "#56b6c2", textDecoration: "underline" },
|
||||
{ tag: t.punctuation, color: "#e06c75" },
|
||||
{ tag: t.strong, fontWeight: "bold" },
|
||||
{ tag: t.emphasis, fontStyle: "italic" },
|
||||
{ tag: t.strikethrough, textDecoration: "line-through" },
|
||||
{ tag: t.meta, color: "#7f848e" },
|
||||
{ tag: t.comment, color: "#7f848e", fontStyle: "italic" },
|
||||
{ tag: t.string, color: "#98c379" },
|
||||
{ tag: t.number, color: "#d19a66" },
|
||||
{ tag: t.propertyName, color: "#e06c75" },
|
||||
{ tag: t.variableName, color: "#e06c75" },
|
||||
]);
|
||||
|
||||
const editorTheme = EditorView.theme({
|
||||
"&": { backgroundColor: "#2a2a2a", color: "#e0e0e0", fontSize: "16px" },
|
||||
".cm-content": { minHeight: "60vh", padding: "1rem" },
|
||||
"&.cm-focused .cm-cursor": { borderLeftColor: "#e0e0e0" },
|
||||
"&.cm-focused .cm-selectionBackground, ::selection": { backgroundColor: "#444444" },
|
||||
".cm-gutters": { backgroundColor: "#222222", color: "#888888", borderRight: "1px solid #444444" },
|
||||
".cm-scroller": { fontFamily: "inherit" }
|
||||
}, { dark: true });
|
||||
|
||||
document.addEventListener("nav", () => {
|
||||
const fabContainer = document.getElementById("fab-container");
|
||||
const editBtn = document.getElementById("edit-button") as HTMLButtonElement;
|
||||
const newBtn = document.getElementById("new-button") as HTMLButtonElement;
|
||||
const saveBtn = document.getElementById("save-button") as HTMLButtonElement;
|
||||
const cancelBtn = document.getElementById("cancel-button") as HTMLButtonElement;
|
||||
const deleteBtn = document.getElementById("delete-button") as HTMLButtonElement;
|
||||
const layout = document.getElementById("editor-layout");
|
||||
const wrapper = document.getElementById("editor-wrapper");
|
||||
const commitSubjectInput = document.getElementById("commit-subject") as HTMLInputElement;
|
||||
const commitBodyInput = document.getElementById("commit-body") as HTMLTextAreaElement;
|
||||
const commitDetails = document.getElementById("commit-details") as HTMLDetailsElement;
|
||||
const fileDirectoryInput = document.getElementById("file-directory") as HTMLInputElement;
|
||||
const fileNameInput = document.getElementById("file-name") as HTMLInputElement;
|
||||
|
||||
if (!editBtn || !newBtn || !layout || !wrapper || !fabContainer || !deleteBtn) return;
|
||||
|
||||
let editorView: EditorView | null = null;
|
||||
let currentFileSha = "";
|
||||
const filePath = editBtn.getAttribute("data-filepath") || "";
|
||||
const editableCompartment = new Compartment();
|
||||
|
||||
let isCreatingNewNote = false;
|
||||
|
||||
const encodeBase64 = (str: string) => btoa(unescape(encodeURIComponent(str)));
|
||||
const decodeBase64 = (str: string) => decodeURIComponent(escape(atob(str)));
|
||||
|
||||
const getPat = () => {
|
||||
let pat = localStorage.getItem("forgejo_pat");
|
||||
if (!pat) {
|
||||
pat = prompt("Enter your Forgejo Personal Access Token:");
|
||||
if (pat) localStorage.setItem("forgejo_pat", pat);
|
||||
}
|
||||
return pat;
|
||||
};
|
||||
|
||||
const getCenterColumn = () => document.querySelector(".center");
|
||||
|
||||
const onWrapperClick = (e: MouseEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (target === wrapper || target.classList.contains("cm-scroller")) {
|
||||
editorView?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const performDOMClose = () => {
|
||||
const center = getCenterColumn();
|
||||
if (center) {
|
||||
Array.from(center.children).forEach(child => {
|
||||
if (child !== layout) {
|
||||
(child as HTMLElement).style.display = "";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
layout.style.display = "none";
|
||||
layout.classList.remove("is-new-note");
|
||||
fabContainer.style.display = "flex";
|
||||
|
||||
commitSubjectInput.value = "";
|
||||
commitBodyInput.value = "";
|
||||
fileDirectoryInput.value = "";
|
||||
fileNameInput.value = "";
|
||||
commitDetails.open = false;
|
||||
isCreatingNewNote = false;
|
||||
};
|
||||
|
||||
const closeEditor = () => {
|
||||
if (history.state?.isEditor) {
|
||||
history.back();
|
||||
} else {
|
||||
performDOMClose();
|
||||
history.replaceState(null, "", window.location.pathname);
|
||||
}
|
||||
};
|
||||
|
||||
const openEditorUI = (content: string, mode: "edit" | "new", pushHistory = true) => {
|
||||
const center = getCenterColumn();
|
||||
if (center) {
|
||||
if (layout.parentNode !== center) {
|
||||
center.appendChild(layout);
|
||||
}
|
||||
|
||||
Array.from(center.children).forEach(child => {
|
||||
if (child !== layout) {
|
||||
const el = child as HTMLElement;
|
||||
if (mode === "edit" && el.classList.contains("page-header")) {
|
||||
el.style.display = "";
|
||||
} else {
|
||||
el.style.display = "none";
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fabContainer.style.display = "none";
|
||||
layout.style.display = "flex";
|
||||
|
||||
if (mode === "new") {
|
||||
layout.classList.add("is-new-note");
|
||||
deleteBtn.style.display = "none";
|
||||
commitSubjectInput.placeholder = `Create new note...`;
|
||||
} else {
|
||||
layout.classList.remove("is-new-note");
|
||||
deleteBtn.style.display = "block";
|
||||
commitSubjectInput.placeholder = `Update ${filePath}...`;
|
||||
}
|
||||
|
||||
if (pushHistory) {
|
||||
if (mode === "edit") {
|
||||
history.pushState({ isEditor: true }, "", "?edit");
|
||||
} else {
|
||||
history.pushState({ isEditor: true }, "", "/?new");
|
||||
}
|
||||
}
|
||||
|
||||
if (editorView) editorView.destroy();
|
||||
|
||||
editorView = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: content,
|
||||
extensions: [
|
||||
basicSetup,
|
||||
markdown(),
|
||||
editorTheme,
|
||||
syntaxHighlighting(customHighlightStyle),
|
||||
editableCompartment.of(EditorView.editable.of(true))
|
||||
]
|
||||
}),
|
||||
parent: wrapper
|
||||
});
|
||||
};
|
||||
|
||||
const onEdit = async (e?: Event, pushHistory = true) => {
|
||||
const pat = getPat();
|
||||
if (!pat || !filePath) return;
|
||||
|
||||
isCreatingNewNote = false;
|
||||
editBtn.disabled = true;
|
||||
|
||||
const parts = filePath.split("/");
|
||||
const fName = parts.pop() || "";
|
||||
fileDirectoryInput.value = parts.join("/");
|
||||
fileNameInput.value = fName.replace(/\.md$/i, "");
|
||||
|
||||
const encodedFilePath = filePath.split('/').map(encodeURIComponent).join('/');
|
||||
|
||||
try {
|
||||
const res = await fetch(`${FORGEJO_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/contents/${encodedFilePath}?ref=${BRANCH}`, {
|
||||
headers: { "Authorization": `token ${pat}` }
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error("Failed to fetch file. Check your PAT.");
|
||||
const data = await res.json();
|
||||
|
||||
currentFileSha = data.sha;
|
||||
const content = decodeBase64(data.content);
|
||||
|
||||
openEditorUI(content, "edit", pushHistory);
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
fabContainer.style.display = "flex";
|
||||
} finally {
|
||||
editBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
const onNewNote = (e?: Event, pushHistory = true) => {
|
||||
isCreatingNewNote = true;
|
||||
currentFileSha = "";
|
||||
|
||||
fileDirectoryInput.value = localStorage.getItem("forgejo_default_dir") || "";
|
||||
fileNameInput.value = "";
|
||||
|
||||
openEditorUI("", "new", pushHistory);
|
||||
};
|
||||
|
||||
const onCancel = () => closeEditor();
|
||||
|
||||
const lockUI = (isLocked: boolean) => {
|
||||
if (saveBtn) saveBtn.disabled = isLocked;
|
||||
if (cancelBtn) cancelBtn.disabled = isLocked;
|
||||
if (deleteBtn) deleteBtn.disabled = isLocked;
|
||||
commitSubjectInput.disabled = isLocked;
|
||||
commitBodyInput.disabled = isLocked;
|
||||
fileDirectoryInput.disabled = isLocked;
|
||||
fileNameInput.disabled = isLocked;
|
||||
|
||||
if (editorView) {
|
||||
editorView.dispatch({
|
||||
effects: editableCompartment.reconfigure(EditorView.editable.of(!isLocked))
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onSave = async () => {
|
||||
if (!editorView) return;
|
||||
const pat = getPat();
|
||||
const newContent = editorView.state.doc.toString();
|
||||
|
||||
const dir = fileDirectoryInput.value.trim();
|
||||
let file = fileNameInput.value.trim();
|
||||
|
||||
if (!file) {
|
||||
alert("Please enter a Note Name.");
|
||||
return;
|
||||
}
|
||||
if (file.startsWith(".")) {
|
||||
alert("Filename must not start with a dot.");
|
||||
return;
|
||||
}
|
||||
if (/[\[\]#\^|\\\/:]/.test(file)) {
|
||||
alert("Filename cannot contain the following characters: [ ] # ^ | \\ / :");
|
||||
return;
|
||||
}
|
||||
if (!file.toLowerCase().endsWith(".md")) {
|
||||
file += ".md";
|
||||
}
|
||||
|
||||
const cleanDir = dir.replace(/\/$/, "");
|
||||
const targetFilePath = cleanDir ? `${cleanDir}/${file}` : file;
|
||||
|
||||
const isMovingOrRenaming = !isCreatingNewNote && targetFilePath !== filePath;
|
||||
|
||||
let defaultSubject = `Update ${targetFilePath}`;
|
||||
if (isCreatingNewNote) defaultSubject = `Create ${targetFilePath}`;
|
||||
if (isMovingOrRenaming) defaultSubject = `Move ${filePath} to ${targetFilePath}`;
|
||||
|
||||
const subject = commitSubjectInput.value.trim() || defaultSubject;
|
||||
const body = commitBodyInput.value.trim();
|
||||
const fullMessage = body ? `${subject}\n\n${body}` : subject;
|
||||
|
||||
lockUI(true);
|
||||
if (saveBtn) saveBtn.innerText = "Saving...";
|
||||
|
||||
const encodedTargetFilePath = targetFilePath.split('/').map(encodeURIComponent).join('/');
|
||||
|
||||
try {
|
||||
const payload: any = {
|
||||
branch: BRANCH,
|
||||
content: encodeBase64(newContent),
|
||||
message: fullMessage
|
||||
};
|
||||
|
||||
if (!isCreatingNewNote) {
|
||||
payload.sha = currentFileSha;
|
||||
if (isMovingOrRenaming) {
|
||||
payload.from_path = filePath;
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(`${FORGEJO_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/contents/${encodedTargetFilePath}`, {
|
||||
method: isCreatingNewNote ? "POST" : "PUT",
|
||||
headers: {
|
||||
"Authorization": `token ${pat}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({}));
|
||||
throw new Error(errorData.message || "Failed to save. If creating a new file, ensure it doesn't already exist.");
|
||||
}
|
||||
|
||||
if (isCreatingNewNote) {
|
||||
localStorage.setItem("forgejo_default_dir", cleanDir);
|
||||
}
|
||||
|
||||
closeEditor();
|
||||
alert(`Saved successfully!\n\nChanges will be live in about 5 minutes once the site rebuilds.\n\nNote: If you moved or renamed this note, it will be unavailable at its old path after the rebuild. Editing a moved/renamed note before the rebuild completes will fail.`);
|
||||
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
} finally {
|
||||
lockUI(false);
|
||||
if (saveBtn) saveBtn.innerText = "Save";
|
||||
}
|
||||
};
|
||||
|
||||
const onDelete = async () => {
|
||||
if (!filePath || !currentFileSha) return;
|
||||
|
||||
const confirmDelete = confirm(`Are you sure you want to permanently delete:\n\n${filePath}\n\nThis cannot be undone.`);
|
||||
if (!confirmDelete) return;
|
||||
|
||||
const pat = getPat();
|
||||
if (!pat) return;
|
||||
|
||||
const subject = commitSubjectInput.value.trim() || `Delete ${filePath}`;
|
||||
const body = commitBodyInput.value.trim();
|
||||
const fullMessage = body ? `${subject}\n\n${body}` : subject;
|
||||
|
||||
lockUI(true);
|
||||
if (deleteBtn) deleteBtn.innerText = "Deleting...";
|
||||
|
||||
const encodedFilePath = filePath.split('/').map(encodeURIComponent).join('/');
|
||||
|
||||
try {
|
||||
const res = await fetch(`${FORGEJO_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/contents/${encodedFilePath}`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Authorization": `token ${pat}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify({
|
||||
branch: BRANCH,
|
||||
message: fullMessage,
|
||||
sha: currentFileSha
|
||||
})
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({}));
|
||||
throw new Error(errorData.message || "Failed to delete file.");
|
||||
}
|
||||
|
||||
closeEditor();
|
||||
alert(`Deleted successfully!\n\nChanges will be live in about 5 minutes once the site rebuilds.`);
|
||||
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
} finally {
|
||||
lockUI(false);
|
||||
if (deleteBtn) deleteBtn.innerText = "Delete Note";
|
||||
}
|
||||
};
|
||||
|
||||
const query = new URLSearchParams(window.location.search);
|
||||
if (query.has("edit")) {
|
||||
onEdit(undefined, false);
|
||||
} else if (query.has("new")) {
|
||||
onNewNote(undefined, false);
|
||||
}
|
||||
|
||||
window.addEventListener("popstate", (e) => {
|
||||
if (layout.style.display !== "none" && !e.state?.isEditor) {
|
||||
performDOMClose();
|
||||
}
|
||||
});
|
||||
|
||||
wrapper.addEventListener("click", onWrapperClick);
|
||||
editBtn.addEventListener("click", onEdit);
|
||||
newBtn.addEventListener("click", onNewNote);
|
||||
cancelBtn?.addEventListener("click", onCancel);
|
||||
saveBtn?.addEventListener("click", onSave);
|
||||
deleteBtn?.addEventListener("click", onDelete);
|
||||
|
||||
window.addCleanup(() => {
|
||||
wrapper.removeEventListener("click", onWrapperClick);
|
||||
editBtn.removeEventListener("click", onEdit);
|
||||
newBtn.removeEventListener("click", onNewNote);
|
||||
cancelBtn?.removeEventListener("click", onCancel);
|
||||
saveBtn?.removeEventListener("click", onSave);
|
||||
deleteBtn?.removeEventListener("click", onDelete);
|
||||
if (editorView) editorView.destroy();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue