1442 lines
49 KiB
JavaScript
1442 lines
49 KiB
JavaScript
"use strict";
|
||
(() => {
|
||
const $ = (id) => document.getElementById(id);
|
||
const sdk = window.Eitaa?.WebApp;
|
||
const native = Boolean(
|
||
sdk?.initData && sdk.platform && sdk.platform !== "unknown",
|
||
);
|
||
const android = native && /android/i.test(sdk.platform);
|
||
let csrf = document.querySelector('meta[name="csrf-token"]').content;
|
||
let authenticated = false,
|
||
authExpiry = 0,
|
||
currentCategory = "overview",
|
||
currentFilter = "all";
|
||
let listening = false,
|
||
eventTotal = 0,
|
||
toastTimer,
|
||
themeOverride = false;
|
||
const actions = new Map(),
|
||
subscriptions = [],
|
||
clickHandlers = new Map();
|
||
const fa = new Intl.NumberFormat("fa-IR");
|
||
const categories = [
|
||
["overview", "نمای کلی", "◫"],
|
||
["all", "همهٔ آزمایشها", "⌘"],
|
||
["interface", "رابط و ظاهر", "◈"],
|
||
["interaction", "تعامل با کاربر", "☷"],
|
||
["device", "دستگاه و حسگرها", "◎"],
|
||
["connection", "لینک و فایل", "↗"],
|
||
["security", "هویت و پیام", "◇"],
|
||
["inspector", "دادهها و رویدادها", "≋"],
|
||
];
|
||
const esc = (s) =>
|
||
String(s).replace(
|
||
/[&<>"']/g,
|
||
(c) =>
|
||
({
|
||
"&": "&",
|
||
"<": "<",
|
||
">": ">",
|
||
'"': """,
|
||
"'": "'",
|
||
})[c],
|
||
);
|
||
const compact = (value) => JSON.stringify(value, null, 2);
|
||
function toast(message) {
|
||
$("toast").textContent = message;
|
||
$("toast").hidden = false;
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(() => ($("toast").hidden = true), 4200);
|
||
}
|
||
function safeLog(value) {
|
||
return (
|
||
JSON.stringify(
|
||
value,
|
||
(key, item) =>
|
||
/hash|token|initData|contact|phone|response|user|device_id|query_id|chat_instance/i.test(
|
||
key,
|
||
)
|
||
? "[private]"
|
||
: item,
|
||
2,
|
||
)?.slice(0, 1400) ?? ""
|
||
);
|
||
}
|
||
function log(name, value = "", error = false) {
|
||
const container = $("event-log");
|
||
container.querySelector(".log-empty")?.remove();
|
||
const row = document.createElement("div");
|
||
row.className = `log-row${error ? " error" : ""}`;
|
||
const time = document.createElement("time");
|
||
time.textContent = new Date().toLocaleTimeString("en-GB");
|
||
const content = document.createElement("div"),
|
||
title = document.createElement("strong"),
|
||
detail = document.createElement("p");
|
||
title.textContent = name;
|
||
detail.textContent =
|
||
typeof value === "string" ? value.slice(0, 1000) : safeLog(value);
|
||
content.append(title, detail);
|
||
row.append(time, content);
|
||
container.prepend(row);
|
||
while (container.children.length > 80) container.lastElementChild.remove();
|
||
$("event-count").textContent = fa.format(++eventTotal);
|
||
}
|
||
function result(id, message, error = false) {
|
||
const target = $(`${id}-result`);
|
||
if (target) {
|
||
target.textContent =
|
||
typeof message === "string" ? message : compact(message);
|
||
target.className = `result ${error ? "error" : "success"}`;
|
||
}
|
||
}
|
||
function fail(id, error) {
|
||
const message = error.message || "اجرای آزمایش ممکن نشد.";
|
||
result(id, message, true);
|
||
log(id, message, true);
|
||
toast(message);
|
||
}
|
||
function resolve(path) {
|
||
// Documentation spells FullScreen differently from the current official SDK.
|
||
if (path === "requestFullScreen")
|
||
path = sdk?.requestFullscreen ? "requestFullscreen" : path;
|
||
if (path === "exitFullScreen")
|
||
path = sdk?.exitFullscreen ? "exitFullscreen" : path;
|
||
const parts = path.split(".");
|
||
const name = parts.pop();
|
||
return { owner: parts.reduce((obj, key) => obj?.[key], sdk), name };
|
||
}
|
||
function availability(path, version = "1.0", androidOnly = false) {
|
||
if (!native) return "این قابلیت را از داخل ایتا اجرا کنید.";
|
||
if (androidOnly && !android)
|
||
return "طبق مستندات، این قابلیت فقط در ایتای اندروید در دسترس است.";
|
||
if (sdk.isVersionAtLeast && !sdk.isVersionAtLeast(version))
|
||
return `این قابلیت به SDK نسخهٔ ${version} یا جدیدتر نیاز دارد.`;
|
||
const { owner, name } = resolve(path);
|
||
if (typeof owner?.[name] !== "function")
|
||
return "این نسخهٔ ایتا از این متد پشتیبانی نمیکند.";
|
||
return "";
|
||
}
|
||
function call(id, path, args = [], version = "1.0", androidOnly = false) {
|
||
const reason = availability(path, version, androidOnly);
|
||
if (reason) throw new Error(reason);
|
||
const { owner, name } = resolve(path);
|
||
result(
|
||
id,
|
||
"درخواست به ایتا فرستاده شد؛ نتیجهٔ بومی یا رویداد را بررسی کنید.",
|
||
);
|
||
log(path, "درخواست ارسال شد");
|
||
const response = owner[name](...args);
|
||
refreshInspector();
|
||
return response;
|
||
}
|
||
async function api(action, payload = {}) {
|
||
const response = await fetch("api.php", {
|
||
method: "POST",
|
||
credentials: "same-origin",
|
||
cache: "no-store",
|
||
headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf },
|
||
body: JSON.stringify({ action, ...payload }),
|
||
signal: AbortSignal.timeout(18000),
|
||
});
|
||
let data;
|
||
try {
|
||
data = await response.json();
|
||
} catch {
|
||
throw new Error(
|
||
"پاسخ سرور قابل خواندن نیست. تنظیمات PHP هاست را بررسی کنید.",
|
||
);
|
||
}
|
||
if (!response.ok || !data.ok) {
|
||
if (response.status === 401) {
|
||
authenticated = false;
|
||
updateAuth();
|
||
}
|
||
throw new Error(data.error || "درخواست انجام نشد.");
|
||
}
|
||
return data;
|
||
}
|
||
function needAuth() {
|
||
if (!authenticated || Date.now() >= authExpiry)
|
||
throw new Error("ابتدا در بخش «هویت و پیام» ورود امن را انجام دهید.");
|
||
}
|
||
const value = (id) => $(id).value;
|
||
const checkbox = (id) => $(id).checked;
|
||
function field(id, label, initial = "", type = "text", extra = "") {
|
||
return `<label class="control-label">${label}<input id="${id}" type="${type}" value="${esc(initial)}" ${extra}></label>`;
|
||
}
|
||
function select(id, label, options) {
|
||
return `<label class="control-label">${label}<select id="${id}">${options
|
||
.map((option) => {
|
||
const [v, t] = Array.isArray(option) ? option : [option, option];
|
||
return `<option value="${esc(v)}">${esc(t)}</option>`;
|
||
})
|
||
.join("")}</select></label>`;
|
||
}
|
||
function check(id, label, checked = false) {
|
||
return `<label class="control-label"><input id="${id}" type="checkbox" ${checked ? "checked" : ""}>${label}</label>`;
|
||
}
|
||
function button(id, label, handler, style = "") {
|
||
const key = `${id}-${actions.size}`;
|
||
actions.set(key, { id, handler });
|
||
return `<button class="lab-button ${style}" data-action="${key}">${label}</button>`;
|
||
}
|
||
const row = (...items) => `<div class="button-row">${items.join("")}</div>`;
|
||
const simple = (
|
||
id,
|
||
label,
|
||
path,
|
||
args = [],
|
||
version = "1.0",
|
||
androidOnly = false,
|
||
style = "",
|
||
) =>
|
||
button(id, label, () => call(id, path, args, version, androidOnly), style);
|
||
const cards = [];
|
||
function card(
|
||
id,
|
||
category,
|
||
title,
|
||
description,
|
||
method,
|
||
icon,
|
||
color,
|
||
body,
|
||
options = {},
|
||
) {
|
||
cards.push({
|
||
id,
|
||
category,
|
||
title,
|
||
description,
|
||
method,
|
||
icon,
|
||
color,
|
||
body,
|
||
...options,
|
||
});
|
||
}
|
||
|
||
card(
|
||
"appearance",
|
||
"interface",
|
||
"رنگِ حال و هوای شما",
|
||
"ظاهر برنامه را با رنگ دلخواه بسازید؛ یا آن را با تم ایتا هماهنگ کنید.",
|
||
"themeParams · setHeaderColor()",
|
||
"◈",
|
||
"violet",
|
||
`<div class="field-row">${field("accent-color", "رنگ انتخابی", "#476c51", "color")}${select(
|
||
"color-target",
|
||
"محل اعمال",
|
||
[
|
||
["setHeaderColor", "سربرگ"],
|
||
["setBackgroundColor", "پسزمینه"],
|
||
["setBottomBarColor", "نوار پایین · 1.3"],
|
||
],
|
||
)}</div>` +
|
||
row(
|
||
button(
|
||
"appearance",
|
||
"اعمال رنگ",
|
||
() =>
|
||
call(
|
||
"appearance",
|
||
value("color-target"),
|
||
[value("accent-color")],
|
||
value("color-target") === "setBottomBarColor" ? "1.3" : "1.0",
|
||
),
|
||
"main",
|
||
),
|
||
button("appearance", "همگامسازی تم", () => {
|
||
themeOverride = false;
|
||
syncTheme();
|
||
result(
|
||
"appearance",
|
||
native ? "تم ایتا اعمال شد." : "تم پیشفرض مرورگر اعمال شد.",
|
||
);
|
||
}),
|
||
) +
|
||
'<div class="theme-swatches" id="theme-swatches"></div>',
|
||
{ featured: true },
|
||
);
|
||
|
||
function nativeButton(kind, title) {
|
||
const id = kind === "MainButton" ? "main-button" : "secondary-button";
|
||
const version = kind === "SecondaryButton" ? "1.3" : "1.0";
|
||
const handler = () => {
|
||
result(id, "دکمهٔ بومی لمس شد.");
|
||
log(`${kind}.click`);
|
||
toast("کلیک دکمهٔ بومی دریافت شد.");
|
||
};
|
||
clickHandlers.set(kind, handler);
|
||
card(
|
||
id,
|
||
"interface",
|
||
title,
|
||
"متن، رنگ، وضعیت و نشانگر بارگذاری دکمهٔ بومی را تغییر دهید.",
|
||
`${kind}.setParams()`,
|
||
kind === "MainButton" ? "▰" : "▱",
|
||
"mint",
|
||
field(
|
||
`${id}-text`,
|
||
"متن دکمه",
|
||
kind === "MainButton" ? "بزن بریم!" : "کمی بعد",
|
||
"text",
|
||
'maxlength="64"',
|
||
) +
|
||
`<div class="field-row">${field(`${id}-color`, "رنگ دکمه", kind === "MainButton" ? "#397057" : "#e5eedc", "color")}${field(`${id}-text-color`, "رنگ متن", kind === "MainButton" ? "#ffffff" : "#254a39", "color")}</div>` +
|
||
(kind === "SecondaryButton"
|
||
? select(`${id}-position`, "جایگاه نسبت به دکمهٔ اصلی", [
|
||
"left",
|
||
"right",
|
||
"top",
|
||
"bottom",
|
||
]) + check(`${id}-shine`, "افکت درخشش")
|
||
: "") +
|
||
row(
|
||
button(
|
||
id,
|
||
"نمایش و اعمال",
|
||
() => {
|
||
call(
|
||
id,
|
||
`${kind}.setParams`,
|
||
[
|
||
{
|
||
text: value(`${id}-text`),
|
||
color: value(`${id}-color`),
|
||
text_color: value(`${id}-text-color`),
|
||
is_visible: true,
|
||
is_active: true,
|
||
...(kind === "SecondaryButton"
|
||
? {
|
||
position: value(`${id}-position`),
|
||
has_shine_effect: checkbox(`${id}-shine`),
|
||
}
|
||
: {}),
|
||
},
|
||
],
|
||
version,
|
||
);
|
||
},
|
||
"main",
|
||
),
|
||
simple(id, "پنهان", `${kind}.hide`, [], version),
|
||
) +
|
||
row(
|
||
simple(id, "فعال", `${kind}.enable`, [], version),
|
||
simple(id, "غیرفعال", `${kind}.disable`, [], version),
|
||
simple(id, "بارگذاری", `${kind}.showProgress`, [false], version),
|
||
simple(id, "پایان بارگذاری", `${kind}.hideProgress`, [], version),
|
||
) +
|
||
`<details class="details"><summary>متن و رویداد کلیک</summary>${row(
|
||
button(id, "فقط تغییر متن", () =>
|
||
call(id, `${kind}.setText`, [value(`${id}-text`)], version),
|
||
),
|
||
button(id, "اتصال کلیک", () => {
|
||
call(id, `${kind}.offClick`, [handler], version);
|
||
call(id, `${kind}.onClick`, [handler], version);
|
||
}),
|
||
simple(id, "قطع کلیک", `${kind}.offClick`, [handler], version),
|
||
)}</details>`,
|
||
{ featured: kind === "MainButton", version },
|
||
);
|
||
}
|
||
nativeButton("MainButton", "یک دکمه، کلی امکان");
|
||
nativeButton("SecondaryButton", "دکمهٔ دوم، انتخاب بیشتر");
|
||
|
||
for (const [kind, title, icon] of [
|
||
["BackButton", "یک قدم به عقب", "↪"],
|
||
["SettingsButton", "تنظیمات در دسترس", "⚙"],
|
||
]) {
|
||
const id = kind === "BackButton" ? "back-button" : "settings-button";
|
||
const handler = () => {
|
||
navigate(kind === "BackButton" ? "overview" : "interface");
|
||
log(`${kind}.click`);
|
||
toast(title);
|
||
};
|
||
clickHandlers.set(kind, handler);
|
||
card(
|
||
id,
|
||
"interface",
|
||
title,
|
||
"دکمهٔ بومی را نمایش دهید و اتصال یا حذف رویداد کلیک را آزمایش کنید.",
|
||
`${kind}.show() · onClick()`,
|
||
icon,
|
||
"blue",
|
||
row(
|
||
simple(id, "نمایش", `${kind}.show`, [], "1.0", false, "main"),
|
||
simple(id, "پنهان", `${kind}.hide`),
|
||
) +
|
||
row(
|
||
button(id, "اتصال کلیک", () => {
|
||
call(id, `${kind}.offClick`, [handler]);
|
||
call(id, `${kind}.onClick`, [handler]);
|
||
}),
|
||
simple(id, "قطع کلیک", `${kind}.offClick`, [handler]),
|
||
),
|
||
);
|
||
}
|
||
|
||
function previewDialog(title, message, options) {
|
||
return new Promise((resolve) => {
|
||
const dialog = $("demo-dialog");
|
||
$("dialog-title").textContent = title;
|
||
$("dialog-message").textContent = message;
|
||
$("dialog-buttons").replaceChildren();
|
||
for (const [id, label] of options) {
|
||
const b = document.createElement("button");
|
||
b.className = "primary";
|
||
b.value = id;
|
||
b.textContent = label;
|
||
$("dialog-buttons").append(b);
|
||
}
|
||
dialog.returnValue = "";
|
||
dialog.addEventListener("close", () => resolve(dialog.returnValue), {
|
||
once: true,
|
||
});
|
||
dialog.showModal();
|
||
});
|
||
}
|
||
card(
|
||
"dialogs",
|
||
"interaction",
|
||
"گفتوگو از همینجا شروع میشود",
|
||
"هشدار، تأیید یا یک پنجرهٔ سهانتخابی؛ واکنش بومی ایتا را ببینید.",
|
||
"showPopup() · showAlert() · showConfirm()",
|
||
"▤",
|
||
"peach",
|
||
field(
|
||
"popup-message",
|
||
"پیام پنجره",
|
||
"آمادهای یک ایدهٔ تازه را امتحان کنی؟",
|
||
"text",
|
||
'maxlength="256"',
|
||
) +
|
||
row(
|
||
...[
|
||
["alert", "هشدار"],
|
||
["confirm", "تأیید"],
|
||
["popup", "سه انتخاب"],
|
||
].map(([type, label]) =>
|
||
button("dialogs", label, async () => {
|
||
const message = value("popup-message").trim();
|
||
if (!message) throw new Error("متن پیام را وارد کنید.");
|
||
const done = (response) => {
|
||
result("dialogs", {
|
||
mode: native ? "Eitaa" : "پیشنمایش مرورگر",
|
||
response: response ?? "closed",
|
||
});
|
||
log(`dialog.${type}`, response ?? "closed");
|
||
};
|
||
if (!native) {
|
||
done(
|
||
await previewDialog(
|
||
"پیشنمایش مرورگر",
|
||
message,
|
||
type === "alert"
|
||
? [["ok", "متوجه شدم"]]
|
||
: type === "confirm"
|
||
? [
|
||
["yes", "بله"],
|
||
["cancel", "انصراف"],
|
||
]
|
||
: [
|
||
["explore", "کشف کنیم"],
|
||
["later", "بعداً"],
|
||
["cancel", "انصراف"],
|
||
],
|
||
),
|
||
);
|
||
return;
|
||
}
|
||
if (type === "alert") call("dialogs", "showAlert", [message, done]);
|
||
else if (type === "confirm")
|
||
call("dialogs", "showConfirm", [message, done]);
|
||
else
|
||
call("dialogs", "showPopup", [
|
||
{
|
||
title: "یک ایدهٔ تازه",
|
||
message,
|
||
buttons: [
|
||
{ id: "explore", type: "default", text: "کشف کنیم" },
|
||
{ id: "later", type: "default", text: "بعداً" },
|
||
{ id: "cancel", type: "cancel" },
|
||
],
|
||
},
|
||
done,
|
||
]);
|
||
}),
|
||
),
|
||
),
|
||
{ featured: true, preview: true },
|
||
);
|
||
|
||
card(
|
||
"haptics",
|
||
"interaction",
|
||
"قابلیتها را لمس کنید",
|
||
"ضربههای سبک و سنگین یا بازخورد موفقیت و خطا را احساس کنید.",
|
||
"HapticFeedback",
|
||
"↯",
|
||
"violet",
|
||
`<div class="field-row">${select("impact-style", "نوع ضربه", ["light", "medium", "heavy", "rigid", "soft"])}${select("notification-type", "نوع اعلان", ["success", "warning", "error"])}</div>` +
|
||
row(
|
||
button(
|
||
"haptics",
|
||
"ضربه",
|
||
() =>
|
||
call("haptics", "HapticFeedback.impactOccurred", [
|
||
value("impact-style"),
|
||
]),
|
||
"main",
|
||
),
|
||
button("haptics", "اعلان", () =>
|
||
call("haptics", "HapticFeedback.notificationOccurred", [
|
||
value("notification-type"),
|
||
]),
|
||
),
|
||
) +
|
||
select("haptic-selection", "انتخاب را تغییر دهید (selectionChanged)", [
|
||
["one", "گزینهٔ اول"],
|
||
["two", "گزینهٔ دوم"],
|
||
["three", "گزینهٔ سوم"],
|
||
]),
|
||
);
|
||
|
||
card(
|
||
"viewport",
|
||
"device",
|
||
"فضای بیشتری برای ایدهها",
|
||
"گسترش صفحه، تمامصفحه و قفل چرخش؛ اندازهٔ تجربه را تغییر دهید.",
|
||
"expand() · requestFullScreen()",
|
||
"⛶",
|
||
"blue",
|
||
row(
|
||
simple("viewport", "گسترش", "expand", [], "1.0", true, "main"),
|
||
simple("viewport", "تمامصفحه", "requestFullScreen", [], "1.3"),
|
||
simple("viewport", "خروج", "exitFullScreen", [], "1.3"),
|
||
) +
|
||
row(
|
||
simple("viewport", "قفل چرخش", "lockOrientation", [], "1.3", true),
|
||
simple(
|
||
"viewport",
|
||
"آزادسازی چرخش",
|
||
"unlockOrientation",
|
||
[],
|
||
"1.3",
|
||
true,
|
||
),
|
||
) +
|
||
'<p class="helper">قفل چرخش و گسترش: اندروید · تمامصفحه: نسخهٔ 1.3</p>',
|
||
);
|
||
card(
|
||
"lifecycle",
|
||
"device",
|
||
"رفتار برنامه در دستان شما",
|
||
"آمادهبودن، تأیید خروج و ژستهای عمودی را کنترل کنید.",
|
||
"ready() · close() · enableClosingConfirmation()",
|
||
"⌁",
|
||
"peach",
|
||
row(
|
||
simple("lifecycle", "اعلام آمادگی", "ready"),
|
||
button(
|
||
"lifecycle",
|
||
"بستن برنامه",
|
||
async () => {
|
||
if (!native)
|
||
throw new Error("بستن برنامه فقط از داخل ایتا ممکن است.");
|
||
const answer = await previewDialog(
|
||
"خروج از مدار",
|
||
"این کار برنامک را در ایتا میبندد.",
|
||
[
|
||
["close", "بستن برنامه"],
|
||
["cancel", "انصراف"],
|
||
],
|
||
);
|
||
if (answer === "close") call("lifecycle", "close");
|
||
},
|
||
"danger",
|
||
),
|
||
) +
|
||
row(
|
||
simple("lifecycle", "تأیید خروج: روشن", "enableClosingConfirmation"),
|
||
simple("lifecycle", "تأیید خروج: خاموش", "disableClosingConfirmation"),
|
||
) +
|
||
row(
|
||
simple(
|
||
"lifecycle",
|
||
"سوایپ: روشن",
|
||
"enableVerticalSwipes",
|
||
[],
|
||
"1.0",
|
||
true,
|
||
),
|
||
simple(
|
||
"lifecycle",
|
||
"سوایپ: خاموش",
|
||
"disableVerticalSwipes",
|
||
[],
|
||
"1.0",
|
||
true,
|
||
),
|
||
),
|
||
);
|
||
card(
|
||
"home",
|
||
"device",
|
||
"مدار، یک لمس نزدیکتر",
|
||
"برنامک را به صفحهٔ اصلی اضافه کنید و وضعیت میانبر را ببینید.",
|
||
"addToHomeScreen() · checkHomeScreenStatus()",
|
||
"⌂",
|
||
"mint",
|
||
row(
|
||
simple(
|
||
"home",
|
||
"افزودن به صفحهٔ اصلی",
|
||
"addToHomeScreen",
|
||
[],
|
||
"1.3",
|
||
true,
|
||
"main",
|
||
),
|
||
button("home", "بررسی وضعیت", () =>
|
||
call(
|
||
"home",
|
||
"checkHomeScreenStatus",
|
||
[
|
||
(status) => {
|
||
result("home", status);
|
||
log("homeScreenStatus", status);
|
||
},
|
||
],
|
||
"1.3",
|
||
true,
|
||
),
|
||
),
|
||
),
|
||
{ androidOnly: true, version: "1.3" },
|
||
);
|
||
|
||
card(
|
||
"qr",
|
||
"interaction",
|
||
"یک کد، یک کشف تازه",
|
||
"اسکنر دوربین ایتا را باز کنید. محتوای کد فقط نمایش داده میشود.",
|
||
"showScanQrPopup() · closeScanQrPopup()",
|
||
"▦",
|
||
"mint",
|
||
row(
|
||
button(
|
||
"qr",
|
||
"شروع اسکن",
|
||
() =>
|
||
call(
|
||
"qr",
|
||
"showScanQrPopup",
|
||
[
|
||
{ text: "یک کد QR را داخل کادر قرار دهید" },
|
||
(text) => {
|
||
result(
|
||
"qr",
|
||
`متن اسکنشده (تأییدنشده):\n${String(text).slice(0, 2000)}`,
|
||
);
|
||
log("QR received", "متن اسکن شد؛ در گزارش ذخیره نمیشود.");
|
||
return true;
|
||
},
|
||
],
|
||
"1.0",
|
||
true,
|
||
),
|
||
"main",
|
||
),
|
||
simple("qr", "بستن اسکنر", "closeScanQrPopup", [], "1.0", true),
|
||
),
|
||
{ androidOnly: true },
|
||
);
|
||
|
||
for (const [kind, title, icon, unit] of [
|
||
["Accelerometer", "حرکت را به تصویر بکشید", "◎", "m/s²"],
|
||
["Gyroscope", "چرخش در سه محور", "⟳", "rad/s"],
|
||
["DeviceOrientation", "جهتِ تازهای پیدا کنید", "⌖", "rad"],
|
||
]) {
|
||
const id = kind.toLowerCase();
|
||
card(
|
||
id,
|
||
"device",
|
||
title,
|
||
"حسگر دستگاه را روشن کنید و تغییرات واقعی را زنده ببینید.",
|
||
`${kind}.start() · stop()`,
|
||
icon,
|
||
"blue",
|
||
`<div class="sensor-stage"><span class="sensor-ball" id="${id}-ball"></span></div><div class="sensor-readout" id="${id}-values">— / — / — ${unit}</div>` +
|
||
field(
|
||
`${id}-rate`,
|
||
"فاصلهٔ نمونهبرداری (میلیثانیه)",
|
||
"200",
|
||
"number",
|
||
'min="20" max="1000" step="10"',
|
||
) +
|
||
(kind === "DeviceOrientation"
|
||
? check(`${id}-absolute`, "جهت مطلق نسبت به شمال مغناطیسی")
|
||
: "") +
|
||
row(
|
||
button(
|
||
id,
|
||
"شروع حسگر",
|
||
() => {
|
||
const rate = Number(value(`${id}-rate`));
|
||
if (!Number.isInteger(rate) || rate < 20 || rate > 1000)
|
||
throw new Error("فاصله باید بین ۲۰ تا ۱۰۰۰ میلیثانیه باشد.");
|
||
call(
|
||
id,
|
||
`${kind}.start`,
|
||
[
|
||
{
|
||
refresh_rate: rate,
|
||
...(kind === "DeviceOrientation"
|
||
? { need_absolute: checkbox(`${id}-absolute`) }
|
||
: {}),
|
||
},
|
||
(started) => {
|
||
result(
|
||
id,
|
||
started
|
||
? "حسگر فعال شد."
|
||
: "حسگر فعال نشد؛ پشتیبانی و مجوز دستگاه را بررسی کنید.",
|
||
!started,
|
||
);
|
||
},
|
||
],
|
||
"1.3",
|
||
true,
|
||
);
|
||
},
|
||
"main",
|
||
),
|
||
simple(
|
||
id,
|
||
"توقف",
|
||
`${kind}.stop`,
|
||
[
|
||
(stopped) =>
|
||
result(id, stopped ? "حسگر متوقف شد." : "توقف تأیید نشد."),
|
||
],
|
||
"1.3",
|
||
true,
|
||
),
|
||
),
|
||
{ androidOnly: true, version: "1.3", featured: kind === "Accelerometer" },
|
||
);
|
||
}
|
||
|
||
async function authenticate() {
|
||
if (!native)
|
||
throw new Error("برای ورود امن، این برنامه را از داخل ایتا باز کنید.");
|
||
const data = await api("authenticate", { initData: sdk.initData });
|
||
authenticated = true;
|
||
authExpiry = data.expires * 1000;
|
||
updateAuth(data.user);
|
||
result("identity", {
|
||
verified: true,
|
||
user: data.user,
|
||
context: data.context,
|
||
expires: new Date(authExpiry).toLocaleString("fa-IR"),
|
||
remoteVerified: data.remoteVerified,
|
||
});
|
||
result("messages", "ورود تأیید شد. پس از دادن مجوز، پیام را ارسال کنید.");
|
||
log("authentication", "امضا و زمان ورود در سرور تأیید شد.");
|
||
}
|
||
function updateAuth(user) {
|
||
$("auth-status").textContent = authenticated ? "تأییدشده" : "مهمان";
|
||
$("auth-caption").textContent = authenticated
|
||
? String(user?.first_name || "ورود امن فعال است")
|
||
: "هنوز وارد نشدهاید";
|
||
}
|
||
card(
|
||
"identity",
|
||
"security",
|
||
"اعتماد از اینجا شروع میشود",
|
||
"امضای ورود و تاریخ آن در سرور بررسی میشود؛ سپس هویت تأییدشده را میبینید.",
|
||
"initData → PHP → HMAC-SHA256",
|
||
"◇",
|
||
"mint",
|
||
row(
|
||
button("identity", "تأیید ورود", authenticate, "main"),
|
||
button("identity", "پایان نشست", async () => {
|
||
const data = await api("logout");
|
||
csrf = data.csrf;
|
||
authenticated = false;
|
||
authExpiry = 0;
|
||
updateAuth();
|
||
for (const id of ["identity", "permissions", "messages"])
|
||
result(id, "نشست پایان یافت.");
|
||
log("logout");
|
||
}),
|
||
) +
|
||
'<p class="helper">توکن فقط در سرور است. ورود تازه: ۵ دقیقه · نشست: ۱ ساعت</p>',
|
||
{ featured: true },
|
||
);
|
||
card(
|
||
"authenticity",
|
||
"security",
|
||
"یک لایه اطمینان بیشتر",
|
||
"اصالت همین ورود را یک بار از سرور ایتایار بپرسید؛ در دقیقهٔ اول اجرا کنید.",
|
||
"POST /api/app/verify",
|
||
"⬡",
|
||
"blue",
|
||
row(
|
||
button(
|
||
"authenticity",
|
||
"اصالتسنجی با ایتایار",
|
||
async () => {
|
||
needAuth();
|
||
const data = await api("verify");
|
||
result("authenticity", data.message);
|
||
log("verify", "اصالت تأیید شد.");
|
||
},
|
||
"main",
|
||
),
|
||
) +
|
||
'<p class="helper">هر hash فقط یک بار قابل تأیید است. نتیجهٔ موفق در نشست نگهداری میشود.</p>',
|
||
);
|
||
card(
|
||
"permissions",
|
||
"security",
|
||
"ارتباط، با اجازهٔ شما",
|
||
"اجازهٔ پیام یا اشتراک تماس را درخواست کنید. تماس امضاشده در سرور بررسی میشود.",
|
||
"requestWriteAccess() · requestContact()",
|
||
"♧",
|
||
"violet",
|
||
row(
|
||
button(
|
||
"permissions",
|
||
"اجازهٔ ارسال پیام",
|
||
() =>
|
||
call("permissions", "requestWriteAccess", [
|
||
(allowed) => {
|
||
result(
|
||
"permissions",
|
||
allowed ? "اجازهٔ ارسال پیام داده شد." : "درخواست مجوز رد شد.",
|
||
);
|
||
log("write access", { allowed });
|
||
},
|
||
]),
|
||
"main",
|
||
),
|
||
button("permissions", "اشتراک تماس", () => {
|
||
needAuth();
|
||
call("permissions", "requestContact", [
|
||
async (sent, details) => {
|
||
try {
|
||
if (!sent) {
|
||
result("permissions", "اشتراک تماس لغو شد.");
|
||
return;
|
||
}
|
||
const raw =
|
||
typeof details === "string" ? details : details?.response;
|
||
if (!raw)
|
||
throw new Error("این کلاینت دادهٔ امضاشدهٔ تماس را برنگرداند.");
|
||
const data = await api("contact", { contactData: raw });
|
||
result("permissions", { verified: true, contact: data.contact });
|
||
log("contact verification", "تماس امضاشده تأیید شد.");
|
||
} catch (error) {
|
||
fail("permissions", error);
|
||
}
|
||
},
|
||
]);
|
||
}),
|
||
) +
|
||
'<p class="helper">شمارهٔ تماس در فایل یا گزارش رویداد ذخیره نمیشود.</p>',
|
||
);
|
||
card(
|
||
"messages",
|
||
"security",
|
||
"یک سلام، از سمت سرور",
|
||
"یک پیام واقعی به حساب ایتای خود بفرستید و مسیر کامل ارتباط را تجربه کنید.",
|
||
"POST /api/app/sendMessage",
|
||
"✉",
|
||
"peach",
|
||
'<label class="control-label">متن پیام<textarea id="message-text" maxlength="1000">سلام از مدار! 🌱\nاین اولین پیام من از آزمایشگاه برنامک ایتاست.</textarea></label>' +
|
||
row(
|
||
button(
|
||
"messages",
|
||
"ارسال به خودم ↗",
|
||
async () => {
|
||
needAuth();
|
||
const text = value("message-text").trim();
|
||
if (!text) throw new Error("متن پیام را بنویسید.");
|
||
const data = await api("sendMessage", { text });
|
||
result("messages", data.message);
|
||
log("sendMessage", "ارسال به کاربر تأییدشده موفق بود.");
|
||
},
|
||
"main",
|
||
),
|
||
) +
|
||
'<p class="helper">نیازمند ورود و مجوز پیام · هر کاربر: ۵ تلاش در ساعت · هر پیام از اعتبار برنامه کسر میشود.</p>',
|
||
{ featured: true },
|
||
);
|
||
|
||
function httpsUrl(input, eitaaOnly = false) {
|
||
let url;
|
||
try {
|
||
url = new URL(input);
|
||
} catch {
|
||
throw new Error("یک آدرس کامل و معتبر وارد کنید.");
|
||
}
|
||
if (url.protocol !== "https:" || url.username || url.password)
|
||
throw new Error("آدرس باید HTTPS و بدون نام کاربری و رمز باشد.");
|
||
if (eitaaOnly && !["eitaa.com", "www.eitaa.com"].includes(url.hostname))
|
||
throw new Error("برای لینک داخلی از دامنهٔ eitaa.com استفاده کنید.");
|
||
return url.href;
|
||
}
|
||
card(
|
||
"links",
|
||
"connection",
|
||
"درهای تازه باز کنید",
|
||
"یک صفحهٔ وب یا لینک داخلی ایتا را با گزینههای دلخواه باز کنید.",
|
||
"openLink() · openEitaaLink()",
|
||
"↗",
|
||
"blue",
|
||
field(
|
||
"external-url",
|
||
"آدرس وب",
|
||
"https://developer.eitaa.com",
|
||
"url",
|
||
'dir="ltr"',
|
||
) +
|
||
check("instant-view", "تلاش برای نمایش Instant View") +
|
||
check("try-browser", "باز کردن در مرورگر پیشفرض · 1.3") +
|
||
row(
|
||
button(
|
||
"links",
|
||
"باز کردن صفحهٔ وب",
|
||
() => {
|
||
const url = httpsUrl(value("external-url"));
|
||
call(
|
||
"links",
|
||
"openLink",
|
||
[
|
||
url,
|
||
{
|
||
try_instant_view: checkbox("instant-view"),
|
||
try_browser: checkbox("try-browser"),
|
||
},
|
||
],
|
||
checkbox("try-browser") ? "1.3" : "1.0",
|
||
);
|
||
},
|
||
"main",
|
||
),
|
||
) +
|
||
field(
|
||
"eitaa-url",
|
||
"لینک داخلی ایتا",
|
||
"https://eitaa.com",
|
||
"url",
|
||
'dir="ltr"',
|
||
) +
|
||
row(
|
||
button("links", "باز کردن در ایتا", () =>
|
||
call("links", "openEitaaLink", [httpsUrl(value("eitaa-url"), true)]),
|
||
),
|
||
),
|
||
);
|
||
card(
|
||
"download",
|
||
"connection",
|
||
"یک یادگاری از مدار",
|
||
"فایل نمونهٔ مدار یا یک فایل HTTPS دلخواه را با دانلود بومی دریافت کنید.",
|
||
"downloadFile({url, file_name})",
|
||
"⇣",
|
||
"mint",
|
||
field(
|
||
"download-url",
|
||
"آدرس HTTPS فایل",
|
||
new URL("sample.php", location.href).href,
|
||
"url",
|
||
'dir="ltr"',
|
||
) +
|
||
field(
|
||
"download-name",
|
||
"نام فایل",
|
||
"madar-postcard.svg",
|
||
"text",
|
||
'dir="ltr" maxlength="80"',
|
||
) +
|
||
row(
|
||
button(
|
||
"download",
|
||
"دریافت فایل",
|
||
() => {
|
||
const name = value("download-name").trim();
|
||
if (!name || /[\\/\x00-\x1f]/.test(name))
|
||
throw new Error("نام فایل معتبر نیست.");
|
||
call(
|
||
"download",
|
||
"downloadFile",
|
||
[
|
||
{ url: httpsUrl(value("download-url")), file_name: name },
|
||
(started) =>
|
||
result(
|
||
"download",
|
||
started ? "دانلود شروع شد." : "دانلود لغو شد.",
|
||
),
|
||
],
|
||
"1.4",
|
||
true,
|
||
);
|
||
},
|
||
"main",
|
||
),
|
||
),
|
||
{ androidOnly: true, version: "1.4" },
|
||
);
|
||
|
||
card(
|
||
"inspector",
|
||
"inspector",
|
||
"پشت صحنهٔ این تجربه",
|
||
"نسخه، پلتفرم، ابعاد، ناحیهٔ امن، تم و وضعیت همهٔ کنترلها را زنده ببینید.",
|
||
"WebApp properties · isVersionAtLeast()",
|
||
"≋",
|
||
"violet",
|
||
`<div class="field-row">${field("version-check", "نسخهٔ مورد بررسی", "1.3", "text", 'dir="ltr" maxlength="12"')}${button(
|
||
"inspector",
|
||
"بررسی نسخه",
|
||
() => {
|
||
if (!/^\d+(\.\d+){0,2}$/.test(value("version-check")))
|
||
throw new Error("نسخه را مانند 1.3 وارد کنید.");
|
||
const supported = call("inspector", "isVersionAtLeast", [
|
||
value("version-check"),
|
||
]);
|
||
result("inspector", { version: value("version-check"), supported });
|
||
},
|
||
)}</div>` +
|
||
row(
|
||
button("inspector", "تازهسازی دادهها", () => {
|
||
refreshInspector();
|
||
result("inspector", "دادهها تازه شدند.");
|
||
}),
|
||
) +
|
||
'<pre class="inspector" id="state-inspector"></pre><p class="helper">initDataUnsafe قابل اعتماد نیست و برای احراز هویت استفاده نمیشود. hash و دادهٔ خام ورود نمایش داده نمیشوند.</p>',
|
||
);
|
||
card(
|
||
"event-tools",
|
||
"inspector",
|
||
"به نبض برنامه گوش کنید",
|
||
"همهٔ رویدادهای مستند را مشاهده کنید؛ شنیدن رویدادها را متوقف و دوباره وصل کنید.",
|
||
"onEvent(event, handler) · offEvent(event, handler)",
|
||
"⌁",
|
||
"mint",
|
||
row(
|
||
button(
|
||
"event-tools",
|
||
"اتصال رویدادها",
|
||
() => {
|
||
listen(true);
|
||
result(
|
||
"event-tools",
|
||
native
|
||
? "شنیدن رویدادها فعال شد."
|
||
: "رویدادهای بومی نیازمند ایتا هستند.",
|
||
);
|
||
},
|
||
"main",
|
||
),
|
||
button("event-tools", "قطع رویدادها", () => {
|
||
listen(false);
|
||
result("event-tools", "شنیدن رویدادهای بومی متوقف شد.");
|
||
}),
|
||
) +
|
||
'<details class="details"><summary>رویدادهای پوششدادهشده</summary><pre class="inspector" id="event-names"></pre></details>',
|
||
);
|
||
|
||
for (const [index, [id, title, icon]] of categories.entries()) {
|
||
const button = document.createElement("button");
|
||
button.className = `nav-item${index === 0 ? " active" : ""}`;
|
||
button.dataset.category = id;
|
||
button.innerHTML = `<span class="nav-icon">${icon}</span><span>${title}</span><span class="nav-number">${String(index + 1).padStart(2, "0")}</span>`;
|
||
button.setAttribute("aria-current", index === 0 ? "page" : "false");
|
||
$("navigation").append(button);
|
||
}
|
||
$("filters").innerHTML = [
|
||
["all", "همه"],
|
||
["available", "قابل اجرا"],
|
||
["android", "فقط اندروید"],
|
||
]
|
||
.map(
|
||
([id, label]) =>
|
||
`<button class="filter${id === "all" ? " active" : ""}" data-filter="${id}" aria-pressed="${id === "all"}">${label}</button>`,
|
||
)
|
||
.join("");
|
||
$("cards").innerHTML = cards
|
||
.map(
|
||
(c) =>
|
||
`<article class="feature-card" id="card-${c.id}" aria-labelledby="title-${c.id}"><div class="card-top"><span class="card-icon ${c.color}" aria-hidden="true">${c.icon}</span><span class="tag ${native && (!c.androidOnly || android) ? "ready" : ""}">${c.androidOnly ? "Android" : c.preview && !native ? "پیشنمایش مرورگر" : c.version ? `SDK ${c.version}` : c.category === "security" ? "سمت سرور" : "Eitaa SDK"}</span></div><h3 id="title-${c.id}">${c.title}</h3><p class="card-description">${c.description}</p><div class="method-line">${esc(c.method)}</div><div class="controls">${c.body}<div class="result" id="${c.id}-result" role="status"></div></div></article>`,
|
||
)
|
||
.join("");
|
||
$("feature-count").textContent = fa.format(cards.length);
|
||
function filterCards() {
|
||
const search = value("search").trim().toLowerCase();
|
||
let count = 0;
|
||
for (const c of cards) {
|
||
const available =
|
||
c.category === "inspector" ||
|
||
c.preview ||
|
||
(native &&
|
||
(!c.androidOnly || android) &&
|
||
(!c.version || sdk.isVersionAtLeast?.(c.version)));
|
||
const category =
|
||
search ||
|
||
currentCategory === "all" ||
|
||
(currentCategory === "overview"
|
||
? c.featured
|
||
: c.category === currentCategory);
|
||
const text =
|
||
`${c.title} ${c.description} ${c.method} ${$("card-" + c.id).textContent}`.toLowerCase();
|
||
const visible = Boolean(
|
||
category &&
|
||
(!search || text.includes(search)) &&
|
||
(currentFilter === "all" ||
|
||
(currentFilter === "available" && available) ||
|
||
(currentFilter === "android" && c.androidOnly)),
|
||
);
|
||
$("card-" + c.id).hidden = !visible;
|
||
if (visible) count++;
|
||
}
|
||
$("result-count").textContent = `${fa.format(count)} آزمایش`;
|
||
$("empty").hidden = count !== 0;
|
||
}
|
||
function navigate(category) {
|
||
currentCategory = category;
|
||
currentFilter = "all";
|
||
$("search").value = "";
|
||
const title = categories.find((c) => c[0] === category)?.[1] || "نمای کلی";
|
||
$("breadcrumb").textContent = title;
|
||
$("section-title").textContent =
|
||
category === "overview" ? "از اینجا شروع کنید ✦" : title;
|
||
$("section-description").textContent =
|
||
category === "overview"
|
||
? "چند تجربهٔ منتخب برای اولین دور در مدار."
|
||
: "آزمایش را اجرا کنید و نتیجه را در همان کارت یا نبض مدار ببینید.";
|
||
$("hero").hidden = category !== "overview";
|
||
document.querySelectorAll("[data-category]").forEach((b) => {
|
||
const active = b.dataset.category === category;
|
||
b.classList.toggle("active", active);
|
||
b.setAttribute("aria-current", active ? "page" : "false");
|
||
});
|
||
document.querySelectorAll("[data-filter]").forEach((b) => {
|
||
const active = b.dataset.filter === "all";
|
||
b.classList.toggle("active", active);
|
||
b.setAttribute("aria-pressed", String(active));
|
||
});
|
||
filterCards();
|
||
}
|
||
$("navigation").addEventListener("click", (e) => {
|
||
const b = e.target.closest("[data-category]");
|
||
if (b) navigate(b.dataset.category);
|
||
});
|
||
$("filters").addEventListener("click", (e) => {
|
||
const b = e.target.closest("[data-filter]");
|
||
if (!b) return;
|
||
currentFilter = b.dataset.filter;
|
||
document.querySelectorAll("[data-filter]").forEach((item) => {
|
||
item.classList.toggle("active", item === b);
|
||
item.setAttribute("aria-pressed", String(item === b));
|
||
});
|
||
filterCards();
|
||
});
|
||
$("search").addEventListener("input", filterCards);
|
||
$("cards").addEventListener("click", async (e) => {
|
||
const target = e.target.closest("[data-action]");
|
||
if (!target) return;
|
||
const action = actions.get(target.dataset.action);
|
||
if (!action) return;
|
||
target.disabled = true;
|
||
try {
|
||
await action.handler();
|
||
} catch (error) {
|
||
fail(action.id, error);
|
||
} finally {
|
||
target.disabled = false;
|
||
}
|
||
});
|
||
$("haptic-selection").addEventListener("change", () => {
|
||
try {
|
||
call("haptics", "HapticFeedback.selectionChanged");
|
||
} catch (error) {
|
||
fail("haptics", error);
|
||
}
|
||
});
|
||
$("explore").addEventListener("click", () => {
|
||
navigate("all");
|
||
$("section-title").scrollIntoView({ behavior: "smooth", block: "start" });
|
||
});
|
||
$("show-session").addEventListener("click", () => navigate("security"));
|
||
$("notice-close").addEventListener(
|
||
"click",
|
||
() => ($("mode-notice").hidden = true),
|
||
);
|
||
$("theme-toggle").addEventListener("click", () => {
|
||
themeOverride = true;
|
||
for (const property of ["--bg", "--text", "--muted", "--panel"])
|
||
document.body.style.removeProperty(property);
|
||
document.body.classList.toggle("dark");
|
||
refreshInspector();
|
||
toast(
|
||
document.body.classList.contains("dark")
|
||
? "تم تیره فعال شد."
|
||
: "تم روشن فعال شد.",
|
||
);
|
||
});
|
||
document.addEventListener("keydown", (e) => {
|
||
if (
|
||
e.key === "/" &&
|
||
!/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName)
|
||
) {
|
||
e.preventDefault();
|
||
$("search").focus();
|
||
}
|
||
});
|
||
|
||
function syncTheme() {
|
||
if (!themeOverride)
|
||
document.body.classList.toggle(
|
||
"dark",
|
||
native
|
||
? sdk.colorScheme === "dark"
|
||
: matchMedia("(prefers-color-scheme: dark)").matches,
|
||
);
|
||
const theme = native ? sdk.themeParams || {} : {};
|
||
$("theme-swatches").replaceChildren();
|
||
for (const [key, color] of Object.entries(theme)) {
|
||
if (!/^#[0-9a-f]{6}$/i.test(color)) continue;
|
||
const swatch = document.createElement("span");
|
||
swatch.className = "swatch";
|
||
swatch.style.backgroundColor = color;
|
||
swatch.title = `${key}: ${color}`;
|
||
swatch.setAttribute("aria-label", swatch.title);
|
||
$("theme-swatches").append(swatch);
|
||
}
|
||
if (native && !themeOverride) {
|
||
for (const [key, variable] of [
|
||
["bg_color", "--bg"],
|
||
["text_color", "--text"],
|
||
["hint_color", "--muted"],
|
||
["section_bg_color", "--panel"],
|
||
]) {
|
||
const color = theme[key];
|
||
if (/^#[0-9a-f]{6}$/i.test(color || ""))
|
||
document.body.style.setProperty(variable, color);
|
||
}
|
||
}
|
||
}
|
||
function refreshInspector() {
|
||
if (!$("state-inspector")) return;
|
||
const data = {
|
||
environment: native ? "Eitaa" : "Browser preview",
|
||
version: sdk?.version ?? null,
|
||
platform: native ? sdk.platform : "browser",
|
||
colorScheme: native
|
||
? sdk.colorScheme
|
||
: document.body.classList.contains("dark")
|
||
? "dark"
|
||
: "light",
|
||
initDataPresent: Boolean(sdk?.initData),
|
||
initDataUnsafe: "Untrusted — never used for authentication",
|
||
};
|
||
if (native) {
|
||
for (const key of [
|
||
"themeParams",
|
||
"isExpanded",
|
||
"isActive",
|
||
"isFullscreen",
|
||
"isOrientationLocked",
|
||
"bottomBarColor",
|
||
"viewportHeight",
|
||
"viewportStableHeight",
|
||
"headerColor",
|
||
"backgroundColor",
|
||
"isClosingConfirmationEnabled",
|
||
"isVerticalSwipesEnabled",
|
||
"safeAreaInset",
|
||
"contentSafeAreaInset",
|
||
])
|
||
data[key] = sdk[key] ?? null;
|
||
for (const key of [
|
||
"MainButton",
|
||
"SecondaryButton",
|
||
"BackButton",
|
||
"SettingsButton",
|
||
"Accelerometer",
|
||
"Gyroscope",
|
||
"DeviceOrientation",
|
||
]) {
|
||
data[key] = {};
|
||
for (const prop of [
|
||
"type",
|
||
"text",
|
||
"color",
|
||
"textColor",
|
||
"isVisible",
|
||
"isActive",
|
||
"hasShineEffect",
|
||
"position",
|
||
"isProgressVisible",
|
||
"isStarted",
|
||
"x",
|
||
"y",
|
||
"z",
|
||
"alpha",
|
||
"beta",
|
||
"gamma",
|
||
"absolute",
|
||
])
|
||
if (sdk[key]?.[prop] !== undefined) data[key][prop] = sdk[key][prop];
|
||
}
|
||
} else data.viewport = { width: innerWidth, height: innerHeight };
|
||
$("state-inspector").textContent = compact(data);
|
||
}
|
||
const events = [
|
||
"themeChanged",
|
||
"viewportChanged",
|
||
"activated",
|
||
"deactivated",
|
||
"safeAreaChanged",
|
||
"contentSafeAreaChanged",
|
||
"mainButtonClicked",
|
||
"secondaryButtonClicked",
|
||
"backButtonClicked",
|
||
"settingsButtonClicked",
|
||
"popupClosed",
|
||
"qrTextReceived",
|
||
"scanQrPopupClosed",
|
||
"writeAccessRequested",
|
||
"contactRequested",
|
||
"fullscreenChanged",
|
||
"fullscreenFailed",
|
||
"homeScreenAdded",
|
||
"homeScreenChecked",
|
||
];
|
||
$("event-names").textContent = events.join("\n");
|
||
for (const event of events) {
|
||
subscriptions.push([
|
||
event,
|
||
(data) => {
|
||
if (event === "themeChanged") syncTheme();
|
||
refreshInspector();
|
||
log(
|
||
event,
|
||
event === "qrTextReceived"
|
||
? "محتوای QR در گزارش ذخیره نمیشود."
|
||
: event === "contactRequested"
|
||
? { status: data?.status }
|
||
: (data ?? "received"),
|
||
);
|
||
},
|
||
]);
|
||
}
|
||
function listen(enabled) {
|
||
if (!native) {
|
||
$("event-toggle").textContent = "نیازمند ایتا";
|
||
return;
|
||
}
|
||
if (listening === enabled) return;
|
||
for (const [name, handler] of subscriptions) {
|
||
try {
|
||
sdk[enabled ? "onEvent" : "offEvent"](name, handler);
|
||
} catch (error) {
|
||
log(name, "اتصال رویداد در این نسخه ممکن نیست.", true);
|
||
}
|
||
}
|
||
listening = enabled;
|
||
$("event-toggle").textContent = enabled ? "توقف شنیدن" : "ادامهٔ شنیدن";
|
||
}
|
||
$("event-toggle").addEventListener("click", () => listen(!listening));
|
||
$("clear-events").addEventListener("click", () => {
|
||
$("event-log").replaceChildren();
|
||
eventTotal = 0;
|
||
$("event-count").textContent = "۰";
|
||
});
|
||
const sensors = ["Accelerometer", "Gyroscope", "DeviceOrientation"];
|
||
function stopSensors() {
|
||
if (!native) return;
|
||
for (const kind of sensors) {
|
||
try {
|
||
if (sdk[kind]?.isStarted) sdk[kind].stop();
|
||
} catch {
|
||
/* Client may already be closing. */
|
||
}
|
||
}
|
||
}
|
||
function updateSensors() {
|
||
for (const kind of sensors) {
|
||
const sensor = native ? sdk[kind] : null;
|
||
if (!sensor) continue;
|
||
const id = kind.toLowerCase();
|
||
const keys =
|
||
kind === "DeviceOrientation"
|
||
? ["alpha", "beta", "gamma"]
|
||
: ["x", "y", "z"];
|
||
const numbers = keys.map((key) => Number(sensor[key] ?? 0));
|
||
$(`${id}-values`).textContent =
|
||
keys
|
||
.map((key, index) => `${key}: ${numbers[index].toFixed(2)}`)
|
||
.join(" ") +
|
||
(kind === "DeviceOrientation"
|
||
? ` | absolute: ${Boolean(sensor.absolute)}`
|
||
: "");
|
||
$(`${id}-ball`).style.transform =
|
||
`translate(${Math.max(-65, Math.min(65, numbers[0] * 9))}px,${Math.max(-35, Math.min(35, numbers[1] * 9))}px)`;
|
||
}
|
||
}
|
||
document.addEventListener("visibilitychange", () => {
|
||
if (document.hidden) stopSensors();
|
||
});
|
||
window.addEventListener("pagehide", () => {
|
||
stopSensors();
|
||
listen(false);
|
||
for (const [kind, handler] of clickHandlers) {
|
||
try {
|
||
sdk?.[kind]?.offClick(handler);
|
||
} catch {}
|
||
}
|
||
});
|
||
setInterval(() => {
|
||
if (document.hidden) return;
|
||
updateSensors();
|
||
if (authenticated && Date.now() >= authExpiry) {
|
||
authenticated = false;
|
||
updateAuth();
|
||
result(
|
||
"identity",
|
||
"نشست منقضی شد. برنامه را دوباره از ایتا باز کنید.",
|
||
true,
|
||
);
|
||
}
|
||
}, 250);
|
||
$("environment").innerHTML =
|
||
`<i></i>${native ? "متصل به ایتا" : "پیشنمایش مرورگر"}`;
|
||
$("environment").classList.toggle("connected", native);
|
||
$("sdk-version").textContent = native ? sdk.version : "Preview";
|
||
if (native) {
|
||
$("mode-notice").querySelector("p").textContent =
|
||
"به مدار خوش آمدید. قابلیتهای وابسته به نسخه و دستگاه هنگام اجرا بررسی میشوند.";
|
||
for (const [kind, handler] of clickHandlers) {
|
||
try {
|
||
sdk[kind]?.onClick(handler);
|
||
} catch {}
|
||
}
|
||
try {
|
||
sdk.ready();
|
||
} catch (error) {
|
||
log("ready", error.message, true);
|
||
}
|
||
listen(true);
|
||
}
|
||
syncTheme();
|
||
refreshInspector();
|
||
filterCards();
|
||
if (native) authenticate().catch((error) => fail("identity", error));
|
||
})();
|