mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-05 00:02:22 -08:00
initial github repo theme fetching logic
This commit is contained in:
12 files changed
+399
No files matched your search
@@ -15,6 +15,11 @@
|
||||
|
||||
"settingsLinkBaseUrl": "https://app.sable.moe",
|
||||
|
||||
"themeCatalogBaseUrl": "https://raw.githubusercontent.com/SableClient/themes/main/",
|
||||
"themeCatalogApprovedHostPrefixes": [
|
||||
"https://raw.githubusercontent.com/SableClient/themes/"
|
||||
],
|
||||
|
||||
"slidingSync": {
|
||||
"enabled": true
|
||||
},
|
||||
|
||||
@@ -43,6 +43,9 @@ export type ClientConfig = {
|
||||
|
||||
matrixToBaseUrl?: string;
|
||||
settingsLinkBaseUrl?: string;
|
||||
|
||||
themeCatalogBaseUrl?: string;
|
||||
themeCatalogApprovedHostPrefixes?: string[];
|
||||
};
|
||||
|
||||
const ClientConfigContext = createContext<ClientConfig | null>(null);
|
||||
|
||||
@@ -121,6 +121,14 @@ export interface Settings {
|
||||
|
||||
// furry stuff
|
||||
renderAnimals: boolean;
|
||||
|
||||
// theme catalog
|
||||
themeRemoteCatalogEnabled: boolean;
|
||||
themeChatPreviewAnyUrl: boolean;
|
||||
themeChatPreviewApprovedCatalogOnly: boolean;
|
||||
themeRemoteManualFullUrl?: string;
|
||||
themeRemoteLightFullUrl?: string;
|
||||
themeRemoteDarkFullUrl?: string;
|
||||
}
|
||||
|
||||
const defaultSettings: Settings = {
|
||||
@@ -219,6 +227,14 @@ const defaultSettings: Settings = {
|
||||
|
||||
// furry stuff
|
||||
renderAnimals: true,
|
||||
|
||||
// theme catalog
|
||||
themeRemoteCatalogEnabled: false,
|
||||
themeChatPreviewAnyUrl: false,
|
||||
themeChatPreviewApprovedCatalogOnly: false,
|
||||
themeRemoteManualFullUrl: undefined,
|
||||
themeRemoteLightFullUrl: undefined,
|
||||
themeRemoteDarkFullUrl: undefined,
|
||||
};
|
||||
|
||||
export const getSettings = () => {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
const DB_NAME = 'sable-theme-cache';
|
||||
const DB_VERSION = 1;
|
||||
const STORE = 'themes';
|
||||
|
||||
export type CachedThemeEntry = {
|
||||
url: string;
|
||||
cssText: string;
|
||||
cachedAt: number;
|
||||
};
|
||||
|
||||
function openDb(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
req.onerror = () => reject(req.error);
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onupgradeneeded = () => {
|
||||
req.result.createObjectStore(STORE, { keyPath: 'url' });
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCachedThemeCss(url: string): Promise<string | undefined> {
|
||||
const db = await openDb();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE, 'readonly');
|
||||
const req = tx.objectStore(STORE).get(url);
|
||||
req.onerror = () => reject(req.error);
|
||||
req.onsuccess = () => {
|
||||
const row = req.result as CachedThemeEntry | undefined;
|
||||
resolve(row?.cssText);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function putCachedThemeCss(url: string, cssText: string): Promise<void> {
|
||||
const db = await openDb();
|
||||
const entry: CachedThemeEntry = { url, cssText, cachedAt: Date.now() };
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE, 'readwrite');
|
||||
tx.objectStore(STORE).put(entry);
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function clearThemeCache(): Promise<void> {
|
||||
const db = await openDb();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE, 'readwrite');
|
||||
tx.objectStore(STORE).clear();
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listThemePairsFromCatalog } from './catalog';
|
||||
|
||||
describe('listThemePairsFromCatalog', () => {
|
||||
const origFetch = globalThis.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = origFetch;
|
||||
});
|
||||
|
||||
it('pairs preview and full theme files from GitHub contents response', async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [
|
||||
{
|
||||
name: 'rose-pine.preview.sable.css',
|
||||
path: 'rose-pine.preview.sable.css',
|
||||
type: 'file',
|
||||
download_url: 'https://raw.githubusercontent.com/SableClient/themes/main/rose-pine.preview.sable.css',
|
||||
},
|
||||
{
|
||||
name: 'rose-pine.sable.css',
|
||||
path: 'rose-pine.sable.css',
|
||||
type: 'file',
|
||||
download_url: 'https://raw.githubusercontent.com/SableClient/themes/main/rose-pine.sable.css',
|
||||
},
|
||||
{
|
||||
name: 'README.md',
|
||||
path: 'README.md',
|
||||
type: 'file',
|
||||
download_url: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const base = 'https://raw.githubusercontent.com/SableClient/themes/main/';
|
||||
const pairs = await listThemePairsFromCatalog(base);
|
||||
|
||||
expect(pairs).toHaveLength(1);
|
||||
expect(pairs[0].basename).toBe('rose-pine');
|
||||
expect(pairs[0].fullUrl).toContain('rose-pine.sable.css');
|
||||
expect(pairs[0].previewUrl).toContain('rose-pine.preview.sable.css');
|
||||
|
||||
expect(globalThis.fetch).toHaveBeenCalledWith(
|
||||
'https://api.github.com/repos/SableClient/themes/contents?ref=main',
|
||||
expect.objectContaining({ headers: { Accept: 'application/vnd.github+json' } })
|
||||
);
|
||||
});
|
||||
|
||||
it('requests nested directory when catalog URL includes a path', async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [],
|
||||
});
|
||||
|
||||
await listThemePairsFromCatalog(
|
||||
'https://raw.githubusercontent.com/SableClient/themes/main/dist/themes/'
|
||||
);
|
||||
|
||||
expect(globalThis.fetch).toHaveBeenCalledWith(
|
||||
'https://api.github.com/repos/SableClient/themes/contents/dist/themes?ref=main',
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('returns empty array when base URL is not a raw GitHub URL', async () => {
|
||||
globalThis.fetch = vi.fn();
|
||||
const pairs = await listThemePairsFromCatalog('https://example.com/');
|
||||
expect(pairs).toEqual([]);
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { parseGithubRawBaseUrl, rawFileUrl, type GithubRawParts } from './githubRaw';
|
||||
|
||||
export type GithubContentItem = {
|
||||
name: string;
|
||||
path: string;
|
||||
type: 'file' | 'dir';
|
||||
download_url: string | null;
|
||||
};
|
||||
|
||||
export type ThemePair = {
|
||||
basename: string;
|
||||
previewUrl: string;
|
||||
fullUrl: string;
|
||||
};
|
||||
|
||||
const PREVIEW_SUFFIX = '.preview.sable.css';
|
||||
const FULL_SUFFIX = '.sable.css';
|
||||
|
||||
export async function listThemePairsFromCatalog(baseUrl: string): Promise<ThemePair[]> {
|
||||
const parts = parseGithubRawBaseUrl(baseUrl);
|
||||
if (!parts) return [];
|
||||
const items = await fetchGithubContents(parts);
|
||||
const previewFiles = items.filter(
|
||||
(i) => i.type === 'file' && i.name.endsWith(PREVIEW_SUFFIX)
|
||||
);
|
||||
const pairs: ThemePair[] = [];
|
||||
for (const p of previewFiles) {
|
||||
const basename = p.name.slice(0, -PREVIEW_SUFFIX.length);
|
||||
const fullName = `${basename}${FULL_SUFFIX}`;
|
||||
const full = items.find((i) => i.type === 'file' && i.name === fullName);
|
||||
if (!full?.download_url) continue;
|
||||
pairs.push({
|
||||
basename,
|
||||
previewUrl: rawFileUrl(parts, p.name),
|
||||
fullUrl: full.download_url,
|
||||
});
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
|
||||
/** Path segments for GET /repos/.../contents/{path} */
|
||||
function directoryPathToApiSegment(directoryPath: string): string {
|
||||
if (!directoryPath) return '';
|
||||
return directoryPath
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map((seg) => encodeURIComponent(seg))
|
||||
.join('/');
|
||||
}
|
||||
|
||||
async function fetchGithubContents(parts: GithubRawParts): Promise<GithubContentItem[]> {
|
||||
const encoded = directoryPathToApiSegment(parts.directoryPath);
|
||||
const pathSeg = encoded ? `/${encoded}` : '';
|
||||
const apiUrl = `https://api.github.com/repos/${parts.owner}/${parts.repo}/contents${pathSeg}?ref=${encodeURIComponent(parts.ref)}`;
|
||||
const res = await fetch(apiUrl, {
|
||||
headers: { Accept: 'application/vnd.github+json' },
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`theme catalog list failed: ${res.status}`);
|
||||
}
|
||||
const data = (await res.json()) as GithubContentItem | GithubContentItem[];
|
||||
return Array.isArray(data) ? data : [data];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Parse a raw.githubusercontent.com base URL into API parameters.
|
||||
* E.g. https://raw.githubusercontent.com/SableClient/themes/main/themes/
|
||||
*/
|
||||
export type GithubRawParts = {
|
||||
owner: string;
|
||||
repo: string;
|
||||
ref: string;
|
||||
directoryPath: string;
|
||||
};
|
||||
|
||||
const RAW_RE =
|
||||
/^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)(?:\/(.*))?$/;
|
||||
|
||||
export function parseGithubRawBaseUrl(baseUrl: string): GithubRawParts | null {
|
||||
const trimmed = baseUrl.trim().replace(/\/+$/, '');
|
||||
const m = trimmed.match(RAW_RE);
|
||||
if (!m) return null;
|
||||
const [, owner, repo, ref, rest] = m;
|
||||
const directoryPath = (rest ?? '').replace(/^\/+|\/+$/g, '');
|
||||
return { owner, repo, ref, directoryPath };
|
||||
}
|
||||
|
||||
export function rawFileUrl(parts: GithubRawParts, fileName: string): string {
|
||||
const dir = parts.directoryPath ? `${parts.directoryPath}/` : '';
|
||||
return `https://raw.githubusercontent.com/${parts.owner}/${parts.repo}/${parts.ref}/${dir}${fileName}`;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from './cache';
|
||||
export * from './catalog';
|
||||
export * from './githubRaw';
|
||||
export * from './legacyThemeMap';
|
||||
export * from './metadata';
|
||||
export * from './previewCss';
|
||||
export * from './themeUrlGuards';
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Map legacy theme ids to catalog basenames (SableClient/themes repo filenames without suffix) for migration.
|
||||
*/
|
||||
export const LEGACY_THEME_TO_BASENAME: Record<string, string> = {
|
||||
'silver-theme': 'silver',
|
||||
'cinny-light-theme': 'cinny-light',
|
||||
'cinny-silver-theme': 'cinny-silver',
|
||||
'dark-theme': 'dark',
|
||||
'light-theme': 'light',
|
||||
'butter-theme': 'butter',
|
||||
'rose-pine-theme': 'rose-pine',
|
||||
'cinny-dark-theme': 'cinny-dark',
|
||||
'gruvdark-theme': 'gruvdark',
|
||||
'accord-theme': 'accord',
|
||||
'black-theme': 'black',
|
||||
};
|
||||
|
||||
export const LEGACY_THEME_IDS = Object.keys(LEGACY_THEME_TO_BASENAME);
|
||||
|
||||
export function isLegacyBuiltinThemeId(id: string | undefined): boolean {
|
||||
if (!id) return false;
|
||||
return id !== 'light-theme' && id !== 'dark-theme' && id in LEGACY_THEME_TO_BASENAME;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { ThemeKind } from '$hooks/useTheme';
|
||||
|
||||
export type SableThemeContrast = 'low' | 'high';
|
||||
|
||||
export type SableThemeMetadata = {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: ThemeKind;
|
||||
contrast: SableThemeContrast;
|
||||
tags: string[];
|
||||
legacyIds: string[];
|
||||
fullThemeUrl?: string;
|
||||
};
|
||||
|
||||
const META_START = '@sable-theme';
|
||||
|
||||
/**
|
||||
* First block comment must contain @sable-theme and key: value lines.
|
||||
*/
|
||||
export function parseSableThemeMetadata(cssText: string): Partial<SableThemeMetadata> {
|
||||
const block = extractFirstBlockComment(cssText);
|
||||
if (!block.includes(META_START)) return {};
|
||||
|
||||
const lines = block.split(/\r?\n/).map((l) => l.replace(/^\s*\*?\s?/, '').trim());
|
||||
const out: Partial<SableThemeMetadata> = {};
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('@') || line === '---' || line === '') continue;
|
||||
const idx = line.indexOf(':');
|
||||
if (idx === -1) continue;
|
||||
const key = line.slice(0, idx).trim().toLowerCase();
|
||||
const value = line.slice(idx + 1).trim();
|
||||
switch (key) {
|
||||
case 'id':
|
||||
out.id = value;
|
||||
break;
|
||||
case 'name':
|
||||
out.name = value;
|
||||
break;
|
||||
case 'kind':
|
||||
out.kind = value === 'dark' ? ThemeKind.Dark : ThemeKind.Light;
|
||||
break;
|
||||
case 'contrast':
|
||||
out.contrast = value === 'high' ? 'high' : 'low';
|
||||
break;
|
||||
case 'tags':
|
||||
out.tags = value.split(',').map((t) => t.trim()).filter(Boolean);
|
||||
break;
|
||||
case 'legacyids':
|
||||
case 'legacy_ids':
|
||||
out.legacyIds = value.split(',').map((t) => t.trim()).filter(Boolean);
|
||||
break;
|
||||
case 'fullthemeurl':
|
||||
case 'full_theme_url':
|
||||
out.fullThemeUrl = value;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractFirstBlockComment(cssText: string): string {
|
||||
const start = cssText.indexOf('/*');
|
||||
if (start === -1) return '';
|
||||
const end = cssText.indexOf('*/', start + 2);
|
||||
if (end === -1) return '';
|
||||
return cssText.slice(start + 2, end);
|
||||
}
|
||||
|
||||
export function extractFullThemeUrlFromPreview(cssText: string): string | undefined {
|
||||
const meta = parseSableThemeMetadata(cssText);
|
||||
if (meta.fullThemeUrl && /^https:\/\//i.test(meta.fullThemeUrl)) {
|
||||
return meta.fullThemeUrl;
|
||||
}
|
||||
const block = extractFirstBlockComment(cssText);
|
||||
const m = block.match(/fullThemeUrl:\s*(https:\/\/[^\s*]+)/i);
|
||||
return m?.[1];
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Build safe preview CSS from a `.preview.sable.css` file: only allow --sable-* / --tc-* custom properties.
|
||||
* Raw preview text is never injected as a stylesheet.
|
||||
*/
|
||||
|
||||
const PROP_RE = /^\s*(--(?:sable|tc)-[a-zA-Z0-9-]+)\s*:\s*([^;]+?)\s*;?\s*$/;
|
||||
|
||||
const DANGEROUS_VALUE = /url\s*\(|@import|expression\s*\(|javascript:|\\0|<!--|-->|<script/i;
|
||||
|
||||
export function extractSafePreviewCustomProperties(cssText: string): Record<string, string> {
|
||||
const noComments = cssText.replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
const vars: Record<string, string> = {};
|
||||
for (const line of noComments.split(/\r?\n/)) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('@')) continue;
|
||||
const m = trimmed.match(PROP_RE);
|
||||
if (!m) continue;
|
||||
const name = m[1];
|
||||
let val = m[2].trim();
|
||||
if (DANGEROUS_VALUE.test(val)) continue;
|
||||
if (val.length > 2000) continue;
|
||||
vars[name] = val;
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
|
||||
export function buildPreviewStyleBlock(
|
||||
vars: Record<string, string>,
|
||||
scopeClass = 'sable-theme-preview'
|
||||
): string {
|
||||
const body = Object.entries(vars)
|
||||
.map(([k, v]) => ` ${k}: ${v};`)
|
||||
.join('\n');
|
||||
if (!body) return '';
|
||||
return `.${scopeClass} {\n${body}\n}`;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
const PREVIEW_RE = /\.preview\.sable\.css(\?|$|#)/i;
|
||||
const FULL_RE = /\.sable\.css(\?|$|#)/i;
|
||||
|
||||
export function isThemePreviewUrl(url: string): boolean {
|
||||
return /^https:\/\//i.test(url) && PREVIEW_RE.test(url) && !isThemeFullUrl(url);
|
||||
}
|
||||
|
||||
export function isThemeFullUrl(url: string): boolean {
|
||||
return /^https:\/\//i.test(url) && /\.sable\.css(\?|$|#)/i.test(url) && !PREVIEW_RE.test(url);
|
||||
}
|
||||
|
||||
export function isApprovedThemeUrl(url: string, approvedPrefixes: string[]): boolean {
|
||||
return approvedPrefixes.some((p) => url.startsWith(p));
|
||||
}
|
||||
Reference in new issue
Block a user