import { sha256 } from "https://denopkg.com/chiefbiiko/sha256@v1.0.0/mod.ts";
import { extractValInfo } from "https://esm.town/v/pomdtr/extractValInfo?v=29";
import { OpenAI } from "https://esm.town/v/std/openai?v=4";
import { ResultSet, sqlite } from "https://esm.town/v/std/sqlite?v=6";
import { Hono } from "npm:hono@3";
import { DOMParser } from "npm:xmldom";
const { name } = extractValInfo(import.meta.url);
const tableName = `${name}_svg_images`;
const heartHashTableName = `${name}_heart_hash`;
function parseResultSet<T>(row: ResultSet): T[] {
return row.rows.map((r) => Object.fromEntries(r.map((c, i) => [row.columns[i], c]))) as T[];
}
const resultSetToSVG = (
result: ResultSet,
): { id: number; parent_id: number; prompt: string; svg_source: string; heart_count: number }[] => {
return parseResultSet(result);
};
const getSVG = async (id: string) => {
let svg = resultSetToSVG(await sqlite.execute({ sql: `SELECT * FROM ${tableName} WHERE id = ?`, args: [id] }));
if (svg.length === 0) return undefined;
return svg[0];
};
const getSVGWithChildren = async (id: string) => {
let [svg, children] = await Promise.all([
getSVG(id),
sqlite.execute({
sql: `SELECT * FROM ${tableName} WHERE parent_id = ? ORDER BY heart_count DESC, RANDOM() LIMIT 100;`,
args: [id],
}),
]);
let parent = undefined;
if (svg.parent_id) { parent = await getSVG(String(svg.parent_id)); }
return { svg, children: resultSetToSVG(children), parent };
};
const getMostPopular = async () => {
return resultSetToSVG(
await sqlite.execute(`SELECT * FROM ${tableName} ORDER BY heart_count DESC, RANDOM() LIMIT 100`),
);
};
const clientJavascript = async () => {
window.switchTab = (event, tabName) => {
var tabs = document.getElementsByClassName("tab");
var tabContents = document.getElementsByClassName("tab-content");
for (var i = 0; i < tabs.length; i++) {
tabs[i].classList.remove("active");
tabContents[i].classList.remove("active");
}
event.currentTarget.classList.add("active");
document.getElementById(tabName).classList.add("active");
};
let submitted = false;
window.submitEdit = async (id, prompt) => {
if (submitted) return;
submitted = true;
document.querySelectorAll("button").forEach((b) => b.classList.add("shimmer"));
if (!prompt) {
prompt = document.getElementById("svgInput").value;
}
let resp = await fetch("/remix/" + id, { method: "POST", body: JSON.stringify({ prompt }) });
const reader = resp.body.getReader();
const decoder = new TextDecoder();
const svgCode = document.getElementById("svgCode");
const svgImage = document.getElementById("svgImage");
let foundSVGEnd = false;
let htmlContent = "";
let jsonResponse = "";
svgCode.textContent = "";