first commit; dx 1.0 beta

This commit is contained in:
2025-11-09 22:35:16 +03:00
commit 4d01725955
153 changed files with 6504 additions and 0 deletions
+136
View File
@@ -0,0 +1,136 @@
export const dayOfWeeksNames = [
"понедельник",
"вторник",
"cреда",
"четверг",
"пятница",
"суббота",
"воскресенье",
];
export const monthNames = [
"января",
"февраля",
"марта",
"апреля",
"мая",
"июня",
"июля",
"августа",
"сентября",
"октября",
"ноября",
"декабря",
];
export const dateTagsList = {
today: "сегодня",
tomorrow: "завтра",
yesterday: "вчера",
afterTomorrow: "послезавтра",
};
export function getDateTags(date) {
const x = new Date();
x.setHours(0, 0, 0, 0);
const t = new Date(date);
t.setHours(0, 0, 0, 0);
const diff = (t - x) / 86400000; // days difference
return diff === 0
? dateTagsList["today"]
: diff === -1
? dateTagsList["yesterday"]
: diff === 1
? dateTagsList["tomorrow"]
: diff === 2
? dateTagsList["afterTomorrow"]
: "";
}
export function usToRussianDay(usDay) {
return (usDay + 6) % 7;
}
export function formatDate(date) {
return `${
dayOfWeeksNames[usToRussianDay(date.getDay())]
}, ${date.getDate()} ${monthNames[date.getMonth()]}`;
}
export function apiFormatDate(date) {
return (
("0" + date.getDate()).slice(-2) +
"-" +
("0" + (date.getMonth() + 1)).slice(-2) +
"-" +
String(date.getFullYear()).slice(-2)
);
}
export const parseApiDate = (s) => {
const [d, m, y] = s.split("-").map(Number);
const yy = 2000 + y;
return new Date(yy, m - 1, d);
};
export const apiToEditorVocabluary = {
// api: editor
num: "position",
cabinet: "room",
subject: "subject",
"t-begin": "time1",
"t-end": "time2",
};
export function convertApiToEditor(arr) {
let uuid = Math.floor(Math.random() * 10000);
return arr.map((item) => {
const converted = {};
for (const [apiKey, editorKey] of Object.entries(apiToEditorVocabluary)) {
if (Object.prototype.hasOwnProperty.call(item, apiKey)) {
converted[editorKey] = item[apiKey];
}
}
converted.id = uuid;
uuid += Math.floor(Math.random() * 10000);
return converted;
});
}
export function convertEditorToApi(arr) {
const editorToApi = Object.fromEntries(
Object.entries(apiToEditorVocabluary).map(([apiKey, editorKey]) => [
editorKey,
apiKey,
])
);
return arr.reduce((acc, item) => {
const converted = {};
for (const [editorKey, apiKey] of Object.entries(editorToApi)) {
if (!Object.prototype.hasOwnProperty.call(item, editorKey)) continue;
const value = item[editorKey];
if (
(editorKey === "time1" || editorKey === "time2") &&
(value === "" || value == null)
) {
// фиг вам
continue;
}
if (editorKey === "subject" && value === "") {
// ваще наху
return acc;
}
converted[apiKey] = value;
}
acc.push(converted);
return acc;
}, []);
}
export function isTimeBeforeNow(timeStr) {
const [h, m] = timeStr.split(':').map(Number);
if (!Number.isFinite(h) || !Number.isFinite(m)) return false;
const now = new Date();
const t = new Date(now.getFullYear(), now.getMonth(), now.getDate(), h, m, 0, 0);
return t.getTime() < now.getTime();
}
+72
View File
@@ -0,0 +1,72 @@
export class DengiCaching {
vals = [
/*
{
name:"unique-id-name",
value:"somevalue",
expires=Date
}
*/
];
constructor() {}
tick() {
this.vals.map((element, index) => {
if (element.expires < new Date()) {
if (index > -1) {
this.vals = this.vals.splice(index, 1);
}
}
});
}
withCache(name, ifNotFound) {
this.tick();
let a = this.get(name);
if (a === undefined) {
let c = ifNotFound();
this.cache(name, c);
return c;
} else {
return a;
}
}
async withCacheAsync(name, ifNotFound) {
this.tick();
let a = this.get(name);
if (a === undefined) {
let c = await ifNotFound();
this.cache(name, c);
return c;
} else {
return a;
}
}
delete(...names) {
names.forEach((name) => {
var index = this.vals.findIndex((a) => a.name == name);
if (index > -1) {
this.vals = this.vals.splice(index, 1);
}
this.tick();
});
}
fullClear() {
this.vals = [];
}
wasCached(name) {
this.tick();
return this.vals.find((a) => a.name == name) !== undefined;
}
get(name) {
this.tick();
const item = this.vals.find((a) => a.name === name);
return item ? item.value : undefined;
}
cache(name, val) {
this.tick();
this.vals.push({
name: name,
value: val,
expires: new Date(Date.now() + 60 * 60 * 1000),
});
}
}
+654
View File
@@ -0,0 +1,654 @@
import React, { useEffect, useRef, useState } from "react";
import {
DndContext,
closestCenter,
PointerSensor,
TouchSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import {
arrayMove,
SortableContext,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { BiCopy, BiDotsVertical, BiX } from "react-icons/bi";
import {
DengiButton,
DengiYesOrNoDialog,
LoadingSpinner,
} from "./trash-components";
import { motion, AnimatePresence } from "motion/react";
import {
BiCheck,
BiPlus,
BiRedo,
BiTime,
BiTrash,
BiUndo,
} from "react-icons/bi";
// import { ifstyle } from "../App";
import {
apiFormatDate,
convertApiToEditor,
convertEditorToApi,
formatDate,
} from "./dengi";
import {
EditorPrefillRequest,
EditorPublishRequest,
EditorRemoveRequest,
} from "./editor_req_mgr";
import { API_BASE_URL } from "../App";
// Configuration
const COLUMNS = [
[
{
key: "position",
label: "номер",
width: "w-9",
placeholder: "№",
useinput: true,
},
{
key: "subject",
label: "предмет",
width: "w-40",
placeholder: "предмет",
useinput: false,
},
{
key: "room",
label: "кабинет",
width: "w-14",
placeholder: "123",
useinput: false,
},
{
key: "time1",
label: "начало",
width: "w-16",
placeholder: "00:00",
useinput: true,
},
{
key: "time2",
label: "конец",
width: "w-16",
placeholder: "00:00",
useinput: true,
},
],
[
{
key: "position",
label: "номер",
width: "w-9",
placeholder: "№",
useinput: true,
},
{
key: "subject",
label: "предмет",
width: "w-40",
placeholder: "предмет",
useinput: false,
},
{
key: "room",
label: "кабинет",
width: "w-14",
placeholder: "123",
useinput: false,
},
],
[
{
key: "position",
label: "номер",
width: "w-9",
placeholder: "№",
useinput: true,
},
{
key: "time1",
label: "начало",
width: "w-16",
placeholder: "00:00",
useinput: true,
},
{
key: "time2",
label: "конец",
width: "w-16",
placeholder: "00:00",
useinput: true,
},
],
];
const INITIAL_DATA = [
// {
// id: "1",
// position: "1",
// subject: "Mathematics",
// time: "09:00",
// room: "A-1",
// },
// { id: "2", position: "2", subject: "Physics", time: "10:00", room: "B-2" },
// { id: "3", position: "3", subject: "Chemistry", time: "11:00", room: "A-3" },
// { id: "4", position: "4", subject: "Biology", time: "13:00", room: "C-1" },
];
function TableInput(props) {
return props.useinput ? <input {...props} /> : <textarea {...props} />;
}
function SortableRow({
item,
columns,
onUpdate,
onDelete,
onDuplicate,
setFocusEdit,
setHoverEdit,
}) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: item.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<div
ref={setNodeRef}
style={style}
className="bg-zinc-900 bg-grain rounded-lg mb-2"
>
<div className="flex flex-col gap-2">
<div className="flex">
{columns.map((col) => (
<TableInput
key={col.key}
useinput={col.useinput}
type="text"
value={item[col.key] || ""}
wrap="hard"
rows={1}
onChange={(e) => onUpdate(item.id, col.key, e.target.value)}
className={`px-1 py-3 text-center bg-transparent text-white border-r border-zinc-700 last:border-r-0 last:rounded-tr-lg focus:outline-none focus:bg-gray-700/50 placeholder-gray-500 transition-colors hover:bg-gray-700/20 first:rounded-tl-lg max-h-min resize-none block min-w-0 grow ${col.width}`}
placeholder={col.placeholder}
onFocus={() => setFocusEdit(col.key)}
onBlur={() => setFocusEdit(null)}
onMouseOver={() => setHoverEdit(col.key)}
onMouseLeave={() => setHoverEdit(null)}
/>
))}
</div>
<span className="w-[98%] mx-auto h-[1px] bg-zinc-500" />
<div className="flex justify-end w-full">
<button
onClick={() => onDuplicate(item.id)}
className="min-w-12 min-h-12 transition-colors bg-zinc-600/20 text-zinc-400 hover:bg-zinc-600/40 hover:text-zinc-300 flex items-center justify-center rounded-l-md"
>
<BiCopy size={20} />
</button>
<div
{...attributes}
{...listeners}
className="min-w-12 min-h-12 transition-colors hover:bg-zinc-200 flex items-center justify-center cursor-move touch-none select-none hover:text-black font-black text-white bg-zinc-700/60"
>
<BiDotsVertical size={24} />
</div>
<button
onClick={() => onDelete(item.id)}
className="min-w-12 min-h-12 transition-colors bg-red-600/20 text-red-400 hover:bg-red-600/40 hover:text-red-300 active:bg-red-600/60 flex items-center justify-center rounded-r-md"
>
<BiX size={24} />
</button>
</div>
</div>
</div>
);
}
async function getPrefilledRasp(tab, date, adminId) {
let a = await EditorPrefillRequest(
API_BASE_URL,
tab,
adminId,
apiFormatDate(date)
);
if (a[0] == 1 && a[1]) {
return convertApiToEditor(a[1]);
}
}
export function TableEditor({
initialData = INITIAL_DATA,
onChange = () => {},
selectedTab,
columns = COLUMNS[selectedTab],
setChangesWereMade,
adminId,
date,
dengiCash,
}) {
const [items, setItems] = useState(initialData);
const [undoItems, setUndoItems] = useState([]);
const [redoItems, setRedoItems] = useState([]);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
let rejected = false;
//console.log("cleanup");
// cleanup on change
setUndoItems([]);
setRedoItems([]);
setLoading(true);
getPrefilledRasp(selectedTab, date, adminId).then((i) => {
if (rejected) return;
console.log(i || []);
setItems(i || []);
setLoading(false);
});
return () => {
rejected = true;
};
}, [
selectedTab,
formatDate(date) /* NOTE: we need to format to rely only on DD-MM-YY,
and forget about time at all*/,
]);
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
}),
useSensor(TouchSensor, {
activationConstraint: {
delay: 200,
tolerance: 8,
},
})
);
const updateItems = (newItems) => {
setItems(newItems);
onChange?.(newItems);
};
useEffect(() => setChangesWereMade(undoItems.length > 0), [undoItems]);
const handleDragEnd = (event) => {
const { active, over } = event;
if (over && active.id !== over.id) {
const oldIndex = items.findIndex((item) => item.id === active.id);
const newIndex = items.findIndex((item) => item.id === over.id);
const newItems = arrayMove(items, oldIndex, newIndex);
// Swap positions: assign old positions to new order
const reorderedItems = newItems.map((item, idx) => ({
...item,
position: items[idx].position, // Use position from original array at this index
}));
setUndoItems([items, ...undoItems]);
updateItems(reorderedItems);
}
};
const updateTimeoutRef = useRef({});
const previousValueRef = useRef({});
const handleUpdate = (id, field, value) => {
const key = `${id}-${field}`;
if (!updateTimeoutRef.current[key]) {
const currentItem = items.find((item) => item.id === id);
previousValueRef.current[key] = currentItem[field];
}
if (updateTimeoutRef.current[key]) {
clearTimeout(updateTimeoutRef.current[key]);
}
const newItems = items.map((item) =>
item.id === id ? { ...item, [field]: value } : item
);
updateItems(newItems);
updateTimeoutRef.current[key] = setTimeout(() => {
// Create items array with the ORIGINAL value from before editing started
const itemsWithOriginalValue = items.map((item) =>
item.id === id
? { ...item, [field]: previousValueRef.current[key] }
: item
);
setUndoItems([itemsWithOriginalValue, ...undoItems]);
// Clean up
delete updateTimeoutRef.current[key];
delete previousValueRef.current[key];
}, 1000);
};
const handleUndo = () => {
if (isLoading) return;
setRedoItems([items, ...redoItems]);
updateItems(undoItems[0]);
setUndoItems(undoItems.slice(1));
};
const handleRedo = () => {
if (isLoading) return;
setUndoItems([items, ...undoItems]);
updateItems(redoItems[0]);
setRedoItems(redoItems.slice(1));
};
const handleDelete = (id) => {
if (isLoading) return;
const newItems = items.filter((item) => item.id !== id);
setUndoItems([items, ...undoItems]);
updateItems(newItems);
};
const handleDuplicate = (id) => {
const index = items.findIndex((item) => item.id === id);
if (index === -1) return;
const itemToDuplicate = items[index];
// Create new item with unique id
const newItem = {
...itemToDuplicate,
id: Date.now(), // or use uuid() or any unique id generator
};
// Insert the new item right after the duplicated item
const newItems = [
...items.slice(0, index + 1),
newItem,
...items.slice(index + 1),
];
// Reassign positions based on the original order
// The duplicate takes the next position, and everything shifts
const reorderedItems = newItems.map((item, idx) => ({
...item,
position: String(idx + 1), // or just (idx + 1) if position is a number
}));
setUndoItems([items, ...undoItems]);
updateItems(reorderedItems);
};
const handleAddRow = () => {
if (isLoading) return;
const newId = String(Date.now());
const sortedItems = [...items];
sortedItems.sort((a, b) => a.position - b.position);
const lastPosition =
items.length > 0
? String(
parseInt(sortedItems[sortedItems.length - 1].position || "0") + 1
)
: "1";
const newItem = { id: newId, position: lastPosition };
columns.forEach((col) => {
if (col.key !== "position") {
newItem[col.key] = "";
}
});
setUndoItems([items, ...undoItems]);
updateItems([...items, newItem]);
setTimeout(
() =>
window.scrollTo({
top: document.documentElement.scrollHeight - window.innerHeight,
left: window.scrollX, // preserve current X
behavior: "smooth",
}),
100
);
};
const [focusEdit, setFocusEdit] = useState(null);
const [hoverEdit, setHoverEdit] = useState(null);
const [deleteDiag, setDeleteDiag] = useState(false);
const handleClear = () => {
if (isLoading) return;
setUndoItems([items, ...undoItems]);
updateItems([]);
};
const handleChangesDefault = () => {
if (selectedTab != 0 || isLoading) return;
setLoading(true);
getPrefilledRasp(1, date, adminId).then((i) => {
setUndoItems([items, ...undoItems]);
setItems(i);
setLoading(false);
});
};
const handlePublish = () => {
if (isLoading) return;
setUndoItems([]);
setRedoItems([]);
console.log(convertEditorToApi(items));
dengiCash.fullClear(); // keep it clean
setLoading(true);
EditorPublishRequest(
API_BASE_URL,
selectedTab,
adminId,
apiFormatDate(date),
JSON.stringify(convertEditorToApi(items))
).then(() => {
setLoading(false);
});
};
const handleDeleteAll = () => {
// if (isLoading) return; // WARN!
setDeleteDiag(true);
};
let deleteDialogBusy = false; // NOTE: we don't need a state
return (
<>
<div>
<DengiYesOrNoDialog
content={{
message: "ВСЁ БУДЕТ УДАЛЕНО! продолжить?",
yesBtn: "да",
noBtn: "нет",
yesIcon: <BiTrash />,
noIcon: <BiX size={20} />,
bgDissmis: true,
yesBtnStyle: "bg-red-500! text-white! md:hover:bg-red-600!",
}}
onAnswer={(answ) => {
if (deleteDialogBusy) return;
if (!answ) setDeleteDiag(false);
else {
dengiCash.fullClear();
// scary
deleteDialogBusy = true;
EditorRemoveRequest(
API_BASE_URL,
selectedTab,
adminId,
apiFormatDate(date)
).then(() => {
deleteDialogBusy = false; // for 100% sure
setDeleteDiag(false);
location.hash = "/app";
});
}
}}
show={deleteDiag}
/>
</div>
<div className="w-full overflow-hidden my-1 flex flex-col gap-3">
<div className="flex gap-2 flex-wrap">
<DengiButton onClick={handleUndo} disabled={undoItems.length == 0}>
<BiUndo />
</DengiButton>
<DengiButton onClick={handleRedo} disabled={redoItems.length == 0}>
<BiRedo />
</DengiButton>
<AnimatePresence mode="popLayout">
{selectedTab == 0 && (
<motion.div exit={{ opacity: 0 }}>
<DengiButton
className="border-red-600! md:not-disabled:not-hover:border-red-400!"
onClick={handleChangesDefault}
>
<BiTime />
убрать&nbsp;зам.
</DengiButton>
</motion.div>
)}
</AnimatePresence>
<motion.div layout="position" className="bg-black">
<DengiButton
onClick={handleClear}
className="border-red-600! md:not-disabled:not-hover:border-red-400!"
>
<BiTrash />
очистить
</DengiButton>
</motion.div>
</div>
{!isLoading && (
<div>
<div className="flex w-full justify-around items-center mb-2">
{columns.map((col, i) => (
<>
<div
key={col.key + i}
className={
`max-${col.width} transition-colors text-` +
((focusEdit == null && hoverEdit == null) ||
focusEdit == col.key ||
hoverEdit == col.key
? "white"
: "zinc-600")
}
// onMouseOver={() => setHoverEdit(col.key)}
// onMouseLeave={() => setHoverEdit(null)}
>
{col.label}
</div>
<span
key={col.key + i + "divider"}
className="w-4 h-[1px] bg-zinc-600 -rotate-45 last:hidden"
/>
</>
))}
</div>
<div className="max-w-3xl mx-auto">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={items.map((item) => item.id)}
strategy={verticalListSortingStrategy}
>
<div>
<AnimatePresence mode={items.length > 0 ? "sync" : "wait"}>
{items.map((item) => (
<motion.div
initial={{ x: -15, filter: "blur(5px)", opacity: 0 }}
animate={{ x: 0, filter: "blur(0px)", opacity: 1 }}
exit={{ x: 15, filter: "blur(5px)", opacity: 0 }}
key={item.id}
>
<SortableRow
item={item}
columns={columns}
onUpdate={handleUpdate}
onDelete={handleDelete}
onDuplicate={handleDuplicate}
setFocusEdit={setFocusEdit}
setHoverEdit={setHoverEdit}
/>
</motion.div>
))}
{items.length === 0 && (
<motion.div
initial={{
filter: "blur(5px)",
opacity: 0,
scale: 0.8,
}}
animate={{
filter: "blur(0px)",
opacity: 1,
scale: 1,
}}
className="border-2 border-dashed border-gray-700 rounded-lg p-12 text-center text-gray-500"
>
пусто
</motion.div>
)}
</AnimatePresence>
</div>
</SortableContext>
</DndContext>
{/* <div className="mt-6 flex gap-3">
<button
onClick={handleAddRow}
className="flex-1 bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-700 active:bg-blue-800"
>
+ Add Row
</button>
<button
onClick={handleClear}
className="px-6 py-3 rounded-lg border-2 border-gray-700 text-gray-300 font-semibold hover:bg-gray-800 active:bg-gray-700"
>
Clear All
</button>
</div> */}
</div>
</div>
)}
{isLoading && (
<div className="w-full flex items-center justify-center py-3">
<LoadingSpinner size={35} />
</div>
)}
<motion.div layout="position" className="flex w-full justify-end gap-2">
<DengiButton
onClick={handleDeleteAll}
className="border-red-600! md:not-disabled:not-hover:border-red-400!"
>
<BiTrash />
удалить всё
</DengiButton>
<DengiButton onClick={handleAddRow}>
<BiPlus />
</DengiButton>
<DengiButton onClick={handlePublish}>
<BiCheck />
сохранить
</DengiButton>
</motion.div>
</div>
</>
);
}
+80
View File
@@ -0,0 +1,80 @@
export async function EditorPrefillRequest(host, tab, adminid, date) {
try {
const req = await fetch(host + "?editor_data", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
adminId: adminid,
tab: tab,
day: date,
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
export async function EditorPublishRequest(host, tab, adminid, date, newData) {
try {
const req = await fetch(host + "?editor_publish", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
adminId: adminid,
tab: tab,
day: date,
newData: newData,
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
export async function EditorRemoveRequest(host, tab, adminid, date) {
try {
const req = await fetch(host + "?editor_fullitems_del", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
adminId: adminid,
tab: tab,
day: date,
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
+70
View File
@@ -0,0 +1,70 @@
export function ifstyle(condition, then) {
return condition ? " " + then : "";
}
export function b64e(str) {
return btoa(
encodeURIComponent(str).replace(
/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode("0x" + p1);
}
)
);
}
export function b64d(str) {
return decodeURIComponent(
atob(str)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join("")
);
}
/** by claude
* Universal copy-to-clipboard function
* Works with modern Clipboard API and falls back to legacy methods
* @param {string} text - The text to copy to clipboard
* @returns {Promise<boolean>} - Returns true if successful, false otherwise
*/
export async function copyToClipboard(text) {
// Method 1: Modern Clipboard API (preferred)
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
console.warn('Clipboard API failed, trying fallback:', err);
}
}
// Method 2: Fallback for older browsers or non-secure contexts
try {
const textarea = document.createElement('textarea');
textarea.value = text;
// Make it invisible and non-intrusive
textarea.style.position = 'fixed';
textarea.style.left = '-999999px';
textarea.style.top = '-999999px';
textarea.style.opacity = '0';
textarea.setAttribute('readonly', '');
document.body.appendChild(textarea);
// Select and copy
textarea.select();
textarea.setSelectionRange(0, text.length);
const success = document.execCommand('copy');
document.body.removeChild(textarea);
return success;
} catch (err) {
console.error('All copy methods failed:', err);
return false;
}
}
+167
View File
@@ -0,0 +1,167 @@
/**
* MD5 hash implementation
* Based on: http://www.myersdaily.org/joseph/javascript/md5-text.html
*/
const HEX_CHARS = '0123456789abcdef';
// Pre-compute add32 function based on environment
const add32 = (() => {
const test = (a, b) => (a + b) & 0xFFFFFFFF;
// Test if simple addition works correctly
if (test(0x80000000, 0x80000000) === 0) {
return test;
}
// Fallback for environments with non-standard 32-bit arithmetic
return (x, y) => {
const lsw = (x & 0xFFFF) + (y & 0xFFFF);
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
})();
const cmn = (q, a, b, x, s, t) => {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
};
const ff = (a, b, c, d, x, s, t) => cmn((b & c) | ((~b) & d), a, b, x, s, t);
const gg = (a, b, c, d, x, s, t) => cmn((b & d) | (c & (~d)), a, b, x, s, t);
const hh = (a, b, c, d, x, s, t) => cmn(b ^ c ^ d, a, b, x, s, t);
const ii = (a, b, c, d, x, s, t) => cmn(c ^ (b | (~d)), a, b, x, s, t);
const md5blk = (s) => {
const blks = [];
for (let i = 0; i < 64; i += 4) {
blks[i >> 2] = s.charCodeAt(i) +
(s.charCodeAt(i + 1) << 8) +
(s.charCodeAt(i + 2) << 16) +
(s.charCodeAt(i + 3) << 24);
}
return blks;
};
const md5cycle = (x, k) => {
let a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
};
const rhex = (n) => {
let s = '';
for (let j = 0; j < 4; j++) {
s += HEX_CHARS[(n >> (j * 8 + 4)) & 0x0F] + HEX_CHARS[(n >> (j * 8)) & 0x0F];
}
return s;
};
const hex = (x) => x.map(rhex).join('');
const md51 = (s) => {
const n = s.length;
const state = [1732584193, -271733879, -1732584194, 271733878];
let i;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
const tail = new Array(16).fill(0);
for (i = 0; i < s.length; i++) {
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
tail.fill(0);
}
tail[14] = n * 8;
md5cycle(state, tail);
return state;
};
/**
* Calculate MD5 hash of a string
* @param {string} s - Input string
* @returns {string} MD5 hash in hexadecimal format
*/
export function md5(s) {
return hex(md51(s));
}
+127
View File
@@ -0,0 +1,127 @@
import { apiFormatDate } from "./dengi";
export async function LoginReq(host, username) {
try {
const req = await fetch(host + "?login", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded", // 💀 важный заголовок
},
body: new URLSearchParams({
classId: username,
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
export async function RaspGet(host, classId, day) {
try {
const req = await fetch(host + "?req_client_schedule", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded", // 💀 важный заголовок
},
body: new URLSearchParams({
classId: classId,
day: apiFormatDate(day),
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
export async function AdminReq(host, adminid) {
try {
const req = await fetch(host + "?admin_login", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded", // 💀 dengi
},
body: new URLSearchParams({
adminId: adminid,
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
export async function AdminUserFRequest(host, adminid) {
try {
const req = await fetch(host + "?get_admin_user_f", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
adminId: adminid,
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
export async function classUserFRequest(host, classid) {
try {
const req = await fetch(host + "?get_class_user_f", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
classId: classid,
}).toString(),
});
if (
req.ok &&
req.headers.get("Content-Type")?.includes("application/json")
) {
return [1, await req.json()];
} else {
return [req.status, await req.text()];
}
} catch (err) {
return [-1, err];
}
}
+299
View File
@@ -0,0 +1,299 @@
import { useEffect, useState } from "react";
import { BiCheck, BiLeftArrowAlt, BiRightArrowAlt, BiX } from "react-icons/bi";
import { formatDate, getDateTags } from "./dengi.js";
import { AnimatePresence, motion } from "motion/react";
export function Switch({
checked,
defaultChecked = false,
onChange,
disabled = false,
ariaLabel,
className = "",
size = "md", // "sm" | "md" | "lg"
}) {
const isControlled = checked !== undefined;
const [internalChecked, setInternalChecked] = useState(defaultChecked);
const current = isControlled ? checked : internalChecked;
useEffect(() => {
if (!isControlled) return;
setInternalChecked(checked);
}, [checked, isControlled]);
const sizes = {
sm: { track: "w-9 h-5", thumb: "w-3 h-3", translate: "translate-x-4" },
md: { track: "w-11 h-6", thumb: "w-4 h-4", translate: "translate-x-5" },
lg: { track: "w-14 h-8", thumb: "w-6 h-6", translate: "translate-x-6" },
};
const s = sizes[size] || sizes.md;
const toggle = (next) => {
if (disabled) return;
const newState = typeof next === "boolean" ? next : !current;
if (!isControlled) setInternalChecked(newState);
onChange?.(newState);
};
return (
<button
type="button"
role="switch"
aria-checked={current}
aria-label={ariaLabel}
disabled={disabled}
tabIndex={disabled ? -1 : 0}
onClick={() => toggle()}
className={[
"inline-flex items-center p-0 focus:outline-none",
// focus-visible: shows ring only when focused by keyboard (better UX)
"focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-0.5 focus-visible:ring-offset-transparent",
disabled ? "opacity-60" : "cursor-pointer",
current ? "bg-zinc-500" : "bg-gray-300/10",
"rounded-full transition-colors duration-150",
s.track,
className,
].join(" ")}
>
<span
className={[
"relative block rounded-full bg-white shadow transform transition-transform ease-out duration-150",
s.thumb,
current ? s.translate : "",
size === "sm" ? "m-1" : "m-1",
].join(" ")}
/>
</button>
);
}
export function LoadingSpinner(props) {
return (
<svg
aria-hidden="true"
className="animate-spin ease-out text-zinc-600 fill-white"
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
width={props.size}
height={props.size}
>
<path
d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="currentColor"
/>
<path
d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentFill"
/>
</svg>
);
}
function DatePickerButton({ next = false, date, setDate }) {
return (
<span
className="cursor-pointer lg:hover:*:fill-black lg:hover:bg-white transition *:transition-colors rounded-full"
onClick={() => {
const d = new Date(date);
d.setDate(d.getDate() + (next ? 1 : -1));
setDate(d);
}}
>
{!next ? <BiLeftArrowAlt size={34} /> : <BiRightArrowAlt size={34} />}
</span>
);
}
export function DatePicker(props) {
const dateTag = getDateTags(props.date);
return (
<div className="flex items-center justify-between px-2 py-1 w-full bg-grain border-zinc-800/40 border rounded-2xl">
<DatePickerButton date={props.date} setDate={props.setDate} />
<AnimatePresence mode="popLayout">
<motion.span
key={formatDate(props.date)}
className="cursor-pointer flex items-center gap-1 justify-center w-[80%] text-zinc-300 lg:hover:text-black *:transition-colors transition-colors p-1 rounded-3xl lg:hover:bg-white px-3 overflow-hidden lg:hover:*:text-black"
variants={{
a: { opacity: 0, filter: "blur(1px)" },
b: { opacity: 1, filter: "blur(0px)" },
}}
initial="a"
animate="b"
exit="a"
onClick={() => {
props.setDate(new Date());
}}
>
<motion.span
className={
"block min-w-2 min-h-2 rounded-full mx-1 transition-colors" +
(props.indicator
? " bg-zinc-300 animate-pulse"
: " bg-transparent")
}
layoutId="datepicker_indicator"
layout="position"
/>
<motion.span
layoutId="datepicker_date"
layout="position"
className="font-semibold"
>
{formatDate(props.date)}
</motion.span>
{dateTag.length > 0 && (
<>
<motion.div
className="flex"
layoutId="datepicker_date_div"
layout="position"
>
<span className="h-[1px] -rotate-50 bg-zinc-800 w-[20px] " />
</motion.div>
<motion.span
initial={{ x: 10, opacity: 0 }}
transition={{ delay: 0.1 }}
animate={{ x: 0, opacity: 1 }}
className="text-zinc-600 italic"
>
{dateTag}
</motion.span>
</>
)}
</motion.span>
</AnimatePresence>
<DatePickerButton next date={props.date} setDate={props.setDate} />
</div>
);
}
export function DengiButton({
onClick,
children,
disabled = false,
className = "",
}) {
return (
<span
role="button"
className={
"flex bg-black items-center justify-center border p-1 gap-2 px-2 border-white " +
(disabled
? "cursor-not-allowed text-zinc-700 border-zinc-900 md:hover:border-red-950/50 "
: "not-disabled:cursor-pointer md:not-hover:border-zinc-700 md:not-hover:text-zinc-400 text-white ") +
"rounded-xl transition-colors h-10 min-w-10 not-md:p-2 " +
(className ? className : "")
}
aria-disabled={disabled}
onClick={disabled ? null : onClick}
>
{children}
</span>
);
}
// BAD IDEA::
//
// export function CoolMouseBg() {
// const x = useSpring(0, { stiffness: 200, damping: 40 });
// const y = useSpring(0, { stiffness: 200, damping: 40 });
// const [visible, setVisible] = useState(false);
// useEffect(() => {
// const move = (e) => {
// if (visible) {
// x.set(e.clientX - 25);
// y.set(e.clientY - 25);
// } else {
// setVisible(true);
// }
// };
// window.addEventListener("mousemove", move);
// return () => {
// window.removeEventListener("mousemove", move);
// };
// }, [visible]);
// return (
// <div className="not-md:hidden w-full h-full -z-2 overflow-hidden absolute top-0 left-0">
// <motion.span
// className="w-[50px] h-[50px] blur-3xl bg-white absolute rounded-full"
// style={{
// top: y,
// left: x,
// }}
// initial={{ opacity: 0 }}
// animate={{ opacity: visible ? 1 : 0 }}
// transition={{ duration: 0.5, delay: 1 }}
// />
// </div>
// );
// }
export function DengiYesOrNoDialog({
content = {
message: "?",
yesBtn: "da",
noBtn: "net",
bgDissmis: true,
yesIcon: <BiCheck />,
noIcon: <BiX />,
noBtnStyle: "",
yesBtnStyle: "",
},
show,
onAnswer,
}) {
return (
<>
{/* Background */}
<AnimatePresence>
{show && (
<motion.div
variants={{ on: { opacity: 1 }, off: { opacity: 0 } }}
initial="off"
animate="on"
exit="off"
className="fixed z-99 bg-black/50 backdrop-blur-xl top-0 left-0 w-full h-full overflow-hidden flex items-center justify-center"
onClick={(e) => {
if (e.target === e.currentTarget && content.bgDissmis)
onAnswer(false);
}}
>
<motion.div
variants={{
on: { filter: "blur(0px)", scale: 1, y: 0, opacity: 1 },
off: { filter: "blur(2px) ", scale: 0.7, y: 10, opacity: 0 },
}}
initial="off"
animate="on"
exit="off"
className="flex flex-col justify-center gap-4 p-4 border bg-black border-zinc-400 rounded-2xl"
>
<span>{content.message}</span>
<div className="flex gap-2 justify-stretch">
<DengiButton
className={content.yesBtnStyle + " w-full"}
onClick={() => onAnswer(true)}
>
{content.yesIcon}
{content.yesBtn}
</DengiButton>
<DengiButton
className={content.noBtnStyle + " w-full"}
onClick={() => onAnswer(false)}
>
{content.noIcon}
{content.noBtn}
</DengiButton>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</>
);
}