Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

22.2 KB
Raw Blame
'use strict';

(() => {
  const REPO = 'praisesora/inkstudio';
  const RELEASES_PAGE_URL = `https://github.com/${REPO}/releases`;
  const API_URL = `https://api.github.com/repos/${REPO}/releases?per_page=8`;
  const DOWNLOAD_PREFIX = `https://github.com/${REPO}/releases/`;
  const CACHE_KEY = 'inkstudio_releases_v1';
  const CACHE_TTL_MS = 10 * 60 * 1000;

  /* --------------------------------------------------------------------------
   * Utilities
   * -------------------------------------------------------------------------- */
  function safeReleaseUrl(raw) {
    if (typeof raw !== 'string') return RELEASES_PAGE_URL;
    try {
      const parsed = new URL(raw);
      if (parsed.protocol === 'https:' && parsed.href.startsWith(DOWNLOAD_PREFIX)) {
        return parsed.href;
      }
    } catch {
      // fall through
    }
    return RELEASES_PAGE_URL;
  }

  function formatBytes(bytes) {
    if (!Number.isFinite(bytes) || bytes <= 0) return '';
    const units = ['B', 'KB', 'MB', 'GB'];
    let value = bytes;
    let idx = 0;
    while (value >= 1024 && idx < units.length - 1) {
      value /= 1024;
      idx += 1;
    }
    return `${value.toFixed(idx >= 2 ? 1 : 0)} ${units[idx]}`;
  }

  function formatDate(iso) {
    if (!iso) return '';
    const d = new Date(iso);
    if (Number.isNaN(d.getTime())) return '';
    return d.toISOString().slice(0, 10);
  }

  function detectVisitorOS() {
    const uaData = navigator.userAgentData && navigator.userAgentData.platform;
    const raw = (uaData || navigator.platform || navigator.userAgent || '').toLowerCase();
    if (raw.includes('win')) return 'windows';
    if (raw.includes('mac') || raw.includes('darwin')) return 'macos';
    if (raw.includes('linux') || raw.includes('x11')) return 'linux';
    return 'windows';
  }

  function el(tag, className, text) {
    const node = document.createElement(tag);
    if (className) node.className = className;
    if (text !== undefined && text !== null) node.textContent = String(text);
    return node;
  }

  /* --------------------------------------------------------------------------
   * Release Asset Classification
   * -------------------------------------------------------------------------- */
  function isInternalUpdaterAsset(name) {
    const lower = name.toLowerCase();
    return (
      lower === 'latest.json' ||
      lower.endsWith('.sig') ||
      lower.endsWith('.nsis.zip') ||
      lower.endsWith('.msi.zip') ||
      lower.endsWith('.app.tar.gz') ||
      lower.endsWith('.appimage.tar.gz')
    );
  }

  function classifyAsset(asset) {
    const name = String(asset.name || '');
    const lower = name.toLowerCase();
    if (!name || isInternalUpdaterAsset(name)) return null;

    const url = safeReleaseUrl(asset.browser_download_url || asset.url);
    const size = Number(asset.size || 0);
    const downloads = Number(asset.download_count || 0);

    if (lower.endsWith('.exe')) {
      return {
        os: 'windows',
        priority: 1,
        label: 'Windows Installer (NSIS)',
        badge: 'Recommended (.exe)',
        recommended: true,
        name,
        url,
        size,
        downloads,
      };
    }
    if (lower.endsWith('.msi')) {
      return {
        os: 'windows',
        priority: 2,
        label: 'Windows Installer (MSI)',
        badge: 'MSI (x64)',
        recommended: false,
        name,
        url,
        size,
        downloads,
      };
    }
    if (lower.endsWith('.dmg')) {
      const isArm = lower.includes('aarch64') || lower.includes('arm64');
      const isIntel = lower.includes('x64') || lower.includes('x86_64');
      const arch = isArm ? 'Apple Silicon' : isIntel ? 'Intel x64' : 'Universal';
      return {
        os: 'macos',
        priority: isArm ? 1 : 2,
        label: `macOS Disk Image (${arch})`,
        badge: `${arch} (.dmg)`,
        recommended: isArm || (!isArm && !isIntel),
        name,
        url,
        size,
        downloads,
      };
    }
    if (lower.endsWith('.appimage')) {
      return {
        os: 'linux',
        priority: 1,
        label: 'Linux AppImage',
        badge: 'Portable (.AppImage)',
        recommended: true,
        name,
        url,
        size,
        downloads,
      };
    }
    if (lower.endsWith('.deb')) {
      return {
        os: 'linux',
        priority: 2,
        label: 'Debian / Ubuntu Package',
        badge: '.deb',
        recommended: false,
        name,
        url,
        size,
        downloads,
      };
    }
    if (lower.endsWith('.rpm')) {
      return {
        os: 'linux',
        priority: 3,
        label: 'Fedora / RHEL Package',
        badge: '.rpm',
        recommended: false,
        name,
        url,
        size,
        downloads,
      };
    }
    return null;
  }

  function normalizeReleases(rawList) {
    if (!Array.isArray(rawList)) return [];
    return rawList
      .filter((r) => r && !r.draft)
      .map((r) => {
        const assets = Array.isArray(r.assets)
          ? r.assets.map(classifyAsset).filter(Boolean).sort((a, b) => a.priority - b.priority)
          : [];
        return {
          tag: String(r.tag_name || r.tag || ''),
          name: String(r.name || r.tag_name || r.tag || 'Release'),
          publishedAt: String(r.published_at || r.publishedAt || ''),
          prerelease: Boolean(r.prerelease),
          url: safeReleaseUrl(r.html_url || r.url || RELEASES_PAGE_URL),
          body: String(r.body || '').trim(),
          assets,
        };
      })
      .filter((r) => r.tag);
  }

  /* --------------------------------------------------------------------------
   * Release Loader (Static Snapshot + Cached Live GitHub API Fallback)
   * -------------------------------------------------------------------------- */
  async function loadSnapshot() {
    try {
      const res = await fetch('./releases.json', { cache: 'no-cache' });
      if (!res.ok) return null;
      const data = await res.json();
      if (!data || !Array.isArray(data.releases)) return null;
      return {
        generatedAt: data.generatedAt || null,
        releases: normalizeReleases(data.releases),
      };
    } catch {
      return null;
    }
  }

  function readSessionCache() {
    try {
      const raw = sessionStorage.getItem(CACHE_KEY);
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      if (!parsed || Date.now() - parsed.ts > CACHE_TTL_MS) return null;
      return normalizeReleases(parsed.releases);
    } catch {
      return null;
    }
  }

  function writeSessionCache(releases) {
    try {
      sessionStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), releases }));
    } catch {
      // ignore storage quota errors
    }
  }

  async function loadLiveReleases() {
    const cached = readSessionCache();
    if (cached && cached.length > 0) return cached;

    try {
      const controller = new AbortController();
      const timer = window.setTimeout(() => controller.abort(), 6000);
      const res = await fetch(API_URL, {
        headers: { Accept: 'application/vnd.github+json' },
        signal: controller.signal,
      });
      window.clearTimeout(timer);
      if (!res.ok) return null;
      const data = await res.json();
      const normalized = normalizeReleases(data);
      writeSessionCache(normalized);
      return normalized;
    } catch {
      return null;
    }
  }

  /* --------------------------------------------------------------------------
   * Release UI Rendering (Zero innerHTML with untrusted data)
   * -------------------------------------------------------------------------- */
  const releaseState = {
    releases: [],
    activeOs: detectVisitorOS(),
    source: 'snapshot',
  };

  function getLatestStable() {
    return (
      releaseState.releases.find((r) => !r.prerelease) ||
      releaseState.releases[0] ||
      null
    );
  }

  function renderHeaderAndHero() {
    const latest = getLatestStable();
    const heroPill = document.getElementById('hero-release-pill');
    const primaryBtn = document.getElementById('primary-download-btn');
    const primaryLabel = document.getElementById('primary-download-label');
    const primaryMeta = document.getElementById('primary-download-meta');
    const syncStatus = document.getElementById('sync-status');

    if (!latest) {
      if (heroPill) heroPill.textContent = 'GPL-3.0';
      if (primaryBtn) primaryBtn.href = RELEASES_PAGE_URL;
      if (primaryLabel) primaryLabel.textContent = 'View GitHub Releases';
      if (primaryMeta) primaryMeta.textContent = 'Windows installer ready, macOS and Linux build from source, opens .psd, .clip, and .sut';
      if (syncStatus) syncStatus.textContent = 'Waiting for first published release';
      return;
    }

    if (heroPill) heroPill.textContent = latest.tag;
    if (syncStatus) {
      syncStatus.textContent = `Latest release: ${latest.tag}, ${formatDate(latest.publishedAt)}`;
    }

    const visitorOs = detectVisitorOS();
    const osAssets = latest.assets.filter((a) => a.os === visitorOs);
    const preferred = osAssets[0] || latest.assets[0] || null;

    if (preferred && primaryBtn && primaryLabel && primaryMeta) {
      primaryBtn.href = preferred.url;
      const osNames = { windows: 'Windows', macos: 'macOS', linux: 'Linux' };
      const osName = osNames[preferred.os] || 'Desktop';
      primaryLabel.textContent = `Download for ${osName} (${latest.tag})`;
      const parts = [preferred.name];
      if (preferred.size) parts.push(formatBytes(preferred.size));
      parts.push('automatic updates included');
      primaryMeta.textContent = parts.join(', ');
    } else if (primaryBtn && primaryLabel && primaryMeta) {
      primaryBtn.href = latest.url;
      primaryLabel.textContent = `Download ${latest.tag}`;
      primaryMeta.textContent = `Published ${formatDate(latest.publishedAt)} on GitHub Releases`;
    }
  }

  function renderBuildFromSource(container, introText) {
    const wrap = el('div', 'download-empty');
    wrap.appendChild(el('p', 'muted', introText));

    const pre = el('pre', 'code-block');
    pre.textContent =
      'git clone https://github.com/praisesora/inkstudio.git\n' +
      'cd inkstudio\n' +
      'npm install && npm run tauri build';
    wrap.appendChild(pre);

    const req = el(
      'p',
      'muted',
      'Requires Node.js 22+, stable Rust toolchain, and Tauri v2 OS prerequisites.'
    );
    wrap.appendChild(req);
    container.appendChild(wrap);
  }

  function renderDownloadTab(osKey) {
    releaseState.activeOs = osKey;
    document.querySelectorAll('.tab-btn').forEach((btn) => {
      const active = btn.dataset.os === osKey;
      btn.classList.toggle('active', active);
      btn.setAttribute('aria-selected', String(active));
    });

    const container = document.getElementById('download-content');
    if (!container) return;
    container.textContent = '';

    if (osKey === 'source') {
      renderBuildFromSource(
        container,
        'Compile native Windows, macOS, or Linux binaries directly from source:'
      );
      return;
    }

    const latest = getLatestStable();
    if (!latest) {
      const empty = el('div', 'download-empty');
      empty.appendChild(
        el(
          'p',
          'muted',
          'No published release artifacts found yet. Once a GitHub Release is published, installers appear here automatically.'
        )
      );
      const link = el('a', 'btn btn-subtle btn-sm', 'Open GitHub Releases');
      link.href = RELEASES_PAGE_URL;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.style.alignSelf = 'flex-start';
      empty.appendChild(link);
      container.appendChild(empty);
      return;
    }

    const matching = latest.assets.filter((a) => a.os === osKey);
    if (matching.length === 0) {
      const osLabel = osKey === 'macos' ? 'macOS' : osKey === 'linux' ? 'Linux' : 'Windows';
      renderBuildFromSource(
        container,
        `Prebuilt ${osLabel} binaries are not attached to ${latest.tag} yet. Build locally from source or check GitHub Releases:`
      );
      return;
    }

    const list = el('div', 'asset-list');
    for (const asset of matching) {
      const row = el('div', `asset-row${asset.recommended ? ' recommended' : ''}`);

      const info = el('div', 'asset-info');
      const titleLine = el('div', 'asset-title-line');
      titleLine.appendChild(el('span', 'asset-title', asset.label));
      titleLine.appendChild(
        el('span', `badge${asset.recommended ? ' badge-accent' : ''}`, asset.badge)
      );
      info.appendChild(titleLine);
      info.appendChild(el('span', 'asset-filename mono', asset.name));

      const actions = el('div', 'asset-actions');
      const metaParts = [];
      if (asset.size) metaParts.push(formatBytes(asset.size));
      if (asset.downloads > 0) metaParts.push(`${asset.downloads.toLocaleString()} dl`);
      if (metaParts.length) {
        actions.appendChild(el('span', 'asset-size mono', metaParts.join(', ')));
      }

      const btn = el(
        'a',
        `btn ${asset.recommended ? 'btn-accent' : 'btn-subtle'} btn-sm`,
        'Download'
      );
      btn.href = asset.url;
      actions.appendChild(btn);

      row.appendChild(info);
      row.appendChild(actions);
      list.appendChild(row);
    }

    container.appendChild(list);
  }

  function appendInlineFormattedText(parent, text) {
    const tokens = String(text || '').split(/(`[^`]+`|\*\*[^*]+\*\*)/g);
    for (const token of tokens) {
      if (!token) continue;
      if (token.length >= 2 && token.startsWith('`') && token.endsWith('`')) {
        parent.appendChild(el('code', 'release-notes-code mono', token.slice(1, -1)));
      } else if (token.length >= 4 && token.startsWith('**') && token.endsWith('**')) {
        parent.appendChild(el('strong', 'release-notes-strong', token.slice(2, -2)));
      } else {
        parent.appendChild(document.createTextNode(token));
      }
    }
  }

  function renderReleaseNotesBody(body) {
    const container = el('div', 'release-notes');
    const lines = String(body || '').replace(/\r\n/g, '\n').split('\n');
    const headingToneMap = {
      new: 'new',
      improvements: 'improvements',
      'bug fixes': 'fixes',
      other: 'other',
    };

    let currentSection = null;
    let currentList = null;

    function ensureSection() {
      if (!currentSection) {
        currentSection = el('div', 'release-notes-section');
        container.appendChild(currentSection);
      }
      return currentSection;
    }

    for (const rawLine of lines) {
      const trimmed = rawLine.trim();
      if (!trimmed) {
        currentList = null;
        continue;
      }

      const headingMatch = /^#{2,4}\s+(.+)$/.exec(trimmed);
      if (headingMatch) {
        const title = headingMatch[1].trim();
        const tone = headingToneMap[title.toLowerCase()] || 'default';
        currentSection = el('div', 'release-notes-section');
        currentSection.appendChild(
          el('div', `release-notes-heading release-notes-heading--${tone}`, title)
        );
        container.appendChild(currentSection);
        currentList = null;
        continue;
      }

      const bulletMatch = /^[-*]\s+(.+)$/.exec(trimmed);
      if (bulletMatch) {
        const sec = ensureSection();
        if (!currentList) {
          currentList = el('ul', 'release-notes-list');
          sec.appendChild(currentList);
        }
        const li = el('li', '');
        appendInlineFormattedText(li, bulletMatch[1].trim());
        currentList.appendChild(li);
        continue;
      }

      currentList = null;
      const p = el('p', 'release-notes-para');
      appendInlineFormattedText(p, trimmed);
      ensureSection().appendChild(p);
    }

    return container;
  }

  function renderReleaseHistory() {
    const host = document.getElementById('release-history');
    if (!host) return;
    host.textContent = '';

    if (releaseState.releases.length === 0) {
      const card = el('div', 'release-item');
      card.appendChild(
        el(
          'p',
          'muted',
          'No published releases yet. Tag a release (v*) and publish it on GitHub to populate this feed automatically.'
        )
      );
      host.appendChild(card);
      return;
    }

    for (const rel of releaseState.releases.slice(0, 5)) {
      const card = el('article', 'release-item');
      const top = el('div', 'release-top');

      const titleGroup = el('div', 'release-title-group');
      const link = el('a', 'release-name', rel.name);
      link.href = rel.url;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      titleGroup.appendChild(link);
      titleGroup.appendChild(el('span', 'badge', rel.tag));
      if (rel.prerelease) {
        titleGroup.appendChild(el('span', 'badge', 'Pre-release'));
      }

      top.appendChild(titleGroup);
      top.appendChild(el('span', 'mono muted', formatDate(rel.publishedAt)));
      card.appendChild(top);

      if (rel.body) {
        card.appendChild(renderReleaseNotesBody(rel.body));
      }

      if (rel.assets.length > 0) {
        const assetsBar = el('div', 'release-assets-inline');
        for (const asset of rel.assets) {
          const pill = el('a', 'asset-pill mono');
          pill.href = asset.url;
          pill.appendChild(el('span', '', asset.name));
          if (asset.size) {
            pill.appendChild(el('span', 'muted', formatBytes(asset.size)));
          }
          assetsBar.appendChild(pill);
        }
        card.appendChild(assetsBar);
      }

      host.appendChild(card);
    }
  }

  async function initReleases() {
    document.querySelectorAll('.tab-btn').forEach((btn) => {
      btn.addEventListener('click', () => renderDownloadTab(btn.dataset.os));
    });

    const snapshot = await loadSnapshot();
    if (snapshot && snapshot.releases.length > 0) {
      releaseState.releases = snapshot.releases;
      releaseState.source = 'snapshot';
      renderHeaderAndHero();
      renderDownloadTab(releaseState.activeOs);
      renderReleaseHistory();
    }

    const snapshotAgeMs =
      snapshot && snapshot.generatedAt
        ? Date.now() - new Date(snapshot.generatedAt).getTime()
        : Infinity;

    if (!snapshot || snapshot.releases.length === 0 || snapshotAgeMs > 5 * 60 * 1000) {
      const live = await loadLiveReleases();
      if (live && live.length > 0) {
        releaseState.releases = live;
        releaseState.source = 'api';
      }
      renderHeaderAndHero();
      renderDownloadTab(releaseState.activeOs);
      renderReleaseHistory();
    }
  }

  /* --------------------------------------------------------------------------
   * Workspace Tour, Mini Feature Switchers & Lightbox Inspection
   * -------------------------------------------------------------------------- */
  function initGalleryAndLightbox() {
    const dialog = document.getElementById('art-lightbox');
    const lightboxImg = document.getElementById('lightbox-img');
    const lightboxCaption = document.getElementById('lightbox-caption');
    const lightboxClose = document.getElementById('lightbox-close');

    function openLightbox(src, alt, caption) {
      if (!dialog || !lightboxImg || !src) return;
      lightboxImg.src = src;
      lightboxImg.alt = alt || caption || '';
      if (lightboxCaption) lightboxCaption.textContent = caption || alt || '';
      if (typeof dialog.showModal === 'function') {
        dialog.showModal();
      } else {
        dialog.setAttribute('open', '');
      }
    }

    function closeLightbox() {
      if (!dialog) return;
      if (typeof dialog.close === 'function' && dialog.open) {
        dialog.close();
      } else {
        dialog.removeAttribute('open');
      }
    }

    if (lightboxClose) {
      lightboxClose.addEventListener('click', closeLightbox);
    }

    if (dialog) {
      dialog.addEventListener('click', (e) => {
        if (e.target === dialog) closeLightbox();
      });
    }

    // Main Workspace Tour Switcher
    const tourImg = document.getElementById('tour-img');
    const tourCaption = document.getElementById('tour-caption');
    const tourZoomBtn = document.getElementById('tour-zoom-btn');
    const tourTabs = document.querySelectorAll('.tour-tab');

    tourTabs.forEach((tab) => {
      tab.addEventListener('click', () => {
        const src = tab.dataset.src;
        const alt = tab.dataset.alt || '';
        const caption = tab.dataset.caption || '';
        if (tourImg && src) {
          tourImg.src = src;
          tourImg.alt = alt;
        }
        if (tourCaption) tourCaption.textContent = caption;
        tourTabs.forEach((t) => {
          const active = t === tab;
          t.classList.toggle('active', active);
          t.setAttribute('aria-selected', String(active));
        });
      });
    });

    if (tourZoomBtn && tourImg) {
      tourZoomBtn.addEventListener('click', () => {
        openLightbox(
          tourImg.getAttribute('src'),
          tourImg.alt,
          tourCaption ? tourCaption.textContent : tourImg.alt
        );
      });
    }

    // Inline Mini Feature Switchers (Color tools & Comic/Perspective tools)
    document.querySelectorAll('[data-switcher]').forEach((group) => {
      const img = group.querySelector('[data-switcher-img]');
      const zoomBtn = group.querySelector('[data-switcher-zoom]');
      const pills = group.querySelectorAll('.mini-pill');

      pills.forEach((pill) => {
        pill.addEventListener('click', () => {
          const src = pill.dataset.src;
          const alt = pill.dataset.alt || '';
          const caption = pill.dataset.caption || '';
          if (img && src) {
            img.src = src;
            img.alt = alt;
          }
          if (zoomBtn && src) {
            zoomBtn.dataset.lightboxSrc = src;
            zoomBtn.dataset.lightboxCaption = caption;
          }
          pills.forEach((p) => {
            const active = p === pill;
            p.classList.toggle('active', active);
            p.setAttribute('aria-selected', String(active));
          });
        });
      });
    });

    // Any zoomable gallery or feature frame
    document.querySelectorAll('[data-lightbox-src]').forEach((btn) => {
      btn.addEventListener('click', () => {
        const img = btn.querySelector('img');
        openLightbox(
          btn.dataset.lightboxSrc,
          img ? img.alt : '',
          btn.dataset.lightboxCaption || (img ? img.alt : '')
        );
      });
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    initGalleryAndLightbox();
    void initReleases();
  });
})();