Widget សម្រាប់ iPhone

បង្ហាញតម្លៃមាសហាងលើអេក្រង់ iPhone តាមរយៈ App Scriptable (ឥតគិតថ្លៃ)

▶មើលវីដេអូបង្រៀនចលនា 3D · ៨ ជំហាន · ប្រហែល ៣៥ វិនាទី
  1. ដំឡើង Scriptable ពី App Store
  2. ចុចប៊ូតុង ចម្លងកូដ ខាងក្រោម
  3. បើក Scriptable → ចុច + ជ្រុងខាងលើស្តាំ → Paste កូដ → ប្តូរឈ្មោះ script ជា មាសថ្ងៃនេះ → Done
  4. ចុចឱ្យជាប់លើអេក្រង់ដើម → ចុច Edit / + → រក Scriptable → ជ្រើសទំហំ (តូច / មធ្យម / ធំ) → Add Widget
  5. ចុចលើ Widget ដែលទើបដាក់ → Script: ជ្រើស មាសថ្ងៃនេះ → When Interacting: Open URL
// មាសថ្ងៃនេះ — iPhone widget for the Scriptable app
// Shows today's shop gold prices from https://measthngainis.pages.dev
// Sizes: small, medium, large, and lock screen (rectangular / inline).

// ---------- Font ----------
// "kantumruy": Kantumruy Pro, the same font as the website. Install it on the iPhone first
//              (free app "iFont" → Google Fonts → Kantumruy Pro → Install). Until it is installed,
//              iOS shows its standard Khmer font instead.
// "khmermn":   Khmer MN, built into every iPhone — nothing to install.
// "system":    the iPhone's default font.
const FONT = "khmermn";
const FONT_NAMES = {
  kantumruy: { regular: "KantumruyPro-Regular", semibold: "KantumruyPro-SemiBold", bold: "KantumruyPro-Bold" },
  khmermn: { regular: "KhmerMN", semibold: "KhmerMN-Bold", bold: "KhmerMN-Bold" },
};

const SITE = "https://measthngainis.pages.dev";
const API = SITE + "/api/shop";

const C = {
  bgTop: new Color("#1a3d6b"),
  bgBottom: new Color("#071427"),
  gold: new Color("#e9c46a"),
  goldHi: new Color("#fff1c2"),
  goldLo: new Color("#a87a22"),
  white: Color.white(),
  muted: new Color("#9fb0c8"),
  line: new Color("#e9c46a", 0.25),
  green: new Color("#3ddc84"),
  red: new Color("#ff6b5b"),
};

// ---------- data (keeps the last good copy for when the phone is offline) ----------
const fm = FileManager.local();
const cachePath = fm.joinPath(fm.documentsDirectory(), "measthngainis-cache.json");

async function loadData() {
  try {
    const req = new Request(API);
    req.timeoutInterval = 15;
    const data = await req.loadJSON();
    if (!data || !data.items) throw new Error("bad data");
    fm.writeString(cachePath, JSON.stringify({ at: Date.now(), data }));
    return { data, stale: false };
  } catch (e) {
    if (fm.fileExists(cachePath)) {
      const saved = JSON.parse(fm.readString(cachePath));
      return { data: saved.data, stale: true };
    }
    return null;
  }
}

// ---------- helpers ----------
function phnomPenhTime(ms) {
  const df = new DateFormatter();
  df.dateFormat = "HH:mm";
  df.timeZone = "Asia/Phnom_Penh";
  return df.string(new Date(ms));
}
function phnomPenhDate(ms) {
  const df = new DateFormatter();
  df.dateFormat = "dd/MM/yyyy";
  df.timeZone = "Asia/Phnom_Penh";
  return df.string(new Date(ms));
}
function shortName(name) {
  return name.replace("ផ្លាទីនទឹក", "ទឹក").replace("មាសគីឡូ ", "គីឡូ ");
}
function addText(stack, text, size, color, weight) {
  const t = stack.addText(String(text));
  const f = FONT_NAMES[FONT];
  if (weight === "num") t.font = Font.boldRoundedSystemFont(size); // prices keep clear, even digits
  else if (f) t.font = new Font(f[weight === "bold" ? "bold" : weight === "semibold" ? "semibold" : "regular"], size);
  else t.font = weight === "bold" ? Font.boldSystemFont(size)
              : weight === "semibold" ? Font.semiboldSystemFont(size)
              : Font.systemFont(size);
  t.textColor = color;
  t.lineLimit = 1;
  t.minimumScaleFactor = 0.6;
  return t;
}
function background(w) {
  const g = new LinearGradient();
  g.colors = [new Color("#24508a"), C.bgTop, C.bgBottom];
  g.locations = [0, 0.35, 1];
  g.startPoint = new Point(0.2, 0);
  g.endPoint = new Point(0.8, 1);
  w.backgroundGradient = g;
}
function nextRefresh(data) {
  // ask iOS to refresh soon after the shop's next price change (or in 15 minutes)
  const soon = Date.now() + 15 * 60 * 1000;
  const next = data && data.nextAt ? data.nextAt + 60 * 1000 : soon;
  return new Date(Math.max(Math.min(next, soon), Date.now() + 5 * 60 * 1000));
}
function header(w, data, stale, compact) {
  const h = w.addStack();
  h.centerAlignContent();
  addText(h, "មាសថ្ងៃនេះ", compact ? 12 : 14, C.gold, "bold");
  h.addSpacer();
  const dot = h.addText("●");
  dot.font = Font.systemFont(compact ? 8 : 9);
  dot.textColor = stale ? C.red : C.green;
  h.addSpacer(3);
  const when = data.lockTime || phnomPenhTime(Date.now());
  addText(h, (compact ? "" : "ម៉ោង ") + when, compact ? 10 : 11, C.muted);
}

// ---------- layouts ----------
// Small widget shows one gold type. Pick which one with the widget's Parameter:
// 1 = first row (default), 2 = second, 3 = third, 4 = fourth.
function pickItem(data) {
  const n = parseInt((args.widgetParameter || "").trim(), 10);
  return data.items[(n >= 1 && n <= data.items.length) ? n - 1 : 0];
}

async function loadLogo() {
  // the app icon from the website, saved on the phone after the first download
  const p = fm.joinPath(fm.documentsDirectory(), "measthngainis-logo.png");
  if (fm.fileExists(p)) return fm.readImage(p);
  try {
    const img = await new Request(SITE + "/icon-192.png").loadImage();
    fm.writeImage(p, img);
    return img;
  } catch (e) { return null; }
}

function priceRow(card, label, value, color) {
  const r = card.addStack();
  r.centerAlignContent();
  addText(r, label, 11, C.muted);
  r.addSpacer();
  addText(r, value, 21, color, "num");
}

function smallWidget(w, data, stale, logo) {
  w.setPadding(13, 13, 12, 13);
  const it = pickItem(data);

  // top: logo + brand, live dot + time
  const top = w.addStack();
  top.centerAlignContent();
  if (logo) {
    const im = top.addImage(logo);
    im.imageSize = new Size(18, 18);
    im.cornerRadius = 5;
    top.addSpacer(5);
  }
  addText(top, "មាសថ្ងៃនេះ", 11, C.gold, "bold");
  top.addSpacer();
  const dot = top.addText("●");
  dot.font = Font.systemFont(7);
  dot.textColor = stale ? C.red : C.green;
  top.addSpacer(3);
  addText(top, data.lockTime || phnomPenhTime(Date.now()), 10, C.muted);

  w.addSpacer();

  // gold type
  addText(w, it.name, 14, C.white, "semibold");
  w.addSpacer(3);
  // gold rule + date
  const dateRow = w.addStack();
  dateRow.centerAlignContent();
  const rule = dateRow.addStack();
  rule.size = new Size(18, 2);
  rule.cornerRadius = 1;
  rule.backgroundColor = C.gold;
  dateRow.addSpacer(6);
  addText(dateRow, "ថ្ងៃទី " + (data.lockLabel || phnomPenhDate(Date.now())), 10, C.muted);

  w.addSpacer();

  // price card: sell and buy, like a shop board
  const card = w.addStack();
  card.layoutVertically();
  card.backgroundColor = new Color("#ffffff", 0.08);
  card.borderColor = new Color("#e9c46a", 0.35);
  card.borderWidth = 1;
  card.cornerRadius = 12;
  card.setPadding(6, 10, 6, 10);
  priceRow(card, "លក់ចេញ", it.sell + "$", C.goldHi);
  const sep = card.addStack();
  sep.size = new Size(0, 1);
  sep.backgroundColor = new Color("#e9c46a", 0.2);
  card.addSpacer(1);
  priceRow(card, "ទិញចូល", it.buy == null ? (it.buyNote || "—") : it.buy + "$", C.white);
}

function tableWidget(w, data, stale, large) {
  w.setPadding(14, 16, 14, 16);
  header(w, data, stale, false);
  w.addSpacer(large ? 10 : 6);

  const colW = large ? 70 : 62;
  const head = w.addStack();
  addText(head, "ប្រភេទមាស (១ ជី)", 10, C.muted);
  head.addSpacer();
  const h1 = head.addStack(); h1.size = new Size(colW, 0); h1.addSpacer(); addText(h1, "លក់ចេញ", 10, C.muted);
  const h2 = head.addStack(); h2.size = new Size(colW, 0); h2.addSpacer(); addText(h2, "ទិញចូល", 10, C.muted);
  w.addSpacer(large ? 6 : 3);

  const items = data.items.slice(0, large ? 8 : 4);
  items.forEach((it, i) => {
    if (i > 0) {
      const sep = w.addStack(); sep.size = new Size(0, 1); sep.backgroundColor = C.line;
      w.addSpacer(large ? 6 : 2);
    }
    const r = w.addStack();
    r.centerAlignContent();
    addText(r, large ? it.name : shortName(it.name), large ? 14 : 12, C.white, "semibold");
    r.addSpacer();
    const s = r.addStack(); s.size = new Size(colW, 0); s.addSpacer();
    addText(s, it.sell + "$", large ? 20 : 16, C.goldHi, "num");
    const b = r.addStack(); b.size = new Size(colW, 0); b.addSpacer();
    addText(b, it.buy == null ? (it.buyNote || "—") : it.buy + "$", large ? 20 : (it.buy == null ? 11 : 16), C.white, it.buy == null ? "semibold" : "num");
    w.addSpacer(large ? 6 : 2);
  });

  w.addSpacer();
  const f = w.addStack();
  addText(f, data.lockLabel ? "ថ្ងៃទី " + data.lockLabel : "", 10, C.muted);
  f.addSpacer();
  if (data.nextAt) addText(f, "ប្តូរតម្លៃបន្ទាប់ " + phnomPenhTime(data.nextAt), 10, C.muted);
}

function lockScreenWidget(w, data, family) {
  const it = data.items[0];
  const buy = it.buy == null ? "" : " / " + it.buy;
  if (family === "accessoryInline") {
    addText(w, "មាស " + it.sell + buy + "$", 12, C.white);
    return;
  }
  addText(w, "មាសថ្ងៃនេះ · " + (data.lockTime || ""), 11, C.white, "semibold");
  data.items.slice(0, 2).forEach((x) => {
    addText(w, shortName(x.name) + "  " + x.sell + (x.buy == null ? "" : "/" + x.buy) + "$", 12, C.white);
  });
}

function errorWidget(w) {
  w.setPadding(14, 14, 14, 14);
  addText(w, "មាសថ្ងៃនេះ", 14, C.gold, "bold");
  w.addSpacer(6);
  addText(w, "ទាញតម្លៃមិនបាន", 13, C.white, "semibold");
  addText(w, "ពិនិត្យអ៊ីនធឺណិត ហើយសាកម្តងទៀត", 11, C.muted);
}

// ---------- build ----------
const family = config.widgetFamily || "medium";
const w = new ListWidget();
w.url = SITE;
const result = await loadData();

if (family.startsWith("accessory")) {
  if (result) lockScreenWidget(w, result.data, family);
  else addText(w, "មាសថ្ងៃនេះ —", 12, C.white);
} else {
  background(w);
  if (!result) errorWidget(w);
  else if (family === "small") smallWidget(w, result.data, result.stale, await loadLogo());
  else tableWidget(w, result.data, result.stale, family === "large" || family === "extraLarge");
}
w.refreshAfterDate = nextRefresh(result && result.data);

if (config.runsInWidget) {
  Script.setWidget(w);
} else {
  // Preview when you tap ▶ inside Scriptable
  await w.presentMedium();
}
Script.complete();

← ត្រឡប់ទៅមាសថ្ងៃនេះ