-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathField.astro
More file actions
216 lines (196 loc) · 9.23 KB
/
Copy pathField.astro
File metadata and controls
216 lines (196 loc) · 9.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
---
import { toLocalInput, type Field } from "@/lib/admin";
import { imageSrc } from "@/lib/ui";
interface Props {
field: Field;
value?: unknown;
}
const { field, value } = Astro.props;
const base =
"w-full bg-ink-900 border border-line rounded-xl px-3.5 py-2.5 text-sm text-ink-text placeholder:text-ink-faint focus:border-violet outline-none transition-colors";
const str = value == null ? "" : String(value);
const num = Number(value);
const preview = field.type === "image" && str ? imageSrc(str) : "";
---
<label class:list={["block", field.full && "md:col-span-2"]}>
<span class="block text-sm text-ink-dim mb-1.5 font-medium">
{field.label}
{field.required && <span class="text-coral">*</span>}
</span>
{field.type === "textarea" && (
<textarea name={field.name} rows="3" class={base} placeholder={field.placeholder} required={field.required}>{str}</textarea>
)}
{field.type === "markdown" && (
<div class="space-y-1.5">
<textarea name={field.name} rows="12" data-md-upload class={`${base} font-mono text-[0.82rem] leading-6`} placeholder="# Markdown supported…">{str}</textarea>
<span class="block text-xs text-ink-faint">Görsel yapıştır (Ctrl/⌘+V) ya da sürükle-bırak — otomatik yüklenir ve markdown olarak eklenir.</span>
</div>
)}
{(field.type === "select" || field.type === "color") && (
<select name={field.name} class={base}>
{(field.options ?? []).map((o) => (
<option value={o.value} selected={str === o.value}>{o.label}</option>
))}
</select>
)}
{field.type === "boolean" && (
<div class="flex items-center gap-2.5 pt-1">
<input type="checkbox" name={field.name} value="1" checked={value == null ? field.default === 1 : num === 1} class="w-4 h-4 accent-violet" />
<span class="text-sm text-ink-dim">Enabled</span>
</div>
)}
{field.type === "datetime" && (
<input type="datetime-local" name={field.name} value={toLocalInput(value as number)} class={base} />
)}
{field.type === "number" && (
<input type="number" name={field.name} value={Number.isFinite(num) ? num : 0} class={base} />
)}
{field.type === "image" && (
<div class="space-y-2">
{preview && <img src={preview} alt="" class="h-24 rounded-lg border border-line object-cover" />}
<input type="text" name={field.name} value={str} class={base} placeholder="https://… or leave blank and upload below" />
<input type="file" name={`${field.name}_file`} accept="image/*" class="block text-xs text-ink-dim file:mr-3 file:rounded-lg file:border-0 file:bg-ink-800 file:px-3 file:py-1.5 file:text-ink-text" />
</div>
)}
{(field.type === "text" || field.type === "tags") && (
<input type="text" name={field.name} value={str} class={base} placeholder={field.placeholder ?? (field.type === "tags" ? "comma, separated, tags" : "")} required={field.required} />
)}
{field.help && <span class="block text-xs text-ink-faint mt-1.5">{field.help}</span>}
</label>
{field.type === "markdown" && (
<script is:inline>
(() => {
if (window.__mdUpload) return;
window.__mdUpload = true;
const isMd = (el) => el && el.tagName === "TEXTAREA" && el.hasAttribute("data-md-upload");
const insertAt = (ta, text) => {
const s = ta.selectionStart, e = ta.selectionEnd;
ta.value = ta.value.slice(0, s) + text + ta.value.slice(e);
ta.selectionStart = ta.selectionEnd = s + text.length;
};
const replaceToken = (ta, token, repl) => {
const i = ta.value.indexOf(token);
if (i !== -1) ta.value = ta.value.slice(0, i) + repl + ta.value.slice(i + token.length);
return i !== -1;
};
async function upload(ta, file) {
const token = "![yükleniyor… " + Math.random().toString(36).slice(2, 8) + "]()";
insertAt(ta, (ta.value && !ta.value.endsWith("\n") ? "\n" : "") + token + "\n");
try {
const fd = new FormData();
fd.append("file", file, file.name || "pasted.png");
const r = await fetch("/admin/upload", { method: "POST", body: fd });
const j = await r.json().catch(() => ({}));
if (j.ok) replaceToken(ta, token, "");
else { replaceToken(ta, token, ""); alert(j.error || "Yükleme başarısız."); }
} catch {
replaceToken(ta, token, "");
alert("Yükleme hatası.");
}
}
document.addEventListener("paste", (e) => {
const ta = document.activeElement;
if (!isMd(ta)) return;
const imgs = [...((e.clipboardData && e.clipboardData.items) || [])].filter((i) => i.kind === "file" && i.type.startsWith("image/"));
if (!imgs.length) return;
e.preventDefault();
imgs.forEach((i) => { const f = i.getAsFile(); if (f) upload(ta, f); });
});
document.addEventListener("dragover", (e) => { if (isMd(e.target)) e.preventDefault(); });
document.addEventListener("drop", (e) => {
const ta = e.target;
if (!isMd(ta)) return;
const files = [...((e.dataTransfer && e.dataTransfer.files) || [])].filter((f) => f.type.startsWith("image/"));
if (!files.length) return;
e.preventDefault();
files.forEach((f) => upload(ta, f));
});
})();
</script>
)}
{field.type === "image" && (
<script is:inline>
(() => {
if (window.__imgShrink) return;
window.__imgShrink = true;
// Downscale in the browser BEFORE the form is submitted. This is not a
// nicety: `uploadImage()` in lib/admin.ts puts the File into R2 with no
// size check at all, so without this a 12MB shoot original would be
// stored and then served, byte for byte, by /media/<key>. ADR 0002 says
// Drive keeps the originals and R2 only ever holds web derivatives —
// this is where that rule is actually enforced.
const MAX = 2000; // long edge, px
const QUALITY = 0.82;
// Left alone on purpose: vectors have no pixels to shrink, and a canvas
// round-trip would flatten an animated GIF to its first frame.
const PASS = /^image\/(svg\+xml|gif)$/;
const target = (() => {
const c = document.createElement("canvas");
return c.toDataURL("image/webp").startsWith("data:image/webp")
? { type: "image/webp", ext: "webp" }
: { type: "image/jpeg", ext: "jpg" };
})();
const fmt = (b) => (b > 1048576 ? (b / 1048576).toFixed(1) + "MB" : Math.round(b / 1024) + "KB");
async function shrink(file) {
if (!file.type.startsWith("image/") || PASS.test(file.type)) return null;
// `imageOrientation: "from-image"` bakes the EXIF rotation into the
// bitmap. Without it every portrait frame off a phone or DSLR uploads
// sideways — a canvas ignores the EXIF tag, and the tag is lost on
// re-encode, so the mistake is permanent.
const bmp = await createImageBitmap(file, { imageOrientation: "from-image" });
const scale = Math.min(1, MAX / Math.max(bmp.width, bmp.height));
const w = Math.round(bmp.width * scale);
const h = Math.round(bmp.height * scale);
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
canvas.getContext("2d").drawImage(bmp, 0, 0, w, h);
bmp.close();
const blob = await new Promise((r) => canvas.toBlob(r, target.type, QUALITY));
// Already web-sized and the re-encode bought nothing — keep the original
// rather than paying a generation of quality for no bytes.
if (!blob || (scale === 1 && blob.size >= file.size)) return null;
const base = (file.name || "photo").replace(/\.[^.]+$/, "");
return new File([blob], base + "." + target.ext, { type: target.type });
}
const noteFor = (el) => {
let n = el.nextElementSibling;
if (!n || !n.classList.contains("shrink-note")) {
n = document.createElement("span");
n.className = "shrink-note block text-xs text-ink-faint mt-1.5";
el.after(n);
}
return n;
};
const bind = () => {
document.querySelectorAll('input[type="file"][accept="image/*"]').forEach((el) => {
if (el.dataset.shrinkBound) return;
el.dataset.shrinkBound = "1";
el.addEventListener("change", async () => {
const file = el.files && el.files[0];
if (!file) return;
const note = noteFor(el);
note.textContent = "küçültülüyor…";
try {
const out = await shrink(file);
if (out) {
const dt = new DataTransfer();
dt.items.add(out);
el.files = dt.files;
note.textContent = fmt(file.size) + " → " + fmt(out.size) + " · " + target.ext;
} else {
note.textContent = fmt(file.size) + " · olduğu gibi gönderilecek";
}
} catch {
// Never block the upload on a resize failure — an oversized photo
// beats no photo, and the note says which one happened.
note.textContent = "küçültülemedi — orijinal gönderilecek";
}
});
});
};
document.addEventListener("astro:page-load", bind);
bind();
})();
</script>
)}