Compare commits
6
Commits
41eb568610
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62e187b9f5 | ||
|
|
99dbea0615 | ||
|
|
032d2a100a | ||
|
|
b9159cf61f | ||
|
|
643e7acf30 | ||
|
|
c42d256454 |
No files matched your search
@@ -32,6 +32,9 @@ jobs:
|
|||||||
- name: Install JS dependencies
|
- name: Install JS dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Type check
|
||||||
|
run: npm run typecheck
|
||||||
|
|
||||||
- name: Run build
|
- name: Run build
|
||||||
run: |
|
run: |
|
||||||
bash scripts/prepare_release.sh
|
bash scripts/prepare_release.sh
|
||||||
|
|||||||
@@ -30,6 +30,9 @@ jobs:
|
|||||||
- name: Install JS dependencies
|
- name: Install JS dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Type check
|
||||||
|
run: npm run typecheck
|
||||||
|
|
||||||
- name: Run build
|
- name: Run build
|
||||||
run: |
|
run: |
|
||||||
bash scripts/prepare_release.sh
|
bash scripts/prepare_release.sh
|
||||||
@@ -38,9 +41,10 @@ jobs:
|
|||||||
- name: Prepare archive
|
- name: Prepare archive
|
||||||
run: |
|
run: |
|
||||||
mkdir -p vision-start
|
mkdir -p vision-start
|
||||||
mv dist vision-start/
|
cp -a dist/. vision-start/
|
||||||
mv extension vision-start/
|
cp -a extension vision-start/
|
||||||
mv manifest.json vision-start/
|
cp manifest.json vision-start/
|
||||||
|
test -f vision-start/index.html
|
||||||
|
|
||||||
- name: Create zip archive
|
- name: Create zip archive
|
||||||
run: |
|
run: |
|
||||||
@@ -80,9 +84,10 @@ jobs:
|
|||||||
|
|
||||||
- name: Unpack build artifact
|
- name: Unpack build artifact
|
||||||
run: |
|
run: |
|
||||||
unzip -o -q ${{ env.ARCHIVE_NAME }}
|
mkdir -p dist
|
||||||
if [ ! -d dist ]; then
|
unzip -o -q ${{ env.ARCHIVE_NAME }} -d dist
|
||||||
echo "The build artifact does not contain dist/."
|
if [ ! -f dist/index.html ]; then
|
||||||
|
echo "The build artifact does not contain index.html at its root."
|
||||||
unzip -l ${{ env.ARCHIVE_NAME }}
|
unzip -l ${{ env.ARCHIVE_NAME }}
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -41,9 +41,8 @@ The design language is **soft liquid glass**: lightly translucent matte surfaces
|
|||||||
- Keep `prefers-reduced-motion` behavior intact when adding animations.
|
- Keep `prefers-reduced-motion` behavior intact when adding animations.
|
||||||
|
|
||||||
### Tailwind specifics
|
### Tailwind specifics
|
||||||
- Tailwind **v4** via `@tailwindcss/vite` and `@tailwindcss/postcss`. Custom easing is in `index.css` under `@theme {}` — add new theme tokens there, not in `tailwind.config.js`.
|
- Tailwind **v4** via the `@tailwindcss/vite` plugin only (there is no `tailwind.config.js` or PostCSS config). Custom easing is in `index.css` under `@theme {}` — add new theme tokens there.
|
||||||
- `tailwind.config.js` has a **safelist** of `w-[Npx]/h-[Npx]` classes because tile/icon sizes are constructed dynamically. If you add new pixel-size classes that are generated at runtime (not literally present in source), add them to the safelist or they will be purged.
|
- Tailwind generates only classes it finds literally in source files. Prefer static classes; for sizes computed at runtime use numeric inline styles (as tile icons do), or add an `@source inline(...)` line to `index.css` if a dynamic class is unavoidable.
|
||||||
- Prefer static classes; only build dynamic class strings when unavoidable and then safelist them.
|
|
||||||
|
|
||||||
### Components with established conventions to reuse
|
### Components with established conventions to reuse
|
||||||
- `Dropdown` (`components/Dropdown.tsx`) for selects — single or multi. Has a glassy look and custom arrow. **Always use it** instead of `<select>`/`<input type=...>` for option picking.
|
- `Dropdown` (`components/Dropdown.tsx`) for selects — single or multi. Has a glassy look and custom arrow. **Always use it** instead of `<select>`/`<input type=...>` for option picking.
|
||||||
@@ -97,8 +96,8 @@ A "feature" in this project typically means: a new widget, a new settings option
|
|||||||
- **Runtime note:** Preact is the actual runtime (`@preact/preset-vite`), but types and imports use `react`/`@types/react`. Do not introduce React-only APIs without verifying Preact compatibility.
|
- **Runtime note:** Preact is the actual runtime (`@preact/preset-vite`), but types and imports use `react`/`@types/react`. Do not introduce React-only APIs without verifying Preact compatibility.
|
||||||
- **Path alias:** `@/*` maps to the project root (see `tsconfig.json` `paths`). Source files currently use relative imports (`./`, `../`) — match the surrounding file.
|
- **Path alias:** `@/*` maps to the project root (see `tsconfig.json` `paths`). Source files currently use relative imports (`./`, `../`) — match the surrounding file.
|
||||||
- **No comments** in committed code unless explicitly requested.
|
- **No comments** in committed code unless explicitly requested.
|
||||||
- **Build vs. dev:** Prefer verifying with `npm run build` rather than `npm run dev`. The only npm scripts are `dev`, `build`, `preview`.
|
- **Build vs. dev:** Prefer verifying with `npm run build` rather than `npm run dev`. npm scripts: `dev`, `build`, `preview`, `typecheck`, `test`, `capture:screenshots`.
|
||||||
- **No lint/typecheck script is configured.** Verify TS correctness manually (e.g. `npx tsc --noEmit`), and confirm `npm run build` succeeds before considering a task complete.
|
- **Verification:** run `npm run typecheck` and `npm run build`, then `npm test` (Playwright regression suite; needs `npx playwright install chromium`) before considering a task complete. CI runs the type check on PRs and pushes to `main`.
|
||||||
- **Don't touch `public/icon-metadata.json`** — it's gitignored and fetched at release-build time by `scripts/prepare_release.sh`. Don't commit a local copy.
|
- **Don't touch `public/icon-metadata.json`** — it's gitignored and fetched at release-build time by `scripts/prepare_release.sh`. Don't commit a local copy.
|
||||||
- **Don't reintroduce dead code:** `components/EditModal.tsx` imports `lucide-react` and `./IconPicker`, neither of which is a dependency. It is not wired into the app. Use `WebsiteEditModal.tsx` / `CategoryEditModal.tsx` instead, and add the icon picker inline (as in `WebsiteEditModal.tsx`) rather than reviving `IconPicker`.
|
- **Don't reintroduce dead code:** `components/EditModal.tsx` imports `lucide-react` and `./IconPicker`, neither of which is a dependency. It is not wired into the app. Use `WebsiteEditModal.tsx` / `CategoryEditModal.tsx` instead, and add the icon picker inline (as in `WebsiteEditModal.tsx`) rather than reviving `IconPicker`.
|
||||||
- **External asset URLs:** any new icons/css/JS pulled from CDNs (e.g. `cdn.jsdelivr.net`) must work offline-or-not without crashing — always provide a fallback (see how `iconService.ts` falls back to Google's S2 favicon service).
|
- **External asset URLs:** any new icons/css/JS pulled from CDNs (e.g. `cdn.jsdelivr.net`) must work offline-or-not without crashing — always provide a fallback (see how `iconService.ts` falls back to Google's S2 favicon service).
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { useState, useEffect, useCallback, lazy, Suspense } from 'react';
|
import { useState, useEffect, useCallback, useRef, lazy, Suspense } from 'react';
|
||||||
import ServerWidget from './components/ServerWidget';
|
import ServerWidget from './components/ServerWidget';
|
||||||
import { DEFAULT_CATEGORIES } from './constants';
|
|
||||||
import { Category, Website, Config } from './types';
|
import { Category, Website, Config } from './types';
|
||||||
import Header from './components/layout/Header';
|
import Header from './components/layout/Header';
|
||||||
import EditButton from './components/layout/EditButton';
|
import EditButton from './components/layout/EditButton';
|
||||||
@@ -11,23 +10,15 @@ import { ConfigurationService } from './components/services/ConfigurationService
|
|||||||
import { getAlignmentClass } from './components/utils/styleUtils';
|
import { getAlignmentClass } from './components/utils/styleUtils';
|
||||||
import { getRandomWallpaperIndex, loadWallpaperState, saveWallpaperState } from './components/utils/wallpaperUtils';
|
import { getRandomWallpaperIndex, loadWallpaperState, saveWallpaperState } from './components/utils/wallpaperUtils';
|
||||||
import { PlusIcon } from './components/icons';
|
import { PlusIcon } from './components/icons';
|
||||||
|
import { createId } from './components/utils/idUtils';
|
||||||
|
import { pruneCachedIconsFromChromeStorageLocal } from './components/utils/StorageLocalManager';
|
||||||
|
|
||||||
const ConfigurationModal = lazy(() => import('./components/ConfigurationModal'));
|
const ConfigurationModal = lazy(() => import('./components/ConfigurationModal'));
|
||||||
const WebsiteEditModal = lazy(() => import('./components/WebsiteEditModal'));
|
const WebsiteEditModal = lazy(() => import('./components/WebsiteEditModal'));
|
||||||
const CategoryEditModal = lazy(() => import('./components/CategoryEditModal'));
|
const CategoryEditModal = lazy(() => import('./components/CategoryEditModal'));
|
||||||
|
|
||||||
const App: React.FC = () => {
|
const App: React.FC = () => {
|
||||||
const [categories, setCategories] = useState<Category[]>(() => {
|
const [categories, setCategories] = useState<Category[]>(() => ConfigurationService.loadCategories());
|
||||||
try {
|
|
||||||
const storedCategories = localStorage.getItem('categories');
|
|
||||||
if (storedCategories) {
|
|
||||||
return JSON.parse(storedCategories);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error parsing categories from localStorage', error);
|
|
||||||
}
|
|
||||||
return DEFAULT_CATEGORIES;
|
|
||||||
});
|
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
const [isConfigModalOpen, setIsConfigModalOpen] = useState(false);
|
const [isConfigModalOpen, setIsConfigModalOpen] = useState(false);
|
||||||
const [editingWebsite, setEditingWebsite] = useState<Website | null>(null);
|
const [editingWebsite, setEditingWebsite] = useState<Website | null>(null);
|
||||||
@@ -36,6 +27,25 @@ const App: React.FC = () => {
|
|||||||
const [isCategoryModalOpen, setIsCategoryModalOpen] = useState(false);
|
const [isCategoryModalOpen, setIsCategoryModalOpen] = useState(false);
|
||||||
const [config, setConfig] = useState<Config>(() => ConfigurationService.loadConfig());
|
const [config, setConfig] = useState<Config>(() => ConfigurationService.loadConfig());
|
||||||
const [wallpaperVersion, setWallpaperVersion] = useState(0);
|
const [wallpaperVersion, setWallpaperVersion] = useState(0);
|
||||||
|
const categoriesRef = useRef(categories);
|
||||||
|
categoriesRef.current = categories;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
const icons = categoriesRef.current.flatMap(category => category.websites.map(website => website.icon));
|
||||||
|
void pruneCachedIconsFromChromeStorageLocal(icons);
|
||||||
|
}, 5000);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onStorage = (event: StorageEvent) => {
|
||||||
|
if (event.key === 'config' || event.key === null) setConfig(ConfigurationService.loadConfig());
|
||||||
|
if (event.key === 'categories' || event.key === null) setCategories(ConfigurationService.loadCategories());
|
||||||
|
};
|
||||||
|
window.addEventListener('storage', onStorage);
|
||||||
|
return () => window.removeEventListener('storage', onStorage);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
ConfigurationService.saveConfig(config);
|
ConfigurationService.saveConfig(config);
|
||||||
@@ -55,9 +65,19 @@ const App: React.FC = () => {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleWallpaperChange = useCallback((newConfig: Partial<Config>) => {
|
const handleWallpaperChange = useCallback((newConfig: Partial<Config>) => {
|
||||||
setConfig(prev => ({ ...prev, ...newConfig }));
|
setConfig(prev => {
|
||||||
|
const next = newConfig.currentWallpapers;
|
||||||
|
const unchanged = Object.keys(newConfig).length === 1 && next !== undefined
|
||||||
|
&& next.length === prev.currentWallpapers.length
|
||||||
|
&& next.every((name, index) => name === prev.currentWallpapers[index]);
|
||||||
|
return unchanged ? prev : { ...prev, ...newConfig };
|
||||||
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const handleToggleEditing = useCallback(() => setIsEditing(editing => !editing), []);
|
||||||
|
|
||||||
|
const handleOpenConfig = useCallback(() => setIsConfigModalOpen(true), []);
|
||||||
|
|
||||||
const handleRandomWallpaper = useCallback(() => {
|
const handleRandomWallpaper = useCallback(() => {
|
||||||
const names = config.currentWallpapers;
|
const names = config.currentWallpapers;
|
||||||
if (names.length === 0) return;
|
if (names.length === 0) return;
|
||||||
@@ -74,90 +94,89 @@ const App: React.FC = () => {
|
|||||||
const handleSaveWebsite = useCallback((website: Partial<Website>) => {
|
const handleSaveWebsite = useCallback((website: Partial<Website>) => {
|
||||||
if (editingWebsite) {
|
if (editingWebsite) {
|
||||||
const idToUpdate = website.id ?? editingWebsite.id;
|
const idToUpdate = website.id ?? editingWebsite.id;
|
||||||
const newCategories = categories.map(category => ({
|
setCategories(previous => previous.map(category => category.id === editingWebsite.categoryId ? {
|
||||||
...category,
|
...category,
|
||||||
websites: category.websites.map(w =>
|
websites: category.websites.map(w =>
|
||||||
w.id === idToUpdate ? { ...w, ...website, id: idToUpdate } : w
|
w.id === idToUpdate ? { ...w, ...website, id: idToUpdate, categoryId: category.id } : w
|
||||||
),
|
),
|
||||||
}));
|
} : category));
|
||||||
setCategories(newCategories);
|
|
||||||
setEditingWebsite(null);
|
setEditingWebsite(null);
|
||||||
} else if (addingWebsite) {
|
} else if (addingWebsite) {
|
||||||
const newWebsite: Website = {
|
const newWebsite: Website = {
|
||||||
id: Date.now().toString(),
|
id: createId(),
|
||||||
name: website.name || '',
|
name: website.name || '',
|
||||||
url: website.url || '',
|
url: website.url || '',
|
||||||
icon: website.icon || '',
|
icon: website.icon || '',
|
||||||
categoryId: addingWebsite.id,
|
categoryId: addingWebsite.id,
|
||||||
};
|
};
|
||||||
const newCategories = categories.map(category =>
|
setCategories(previous => previous.map(category =>
|
||||||
category.id === addingWebsite.id
|
category.id === addingWebsite.id
|
||||||
? { ...category, websites: [...category.websites, newWebsite] }
|
? { ...category, websites: [...category.websites, newWebsite] }
|
||||||
: category
|
: category
|
||||||
);
|
));
|
||||||
setCategories(newCategories);
|
|
||||||
setAddingWebsite(null);
|
setAddingWebsite(null);
|
||||||
}
|
}
|
||||||
}, [editingWebsite, addingWebsite, categories]);
|
}, [editingWebsite, addingWebsite]);
|
||||||
|
|
||||||
const handleSaveCategory = useCallback((name: string) => {
|
const handleSaveCategory = useCallback((name: string) => {
|
||||||
if (editingCategory) {
|
if (editingCategory) {
|
||||||
const newCategories = categories.map(category =>
|
setCategories(previous => previous.map(category =>
|
||||||
category.id === editingCategory.id ? { ...category, name } : category
|
category.id === editingCategory.id ? { ...category, name } : category
|
||||||
);
|
));
|
||||||
setCategories(newCategories);
|
|
||||||
} else {
|
} else {
|
||||||
const newCategory: Category = {
|
const newCategory: Category = {
|
||||||
id: Date.now().toString(),
|
id: createId(),
|
||||||
name,
|
name,
|
||||||
websites: [],
|
websites: [],
|
||||||
};
|
};
|
||||||
setCategories([...categories, newCategory]);
|
setCategories(previous => [...previous, newCategory]);
|
||||||
}
|
}
|
||||||
setEditingCategory(null);
|
setEditingCategory(null);
|
||||||
setIsCategoryModalOpen(false);
|
setIsCategoryModalOpen(false);
|
||||||
}, [editingCategory, categories]);
|
}, [editingCategory]);
|
||||||
|
|
||||||
const handleDeleteWebsite = useCallback(() => {
|
const handleDeleteWebsite = useCallback(() => {
|
||||||
if (!editingWebsite) return;
|
if (!editingWebsite) return;
|
||||||
|
|
||||||
const newCategories = categories.map(category => ({
|
setCategories(previous => previous.map(category => category.id === editingWebsite.categoryId ? {
|
||||||
...category,
|
...category,
|
||||||
websites: category.websites.filter(w => w.id !== editingWebsite.id),
|
websites: category.websites.filter(w => w.id !== editingWebsite.id),
|
||||||
}));
|
} : category));
|
||||||
setCategories(newCategories);
|
|
||||||
setEditingWebsite(null);
|
setEditingWebsite(null);
|
||||||
}, [editingWebsite, categories]);
|
}, [editingWebsite]);
|
||||||
|
|
||||||
const handleDeleteCategory = useCallback(() => {
|
const handleDeleteCategory = useCallback(() => {
|
||||||
if (!editingCategory) return;
|
if (!editingCategory) return;
|
||||||
|
const websiteCount = editingCategory.websites.length;
|
||||||
|
if (websiteCount > 0 && !confirm(`Delete "${editingCategory.name}" and its ${websiteCount} ${websiteCount === 1 ? 'website' : 'websites'}?`)) return;
|
||||||
|
|
||||||
const newCategories = categories.filter(c => c.id !== editingCategory.id);
|
setCategories(previous => previous.filter(c => c.id !== editingCategory.id));
|
||||||
setCategories(newCategories);
|
|
||||||
setEditingCategory(null);
|
setEditingCategory(null);
|
||||||
setIsCategoryModalOpen(false);
|
setIsCategoryModalOpen(false);
|
||||||
}, [editingCategory, categories]);
|
}, [editingCategory]);
|
||||||
|
|
||||||
const handleMoveWebsite = useCallback((website: Website, direction: 'left' | 'right') => {
|
const handleMoveWebsite = useCallback((website: Website, direction: 'left' | 'right') => {
|
||||||
const categoryIndex = categories.findIndex(cat => cat.websites.some(w => w.id === website.id));
|
setCategories(previous => {
|
||||||
if (categoryIndex === -1) return;
|
const categoryIndex = previous.findIndex(cat => cat.id === website.categoryId);
|
||||||
|
if (categoryIndex === -1) return previous;
|
||||||
|
|
||||||
const category = categories[categoryIndex];
|
const category = previous[categoryIndex];
|
||||||
const websiteIndex = category.websites.findIndex(w => w.id === website.id);
|
const websiteIndex = category.websites.findIndex(w => w.id === website.id);
|
||||||
if (websiteIndex === -1) return;
|
if (websiteIndex === -1) return previous;
|
||||||
|
|
||||||
const targetIndex = direction === 'left' ? websiteIndex - 1 : websiteIndex + 1;
|
const targetIndex = direction === 'left' ? websiteIndex - 1 : websiteIndex + 1;
|
||||||
if (targetIndex < 0 || targetIndex >= category.websites.length) return;
|
if (targetIndex < 0 || targetIndex >= category.websites.length) return previous;
|
||||||
|
|
||||||
const newWebsites = [...category.websites];
|
const newWebsites = [...category.websites];
|
||||||
const [movedWebsite] = newWebsites.splice(websiteIndex, 1);
|
const [movedWebsite] = newWebsites.splice(websiteIndex, 1);
|
||||||
newWebsites.splice(targetIndex, 0, movedWebsite);
|
newWebsites.splice(targetIndex, 0, movedWebsite);
|
||||||
|
|
||||||
const newCategories = [...categories];
|
const newCategories = [...previous];
|
||||||
newCategories[categoryIndex] = { ...category, websites: newWebsites };
|
newCategories[categoryIndex] = { ...category, websites: newWebsites };
|
||||||
|
|
||||||
setCategories(newCategories);
|
return newCategories;
|
||||||
}, [categories]);
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main
|
<main
|
||||||
@@ -171,8 +190,8 @@ const App: React.FC = () => {
|
|||||||
wallpaperFrequency={config.wallpaperFrequency}
|
wallpaperFrequency={config.wallpaperFrequency}
|
||||||
wallpaperVersion={wallpaperVersion}
|
wallpaperVersion={wallpaperVersion}
|
||||||
/>
|
/>
|
||||||
<EditButton isEditing={isEditing} onClick={() => setIsEditing(!isEditing)} />
|
<EditButton isEditing={isEditing} onClick={handleToggleEditing} />
|
||||||
<ConfigurationButton onClick={() => setIsConfigModalOpen(true)} />
|
<ConfigurationButton onClick={handleOpenConfig} />
|
||||||
|
|
||||||
<Header config={config} />
|
<Header config={config} />
|
||||||
|
|
||||||
@@ -208,7 +227,7 @@ const App: React.FC = () => {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{config.serverWidget.enabled && <ServerWidget config={config} />}
|
{config.serverWidget.enabled && <ServerWidget serverWidget={config.serverWidget} />}
|
||||||
|
|
||||||
{(editingWebsite || addingWebsite) && (
|
{(editingWebsite || addingWebsite) && (
|
||||||
<Suspense fallback={null}>
|
<Suspense fallback={null}>
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ const CategoryEditModal: React.FC<CategoryEditModalProps> = ({ category, edit, o
|
|||||||
title={edit ? 'Edit Category' : 'Add Category'}
|
title={edit ? 'Edit Category' : 'Add Category'}
|
||||||
edit={edit}
|
edit={edit}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
onSave={() => onSave(name)}
|
onSave={() => onSave(name.trim())}
|
||||||
|
canSave={name.trim() !== ''}
|
||||||
onDelete={edit ? onDelete : undefined}
|
onDelete={edit ? onDelete : undefined}
|
||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
|
|||||||
+18
-15
@@ -12,28 +12,31 @@ interface ClockProps {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getMinuteKey = (date: Date): number => Math.floor(date.getTime() / 60_000);
|
||||||
|
|
||||||
const Clock: React.FC<ClockProps> = ({ config }) => {
|
const Clock: React.FC<ClockProps> = ({ config }) => {
|
||||||
const [time, setTime] = useState(new Date());
|
const [minuteKey, setMinuteKey] = useState(() => getMinuteKey(new Date()));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!config.clock.enabled) return;
|
if (!config.clock.enabled) return;
|
||||||
|
|
||||||
const scheduleNext = () => {
|
|
||||||
const now = new Date();
|
|
||||||
const msToNextMinute = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
|
|
||||||
timeoutId = window.setTimeout(() => {
|
|
||||||
setTime(new Date());
|
|
||||||
intervalId = window.setInterval(() => setTime(new Date()), 60_000);
|
|
||||||
}, msToNextMinute);
|
|
||||||
};
|
|
||||||
|
|
||||||
let timeoutId = 0;
|
let timeoutId = 0;
|
||||||
let intervalId = 0;
|
const refresh = () => {
|
||||||
scheduleNext();
|
window.clearTimeout(timeoutId);
|
||||||
|
if (document.visibilityState !== 'visible') return;
|
||||||
|
const now = new Date();
|
||||||
|
setMinuteKey(getMinuteKey(now));
|
||||||
|
const msToNextMinute = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
|
||||||
|
timeoutId = window.setTimeout(refresh, msToNextMinute);
|
||||||
|
};
|
||||||
|
refresh();
|
||||||
|
document.addEventListener('visibilitychange', refresh);
|
||||||
|
window.addEventListener('focus', refresh);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (timeoutId) window.clearTimeout(timeoutId);
|
window.clearTimeout(timeoutId);
|
||||||
if (intervalId) window.clearInterval(intervalId);
|
document.removeEventListener('visibilitychange', refresh);
|
||||||
|
window.removeEventListener('focus', refresh);
|
||||||
};
|
};
|
||||||
}, [config.clock.enabled]);
|
}, [config.clock.enabled]);
|
||||||
|
|
||||||
@@ -61,7 +64,7 @@ const Clock: React.FC<ClockProps> = ({ config }) => {
|
|||||||
fontFamily: config.clock.font,
|
fontFamily: config.clock.font,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{formatTime(time)}
|
{formatTime(new Date(minuteKey * 60_000))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useRef, useEffect } from 'react';
|
import React, { useState, useRef, useEffect, lazy, Suspense } from 'react';
|
||||||
import { Config, Wallpaper } from '../types';
|
import { Config, Wallpaper } from '../types';
|
||||||
import { baseWallpapers } from './utils/baseWallpapers';
|
import { baseWallpapers } from './utils/baseWallpapers';
|
||||||
import { checkChromeStorageLocalAvailable } from './utils/StorageLocalManager';
|
import { checkChromeStorageLocalAvailable } from './utils/StorageLocalManager';
|
||||||
@@ -6,7 +6,7 @@ import { ConfigurationService } from './services/ConfigurationService';
|
|||||||
import GeneralTab from './configuration/GeneralTab';
|
import GeneralTab from './configuration/GeneralTab';
|
||||||
import ThemeTab from './configuration/ThemeTab';
|
import ThemeTab from './configuration/ThemeTab';
|
||||||
import ClockTab from './configuration/ClockTab';
|
import ClockTab from './configuration/ClockTab';
|
||||||
import ServerWidgetTab from './configuration/ServerWidgetTab';
|
const ServerWidgetTab = lazy(() => import('./configuration/ServerWidgetTab'));
|
||||||
|
|
||||||
interface ConfigurationModalProps {
|
interface ConfigurationModalProps {
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
@@ -30,6 +30,8 @@ const ConfigurationModal: React.FC<ConfigurationModalProps> = ({
|
|||||||
const [isVisible, setIsVisible] = useState(false);
|
const [isVisible, setIsVisible] = useState(false);
|
||||||
const importInputRef = useRef<HTMLInputElement>(null);
|
const importInputRef = useRef<HTMLInputElement>(null);
|
||||||
const isSaving = useRef(false);
|
const isSaving = useRef(false);
|
||||||
|
const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||||
|
const wallpaperMutation = useRef<Promise<void>>(Promise.resolve());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setChromeStorageAvailable(checkChromeStorageLocalAvailable());
|
setChromeStorageAvailable(checkChromeStorageLocalAvailable());
|
||||||
@@ -43,8 +45,10 @@ const ConfigurationModal: React.FC<ConfigurationModalProps> = ({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
|
clearTimeout(closeTimer.current);
|
||||||
if (!isSaving.current) {
|
if (!isSaving.current) {
|
||||||
onWallpaperChange({ currentWallpapers: currentConfig.currentWallpapers });
|
const availableNames = new Set([...baseWallpapers, ...ConfigurationService.loadUserWallpapers()].map(wallpaper => wallpaper.name));
|
||||||
|
onWallpaperChange({ currentWallpapers: currentConfig.currentWallpapers.filter(name => availableNames.has(name)) });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
@@ -55,39 +59,60 @@ const ConfigurationModal: React.FC<ConfigurationModalProps> = ({
|
|||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
setIsVisible(false);
|
setIsVisible(false);
|
||||||
setTimeout(onClose, 250);
|
clearTimeout(closeTimer.current);
|
||||||
|
closeTimer.current = setTimeout(onClose, 250);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleCloseRef = useRef(handleClose);
|
||||||
|
handleCloseRef.current = handleClose;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape' && !e.defaultPrevented) handleCloseRef.current();
|
||||||
|
};
|
||||||
|
document.addEventListener('keydown', handleKeyDown);
|
||||||
|
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleConfigChange = (updates: Partial<Config>) => {
|
const handleConfigChange = (updates: Partial<Config>) => {
|
||||||
setConfig((prev) => ({ ...prev, ...updates }));
|
setConfig((prev) => ({ ...prev, ...updates }));
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddWallpaperEntry = async (promise: Promise<Wallpaper>) => {
|
const mutateWallpapers = (mutate: () => Promise<void>): Promise<void> => {
|
||||||
const newWallpaper = await promise;
|
const operation = wallpaperMutation.current.then(mutate);
|
||||||
const updated = [...userWallpapers, newWallpaper];
|
wallpaperMutation.current = operation.catch(() => {});
|
||||||
setUserWallpapers(updated);
|
return operation;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddWallpaperEntry = (createWallpaper: () => Promise<Wallpaper>) => mutateWallpapers(async () => {
|
||||||
|
const newWallpaper = await createWallpaper();
|
||||||
|
const updated = [...ConfigurationService.loadUserWallpapers(), newWallpaper];
|
||||||
|
if (updated.slice(0, -1).some(wallpaper => wallpaper.name === newWallpaper.name)) {
|
||||||
|
throw new Error('A wallpaper with this name already exists. Please choose a different name.');
|
||||||
|
}
|
||||||
ConfigurationService.saveUserWallpapers(updated);
|
ConfigurationService.saveUserWallpapers(updated);
|
||||||
|
setUserWallpapers(updated);
|
||||||
setConfig((prev) => ({
|
setConfig((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
currentWallpapers: [...prev.currentWallpapers, newWallpaper.name],
|
currentWallpapers: [...prev.currentWallpapers, newWallpaper.name],
|
||||||
}));
|
}));
|
||||||
};
|
});
|
||||||
|
|
||||||
const handleAddWallpaper = (name: string, url: string) =>
|
const handleAddWallpaper = (name: string, url: string) =>
|
||||||
handleAddWallpaperEntry(ConfigurationService.addWallpaper(name, url));
|
handleAddWallpaperEntry(() => ConfigurationService.addWallpaper(name, url));
|
||||||
|
|
||||||
const handleAddWallpaperFile = (file: File) =>
|
const handleAddWallpaperFile = (file: File) =>
|
||||||
handleAddWallpaperEntry(ConfigurationService.addWallpaperFile(file));
|
handleAddWallpaperEntry(() => ConfigurationService.addWallpaperFile(file));
|
||||||
|
|
||||||
const handleDeleteWallpaper = async (wallpaper: Wallpaper) => {
|
const handleDeleteWallpaper = async (wallpaper: Wallpaper) => {
|
||||||
try {
|
try {
|
||||||
|
await mutateWallpapers(async () => {
|
||||||
await ConfigurationService.deleteWallpaper(wallpaper);
|
await ConfigurationService.deleteWallpaper(wallpaper);
|
||||||
const updated = userWallpapers.filter((w) => w.name !== wallpaper.name);
|
const updated = ConfigurationService.loadUserWallpapers().filter((w) => w.name !== wallpaper.name);
|
||||||
setUserWallpapers(updated);
|
|
||||||
ConfigurationService.saveUserWallpapers(updated);
|
ConfigurationService.saveUserWallpapers(updated);
|
||||||
const newCurrentWallpapers = config.currentWallpapers.filter((n) => n !== wallpaper.name);
|
setUserWallpapers(updated);
|
||||||
setConfig((prev) => ({ ...prev, currentWallpapers: newCurrentWallpapers }));
|
setConfig((prev) => ({ ...prev, currentWallpapers: prev.currentWallpapers.filter(name => name !== wallpaper.name) }));
|
||||||
onWallpaperChange({ currentWallpapers: newCurrentWallpapers });
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Error deleting wallpaper. Please try again.');
|
alert('Error deleting wallpaper. Please try again.');
|
||||||
console.error(error);
|
console.error(error);
|
||||||
@@ -103,6 +128,7 @@ const ConfigurationModal: React.FC<ConfigurationModalProps> = ({
|
|||||||
setConfig(importedConfig);
|
setConfig(importedConfig);
|
||||||
setUserWallpapers(importedWallpapers);
|
setUserWallpapers(importedWallpapers);
|
||||||
onWallpaperChange({ currentWallpapers: importedConfig.currentWallpapers || [] });
|
onWallpaperChange({ currentWallpapers: importedConfig.currentWallpapers || [] });
|
||||||
|
isSaving.current = true;
|
||||||
onSave(importedConfig);
|
onSave(importedConfig);
|
||||||
alert('Configuration imported successfully. The page will reload to apply all data.');
|
alert('Configuration imported successfully. The page will reload to apply all data.');
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
@@ -124,7 +150,7 @@ const ConfigurationModal: React.FC<ConfigurationModalProps> = ({
|
|||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50" role="dialog" aria-modal="true">
|
<div className="fixed inset-0 z-50" role="dialog" aria-modal="true" aria-labelledby="configuration-title">
|
||||||
<div
|
<div
|
||||||
className={`liquid-modal-backdrop fixed inset-0 transition-opacity duration-200 ease-ios ${
|
className={`liquid-modal-backdrop fixed inset-0 transition-opacity duration-200 ease-ios ${
|
||||||
isVisible ? 'opacity-100' : 'opacity-0'
|
isVisible ? 'opacity-100' : 'opacity-0'
|
||||||
@@ -138,7 +164,7 @@ const ConfigurationModal: React.FC<ConfigurationModalProps> = ({
|
|||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div className="p-6 sm:p-8 flex-grow overflow-y-auto">
|
<div className="p-6 sm:p-8 flex-grow overflow-y-auto">
|
||||||
<h2 className="liquid-title-text text-3xl font-extrabold mb-6">Configuration</h2>
|
<h2 id="configuration-title" className="liquid-title-text text-3xl font-extrabold mb-6">Configuration</h2>
|
||||||
|
|
||||||
<div className="liquid-surface grid grid-cols-2 sm:grid-cols-4 gap-1 rounded-2xl p-1 mb-7">
|
<div className="liquid-surface grid grid-cols-2 sm:grid-cols-4 gap-1 rounded-2xl p-1 mb-7">
|
||||||
{tabs.map((tab) => (
|
{tabs.map((tab) => (
|
||||||
@@ -176,7 +202,9 @@ const ConfigurationModal: React.FC<ConfigurationModalProps> = ({
|
|||||||
<ClockTab config={config} onChange={handleConfigChange} />
|
<ClockTab config={config} onChange={handleConfigChange} />
|
||||||
)}
|
)}
|
||||||
{activeTab === 'serverWidget' && (
|
{activeTab === 'serverWidget' && (
|
||||||
|
<Suspense fallback={null}>
|
||||||
<ServerWidgetTab config={config} onChange={handleConfigChange} />
|
<ServerWidgetTab config={config} onChange={handleConfigChange} />
|
||||||
|
</Suspense>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+11
-3
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useRef, useEffect } from 'react';
|
import React, { useState, useRef, useLayoutEffect } from 'react';
|
||||||
|
|
||||||
interface DropdownProps {
|
interface DropdownProps {
|
||||||
options: { value: string; label: string }[];
|
options: { value: string; label: string }[];
|
||||||
@@ -12,17 +12,25 @@ const Dropdown: React.FC<DropdownProps> = ({ options, value, onChange, name, mul
|
|||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useLayoutEffect(() => {
|
||||||
|
if (!isOpen) return;
|
||||||
const handleClickOutside = (event: MouseEvent) => {
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||||
setIsOpen(false);
|
setIsOpen(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key !== 'Escape') return;
|
||||||
|
event.preventDefault();
|
||||||
|
setIsOpen(false);
|
||||||
|
};
|
||||||
document.addEventListener('mousedown', handleClickOutside);
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
|
document.addEventListener('keydown', handleKeyDown, true);
|
||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener('mousedown', handleClickOutside);
|
document.removeEventListener('mousedown', handleClickOutside);
|
||||||
|
document.removeEventListener('keydown', handleKeyDown, true);
|
||||||
};
|
};
|
||||||
}, []);
|
}, [isOpen]);
|
||||||
|
|
||||||
const handleOptionClick = (optionValue: string) => {
|
const handleOptionClick = (optionValue: string) => {
|
||||||
let newValue: string | string[];
|
let newValue: string | string[];
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React from 'react';
|
import React, { useEffect, useId, useRef } from 'react';
|
||||||
|
|
||||||
interface ModalShellProps {
|
interface ModalShellProps {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -6,10 +6,23 @@ interface ModalShellProps {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onSave: () => void;
|
onSave: () => void;
|
||||||
onDelete?: () => void;
|
onDelete?: () => void;
|
||||||
|
canSave?: boolean;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ModalShell: React.FC<ModalShellProps> = ({ title, edit, onClose, onSave, onDelete, children }) => {
|
const ModalShell: React.FC<ModalShellProps> = ({ title, edit, onClose, onSave, onDelete, canSave = true, children }) => {
|
||||||
|
const titleId = useId();
|
||||||
|
const onCloseRef = useRef(onClose);
|
||||||
|
onCloseRef.current = onClose;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape' && !e.defaultPrevented) onCloseRef.current();
|
||||||
|
};
|
||||||
|
document.addEventListener('keydown', handleKeyDown);
|
||||||
|
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleOverlayClick = (e: React.MouseEvent<HTMLDivElement>) => {
|
const handleOverlayClick = (e: React.MouseEvent<HTMLDivElement>) => {
|
||||||
if (e.target === e.currentTarget) {
|
if (e.target === e.currentTarget) {
|
||||||
onClose();
|
onClose();
|
||||||
@@ -18,8 +31,8 @@ const ModalShell: React.FC<ModalShellProps> = ({ title, edit, onClose, onSave, o
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="liquid-modal-backdrop fixed inset-0 flex items-center justify-center z-50 p-4" onClick={handleOverlayClick}>
|
<div className="liquid-modal-backdrop fixed inset-0 flex items-center justify-center z-50 p-4" onClick={handleOverlayClick}>
|
||||||
<div className="liquid-panel liquid-modal-card rounded-3xl p-6 sm:p-8 w-full max-w-lg text-white">
|
<div className="liquid-panel liquid-modal-card rounded-3xl p-6 sm:p-8 w-full max-w-lg text-white" role="dialog" aria-modal="true" aria-labelledby={titleId}>
|
||||||
<h2 className="liquid-title-text text-3xl font-extrabold mb-6">{title}</h2>
|
<h2 id={titleId} className="liquid-title-text text-3xl font-extrabold mb-6">{title}</h2>
|
||||||
<div className="flex flex-col gap-4">{children}</div>
|
<div className="flex flex-col gap-4">{children}</div>
|
||||||
<div className="flex justify-between items-center mt-8">
|
<div className="flex justify-between items-center mt-8">
|
||||||
<div>
|
<div>
|
||||||
@@ -30,7 +43,11 @@ const ModalShell: React.FC<ModalShellProps> = ({ title, edit, onClose, onSave, o
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-end gap-3">
|
<div className="flex justify-end gap-3">
|
||||||
<button onClick={onSave} className="liquid-button liquid-button-success liquid-focus py-2.5 px-5">
|
<button
|
||||||
|
onClick={onSave}
|
||||||
|
disabled={!canSave}
|
||||||
|
className="liquid-button liquid-button-success liquid-focus py-2.5 px-5 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
Save
|
Save
|
||||||
</button>
|
</button>
|
||||||
<button onClick={onClose} className="liquid-button liquid-button-secondary liquid-focus py-2.5 px-5">
|
<button onClick={onClose} className="liquid-button liquid-button-secondary liquid-focus py-2.5 px-5">
|
||||||
|
|||||||
+52
-38
@@ -1,15 +1,13 @@
|
|||||||
import { useState, useEffect, useRef } from 'react';
|
import { memo, useState, useEffect, useRef } from 'react';
|
||||||
import { Server } from '../types';
|
import { Server } from '../types';
|
||||||
import ping from './utils/jsping.js';
|
import ping from './utils/jsping';
|
||||||
|
|
||||||
interface ServerWidgetProps {
|
interface ServerWidgetProps {
|
||||||
config: {
|
|
||||||
serverWidget: {
|
serverWidget: {
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
pingFrequency: number;
|
pingFrequency: number;
|
||||||
servers: Server[];
|
servers: Server[];
|
||||||
};
|
};
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATUS_COLORS: Record<string, string> = {
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
@@ -20,57 +18,73 @@ const STATUS_COLORS: Record<string, string> = {
|
|||||||
const getStatusColor = (status: string): string =>
|
const getStatusColor = (status: string): string =>
|
||||||
STATUS_COLORS[status] ?? 'bg-slate-400 text-slate-400';
|
STATUS_COLORS[status] ?? 'bg-slate-400 text-slate-400';
|
||||||
|
|
||||||
const ServerWidget: React.FC<ServerWidgetProps> = ({ config }) => {
|
const ServerWidget: React.FC<ServerWidgetProps> = ({ serverWidget }) => {
|
||||||
const [serverStatus, setServerStatus] = useState<Record<string, string>>({});
|
const [serverStatus, setServerStatus] = useState<Record<string, string>>({});
|
||||||
const serversRef = useRef(config.serverWidget.servers);
|
const serversRef = useRef(serverWidget.servers);
|
||||||
serversRef.current = config.serverWidget.servers;
|
serversRef.current = serverWidget.servers;
|
||||||
|
|
||||||
const serversSignature = config.serverWidget.servers
|
const serversSignature = JSON.stringify(serverWidget.servers.map(s => [s.id, s.address]));
|
||||||
.map(s => `${s.id}:${s.address}`)
|
|
||||||
.join('|');
|
|
||||||
const serverCount = config.serverWidget.servers.length;
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!config.serverWidget.enabled) return;
|
if (!serverWidget.enabled || serversRef.current.length === 0) return;
|
||||||
|
|
||||||
const pingServers = () => {
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
const pending: Record<string, string> = {};
|
let controller: AbortController | undefined;
|
||||||
for (const s of serversRef.current) pending[s.id] = 'pending';
|
let cancelled = false;
|
||||||
setServerStatus(prev => ({ ...prev, ...pending }));
|
const frequency = Math.min(60, Math.max(5, serverWidget.pingFrequency || 15)) * 1000;
|
||||||
|
setServerStatus(Object.fromEntries(serversRef.current.map(server => [server.id, 'pending'])));
|
||||||
|
|
||||||
serversRef.current.forEach((server) => {
|
const pingServers = async () => {
|
||||||
ping(server.address)
|
if (cancelled || document.visibilityState !== 'visible') return;
|
||||||
.then(() => {
|
const cycle = new AbortController();
|
||||||
setServerStatus(prev =>
|
controller = cycle;
|
||||||
prev[server.id] === 'online' ? prev : { ...prev, [server.id]: 'online' }
|
const servers = serversRef.current;
|
||||||
);
|
const statuses: Record<string, string> = {};
|
||||||
})
|
let next = 0;
|
||||||
.catch(() => {
|
await Promise.all(Array.from({ length: Math.min(4, servers.length) }, async () => {
|
||||||
setServerStatus(prev =>
|
while (next < servers.length && !cycle.signal.aborted) {
|
||||||
prev[server.id] === 'offline' ? prev : { ...prev, [server.id]: 'offline' }
|
const server = servers[next++];
|
||||||
);
|
try {
|
||||||
});
|
await ping(server.address, 1, cycle.signal);
|
||||||
});
|
statuses[server.id] = 'online';
|
||||||
|
} catch {
|
||||||
|
statuses[server.id] = 'offline';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
if (cancelled || cycle.signal.aborted) return;
|
||||||
|
setServerStatus(previous => servers.every(server => previous[server.id] === statuses[server.id])
|
||||||
|
? previous : statuses);
|
||||||
|
timer = setTimeout(() => void pingServers(), frequency);
|
||||||
|
};
|
||||||
|
const onVisibilityChange = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
controller?.abort();
|
||||||
|
if (document.visibilityState === 'visible') void pingServers();
|
||||||
};
|
};
|
||||||
|
|
||||||
pingServers();
|
void pingServers();
|
||||||
const interval = setInterval(pingServers, config.serverWidget.pingFrequency * 1000);
|
document.addEventListener('visibilitychange', onVisibilityChange);
|
||||||
return () => clearInterval(interval);
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
controller?.abort();
|
||||||
|
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||||
|
};
|
||||||
}, [
|
}, [
|
||||||
config.serverWidget.enabled,
|
serverWidget.enabled,
|
||||||
config.serverWidget.pingFrequency,
|
serverWidget.pingFrequency,
|
||||||
serversSignature,
|
serversSignature,
|
||||||
serverCount,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (!config.serverWidget.enabled) {
|
if (!serverWidget.enabled) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed bottom-3 left-1/2 z-20 w-auto max-w-[calc(100%-1.5rem)] -translate-x-1/2">
|
<div className="fixed bottom-3 left-1/2 z-20 w-auto max-w-[calc(100%-1.5rem)] -translate-x-1/2">
|
||||||
<div className="liquid-surface flex items-center gap-4 rounded-full px-4 py-2">
|
<div className="liquid-surface flex items-center gap-4 rounded-full px-4 py-2">
|
||||||
{config.serverWidget.servers.map((server) => (
|
{serverWidget.servers.map((server) => (
|
||||||
<div key={server.id} className="flex items-center gap-2">
|
<div key={server.id} className="flex items-center gap-2">
|
||||||
<div className={`liquid-status-dot w-2.5 h-2.5 rounded-full ${getStatusColor(serverStatus[server.id])}`}></div>
|
<div className={`liquid-status-dot w-2.5 h-2.5 rounded-full ${getStatusColor(serverStatus[server.id])}`}></div>
|
||||||
<span className="text-slate-100 text-sm font-medium">
|
<span className="text-slate-100 text-sm font-medium">
|
||||||
@@ -83,4 +97,4 @@ const ServerWidget: React.FC<ServerWidgetProps> = ({ config }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ServerWidget;
|
export default memo(ServerWidget);
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { memo, useState, useEffect } from 'react';
|
||||||
import { baseWallpapers } from './utils/baseWallpapers';
|
import { baseWallpapers } from './utils/baseWallpapers';
|
||||||
import { Wallpaper as WallpaperType } from '../types';
|
import { Wallpaper as WallpaperType } from '../types';
|
||||||
import { getWallpaperFromChromeStorageLocal } from './utils/StorageLocalManager';
|
import { getWallpaperFromChromeStorageLocal } from './utils/StorageLocalManager';
|
||||||
import { getRandomWallpaperIndex, getWallpaperFrequencyMs, loadWallpaperState, saveWallpaperState } from './utils/wallpaperUtils';
|
import { getRandomWallpaperIndex, getWallpaperFrequencyMs, loadWallpaperState, saveWallpaperState } from './utils/wallpaperUtils';
|
||||||
|
import { ConfigurationService } from './services/ConfigurationService';
|
||||||
|
|
||||||
interface WallpaperProps {
|
interface WallpaperProps {
|
||||||
wallpaperNames: string[];
|
wallpaperNames: string[];
|
||||||
@@ -17,6 +18,7 @@ const MAX_WALLPAPER_URL_CACHE = 3;
|
|||||||
const wallpaperUrlCache = new Map<string, string | undefined>();
|
const wallpaperUrlCache = new Map<string, string | undefined>();
|
||||||
|
|
||||||
const rememberWallpaperUrl = (name: string, resolved: string | undefined): void => {
|
const rememberWallpaperUrl = (name: string, resolved: string | undefined): void => {
|
||||||
|
if (resolved?.startsWith('data:')) return;
|
||||||
wallpaperUrlCache.set(name, resolved);
|
wallpaperUrlCache.set(name, resolved);
|
||||||
while (wallpaperUrlCache.size > MAX_WALLPAPER_URL_CACHE) {
|
while (wallpaperUrlCache.size > MAX_WALLPAPER_URL_CACHE) {
|
||||||
const oldest = wallpaperUrlCache.keys().next().value;
|
const oldest = wallpaperUrlCache.keys().next().value;
|
||||||
@@ -25,9 +27,56 @@ const rememberWallpaperUrl = (name: string, resolved: string | undefined): void
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MAX_WALLPAPER_OBJECT_URLS = 2;
|
||||||
|
const wallpaperObjectUrls = new Map<string, string>();
|
||||||
|
|
||||||
|
const revokeWallpaperObjectUrls = (keepNames?: string[]): void => {
|
||||||
|
for (const [name, url] of wallpaperObjectUrls) {
|
||||||
|
if (keepNames?.includes(name)) continue;
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
wallpaperObjectUrls.delete(name);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const rememberWallpaperObjectUrl = (name: string, url: string): string => {
|
||||||
|
const existing = wallpaperObjectUrls.get(name);
|
||||||
|
if (existing) {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
wallpaperObjectUrls.set(name, url);
|
||||||
|
while (wallpaperObjectUrls.size > MAX_WALLPAPER_OBJECT_URLS) {
|
||||||
|
const [oldestName, oldestUrl] = wallpaperObjectUrls.entries().next().value ?? [];
|
||||||
|
if (oldestName === undefined || oldestUrl === undefined) break;
|
||||||
|
URL.revokeObjectURL(oldestUrl);
|
||||||
|
wallpaperObjectUrls.delete(oldestName);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
};
|
||||||
|
|
||||||
|
const dataUrlToObjectUrl = (dataUrl: string): string => {
|
||||||
|
const header = dataUrl.match(/^data:([^;,]*)((?:;[^;,]*)*),/);
|
||||||
|
if (!header || typeof URL.createObjectURL !== 'function') return dataUrl;
|
||||||
|
try {
|
||||||
|
const payload = dataUrl.slice(header[0].length);
|
||||||
|
const type = header[1] || 'application/octet-stream';
|
||||||
|
if (!/;base64/i.test(header[2])) {
|
||||||
|
return URL.createObjectURL(new Blob([decodeURIComponent(payload)], { type }));
|
||||||
|
}
|
||||||
|
const binary = atob(payload);
|
||||||
|
const bytes = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||||
|
return URL.createObjectURL(new Blob([bytes], { type }));
|
||||||
|
} catch {
|
||||||
|
return dataUrl;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const getWallpaperUrlByName = async (name: string): Promise<string | undefined> => {
|
const getWallpaperUrlByName = async (name: string): Promise<string | undefined> => {
|
||||||
if (!name) return undefined;
|
if (!name) return undefined;
|
||||||
if (wallpaperUrlCache.has(name)) return wallpaperUrlCache.get(name);
|
if (wallpaperUrlCache.has(name)) return wallpaperUrlCache.get(name);
|
||||||
|
const objectUrl = wallpaperObjectUrls.get(name);
|
||||||
|
if (objectUrl) return objectUrl;
|
||||||
|
|
||||||
let resolved: string | undefined;
|
let resolved: string | undefined;
|
||||||
const foundInBase = baseWallpapers.find((w: WallpaperType) => w.name === name);
|
const foundInBase = baseWallpapers.find((w: WallpaperType) => w.name === name);
|
||||||
@@ -35,8 +84,7 @@ const getWallpaperUrlByName = async (name: string): Promise<string | undefined>
|
|||||||
resolved = foundInBase.url || foundInBase.base64;
|
resolved = foundInBase.url || foundInBase.base64;
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
const storedUserWallpapers: WallpaperType[] =
|
const storedUserWallpapers = ConfigurationService.loadUserWallpapers();
|
||||||
JSON.parse(localStorage.getItem('userWallpapers') || '[]');
|
|
||||||
const foundInUser = storedUserWallpapers.find((w: WallpaperType) => w.name === name);
|
const foundInUser = storedUserWallpapers.find((w: WallpaperType) => w.name === name);
|
||||||
if (foundInUser) {
|
if (foundInUser) {
|
||||||
resolved = foundInUser.url || foundInUser.base64;
|
resolved = foundInUser.url || foundInUser.base64;
|
||||||
@@ -55,10 +103,22 @@ const getWallpaperUrlByName = async (name: string): Promise<string | undefined>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (resolved?.startsWith('data:')) {
|
||||||
|
const url = dataUrlToObjectUrl(resolved);
|
||||||
|
return url.startsWith('blob:') ? rememberWallpaperObjectUrl(name, url) : url;
|
||||||
|
}
|
||||||
rememberWallpaperUrl(name, resolved);
|
rememberWallpaperUrl(name, resolved);
|
||||||
return resolved;
|
return resolved;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getWallpaperFilter = (blur: number, brightness: number): string => {
|
||||||
|
const filters = [
|
||||||
|
blur > 0 ? `blur(${blur}px)` : '',
|
||||||
|
brightness !== 100 ? `brightness(${brightness / 100})` : '',
|
||||||
|
].filter(Boolean);
|
||||||
|
return filters.length > 0 ? filters.join(' ') : 'none';
|
||||||
|
};
|
||||||
|
|
||||||
const Wallpaper: React.FC<WallpaperProps> = ({ wallpaperNames, blur, brightness, opacity, wallpaperFrequency, wallpaperVersion }) => {
|
const Wallpaper: React.FC<WallpaperProps> = ({ wallpaperNames, blur, brightness, opacity, wallpaperFrequency, wallpaperVersion }) => {
|
||||||
const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);
|
const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);
|
||||||
|
|
||||||
@@ -67,10 +127,12 @@ const Wallpaper: React.FC<WallpaperProps> = ({ wallpaperNames, blur, brightness,
|
|||||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
let revision = 0;
|
let revision = 0;
|
||||||
wallpaperUrlCache.clear();
|
wallpaperUrlCache.clear();
|
||||||
|
revokeWallpaperObjectUrls(wallpaperNames);
|
||||||
|
|
||||||
const updateWallpaper = async () => {
|
const updateWallpaper = async () => {
|
||||||
const request = ++revision;
|
const request = ++revision;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
|
if (document.visibilityState !== 'visible') return;
|
||||||
if (wallpaperNames.length === 0) {
|
if (wallpaperNames.length === 0) {
|
||||||
setImageUrl(undefined);
|
setImageUrl(undefined);
|
||||||
saveWallpaperState([], 0, loadWallpaperState([]).lastChange);
|
saveWallpaperState([], 0, loadWallpaperState([]).lastChange);
|
||||||
@@ -109,10 +171,15 @@ const Wallpaper: React.FC<WallpaperProps> = ({ wallpaperNames, blur, brightness,
|
|||||||
};
|
};
|
||||||
const onVisibilityChange = () => {
|
const onVisibilityChange = () => {
|
||||||
if (document.visibilityState === 'visible') refresh();
|
if (document.visibilityState === 'visible') refresh();
|
||||||
|
else {
|
||||||
|
++revision;
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const onStorage = (event: StorageEvent) => {
|
const onStorage = (event: StorageEvent) => {
|
||||||
if (event.key === 'wallpaperState' || event.key === 'userWallpapers' || event.key === null) {
|
if (event.key === 'wallpaperState' || event.key === 'userWallpapers' || event.key === null) {
|
||||||
wallpaperUrlCache.clear();
|
wallpaperUrlCache.clear();
|
||||||
|
if (event.key !== 'wallpaperState') revokeWallpaperObjectUrls();
|
||||||
refresh();
|
refresh();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -124,12 +191,15 @@ const Wallpaper: React.FC<WallpaperProps> = ({ wallpaperNames, blur, brightness,
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
|
wallpaperUrlCache.clear();
|
||||||
document.removeEventListener('visibilitychange', onVisibilityChange);
|
document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||||
window.removeEventListener('focus', refresh);
|
window.removeEventListener('focus', refresh);
|
||||||
window.removeEventListener('storage', onStorage);
|
window.removeEventListener('storage', onStorage);
|
||||||
};
|
};
|
||||||
}, [wallpaperNames, wallpaperFrequency, wallpaperVersion]);
|
}, [wallpaperNames, wallpaperFrequency, wallpaperVersion]);
|
||||||
|
|
||||||
|
useEffect(() => () => revokeWallpaperObjectUrls(), []);
|
||||||
|
|
||||||
if (!imageUrl) return null;
|
if (!imageUrl) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -137,8 +207,9 @@ const Wallpaper: React.FC<WallpaperProps> = ({ wallpaperNames, blur, brightness,
|
|||||||
<div
|
<div
|
||||||
className="wallpaper-layer wallpaper-transition"
|
className="wallpaper-layer wallpaper-transition"
|
||||||
style={{
|
style={{
|
||||||
backgroundImage: `url(${imageUrl})`,
|
backgroundImage: `url(${JSON.stringify(imageUrl)})`,
|
||||||
filter: `blur(${blur}px) brightness(${brightness / 100})`,
|
filter: getWallpaperFilter(blur, brightness),
|
||||||
|
transform: blur > 0 ? 'scale(1.015)' : 'none',
|
||||||
opacity: opacity / 100,
|
opacity: opacity / 100,
|
||||||
}}
|
}}
|
||||||
aria-label="Wallpaper background"
|
aria-label="Wallpaper background"
|
||||||
@@ -148,4 +219,4 @@ const Wallpaper: React.FC<WallpaperProps> = ({ wallpaperNames, blur, brightness,
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Wallpaper;
|
export default memo(Wallpaper);
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useState, useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { Website } from '../types';
|
import { Website } from '../types';
|
||||||
import { getWebsiteIcon } from './utils/iconService';
|
import { getWebsiteIcon } from './utils/iconService';
|
||||||
|
import { normalizeWebsiteUrl } from './utils/urlUtils';
|
||||||
import ModalShell from './ModalShell';
|
import ModalShell from './ModalShell';
|
||||||
|
|
||||||
interface WebsiteEditModalProps {
|
interface WebsiteEditModalProps {
|
||||||
@@ -14,57 +15,60 @@ interface WebsiteEditModalProps {
|
|||||||
interface IconMetadata {
|
interface IconMetadata {
|
||||||
name: string;
|
name: string;
|
||||||
base: string;
|
base: string;
|
||||||
aliases: string[];
|
colors: string[];
|
||||||
categories: string[];
|
|
||||||
update: {
|
|
||||||
timestamp: string;
|
|
||||||
author: {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
colors: any;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let iconMetadataCache: IconMetadata[] | null = null;
|
|
||||||
|
|
||||||
const getIconPickUrl = (iconData: IconMetadata): string =>
|
const getIconPickUrl = (iconData: IconMetadata): string =>
|
||||||
`https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/${iconData.base}/${iconData.name}.${iconData.base}`;
|
`https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/${iconData.base}/${iconData.name}.${iconData.base}`;
|
||||||
|
|
||||||
|
const isIconUrl = (value: string): boolean => /^(https?:|data:image\/)/i.test(value.trim());
|
||||||
|
|
||||||
const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onClose, onSave, onDelete }) => {
|
const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onClose, onSave, onDelete }) => {
|
||||||
const [name, setName] = useState(website ? website.name : '');
|
const [name, setName] = useState(website ? website.name : '');
|
||||||
const [url, setUrl] = useState(website ? website.url : '');
|
const [url, setUrl] = useState(website ? website.url : '');
|
||||||
const [icon, setIcon] = useState(website ? website.icon : '');
|
const [icon, setIcon] = useState(website ? website.icon : '');
|
||||||
const [iconQuery, setIconQuery] = useState('');
|
const [iconQuery, setIconQuery] = useState('');
|
||||||
const [filteredIcons, setFilteredIcons] = useState<IconMetadata[]>([]);
|
const [filteredIcons, setFilteredIcons] = useState<IconMetadata[]>([]);
|
||||||
const [iconMetadata, setIconMetadata] = useState<IconMetadata[]>(() => iconMetadataCache ?? []);
|
const [iconMetadata, setIconMetadata] = useState<IconMetadata[]>([]);
|
||||||
const [iconsFetched, setIconsFetched] = useState(() => iconMetadataCache !== null);
|
const [previewFailed, setPreviewFailed] = useState(false);
|
||||||
|
const metadataRequest = useRef<AbortController | null>(null);
|
||||||
const debounceRef = useRef<number | null>(null);
|
const debounceRef = useRef<number | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
iconMetadataCache = null;
|
metadataRequest.current?.abort();
|
||||||
|
if (debounceRef.current !== null) window.clearTimeout(debounceRef.current);
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const ensureIconMetadata = () => {
|
const ensureIconMetadata = () => {
|
||||||
if (iconMetadataCache) {
|
if (iconMetadata.length > 0 || metadataRequest.current) return;
|
||||||
setIconMetadata(iconMetadataCache);
|
const controller = new AbortController();
|
||||||
return;
|
metadataRequest.current = controller;
|
||||||
}
|
const timeout = window.setTimeout(() => controller.abort(), 10_000);
|
||||||
if (iconsFetched) return;
|
fetch(new URL('icon-metadata.json', document.baseURI).href, { cache: 'force-cache', signal: controller.signal })
|
||||||
setIconsFetched(true);
|
.then(response => {
|
||||||
fetch('/icon-metadata.json', { cache: 'force-cache' })
|
if (!response.ok) throw new Error('Icon metadata is unavailable');
|
||||||
.then(response => response.json())
|
return response.json();
|
||||||
|
})
|
||||||
.then(data => {
|
.then(data => {
|
||||||
const iconsArray: IconMetadata[] = Object.entries(data).map(([name, details]) => ({
|
if (controller.signal.aborted) return;
|
||||||
name,
|
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid icon metadata');
|
||||||
...(details as object),
|
const iconsArray: IconMetadata[] = Object.entries(data).flatMap(([name, details]) => {
|
||||||
})) as IconMetadata[];
|
if (!details || typeof details !== 'object' || !('base' in details) || typeof details.base !== 'string') return [];
|
||||||
iconMetadataCache = iconsArray;
|
const colors = 'colors' in details && details.colors && typeof details.colors === 'object'
|
||||||
|
? Object.values(details.colors).filter((color): color is string => typeof color === 'string' && color !== name) : [];
|
||||||
|
return [{ name, base: details.base, colors }];
|
||||||
|
});
|
||||||
setIconMetadata(iconsArray);
|
setIconMetadata(iconsArray);
|
||||||
})
|
})
|
||||||
.catch(err => console.error('Failed to load icon metadata', err));
|
.catch(err => {
|
||||||
|
if (!controller.signal.aborted) console.error('Failed to load icon metadata', err);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
window.clearTimeout(timeout);
|
||||||
|
if (metadataRequest.current === controller) metadataRequest.current = null;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -78,9 +82,8 @@ const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onCl
|
|||||||
filtered.push(ic);
|
filtered.push(ic);
|
||||||
if (filtered.length >= 50) break;
|
if (filtered.length >= 50) break;
|
||||||
}
|
}
|
||||||
if (ic.colors && typeof ic.colors === 'object') {
|
if (ic.colors.length > 0) {
|
||||||
const colors = Object.values(ic.colors).filter(key => typeof key === 'string' && key !== ic.name);
|
for (const color of ic.colors) {
|
||||||
for (const color of colors as string[]) {
|
|
||||||
if (color.toLowerCase().includes(lowerCaseQuery)) {
|
if (color.toLowerCase().includes(lowerCaseQuery)) {
|
||||||
filtered.push({ ...ic, name: color });
|
filtered.push({ ...ic, name: color });
|
||||||
if (filtered.length >= 50) break;
|
if (filtered.length >= 50) break;
|
||||||
@@ -99,10 +102,36 @@ const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onCl
|
|||||||
}
|
}
|
||||||
}, [iconQuery, iconMetadata]);
|
}, [iconQuery, iconMetadata]);
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
const normalizedUrl = normalizeWebsiteUrl(url);
|
||||||
|
if (!normalizedUrl) {
|
||||||
|
alert('Please enter a valid website URL (http, https, ftp, or mailto).');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSave({ id: website?.id, name: name.trim(), url: normalizedUrl, icon: resolveIcon(icon) });
|
||||||
|
};
|
||||||
|
|
||||||
|
const resolveIcon = (value: string): string => {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (!trimmed || isIconUrl(trimmed)) return trimmed;
|
||||||
|
const query = trimmed.toLowerCase();
|
||||||
|
for (const ic of iconMetadata) {
|
||||||
|
if (ic.name.toLowerCase() === query) return getIconPickUrl(ic);
|
||||||
|
const color = ic.colors.find(c => c.toLowerCase() === query);
|
||||||
|
if (color) return getIconPickUrl({ ...ic, name: color });
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateIcon = (value: string) => {
|
||||||
|
setIcon(value);
|
||||||
|
setPreviewFailed(false);
|
||||||
|
};
|
||||||
|
|
||||||
const fetchIcon = async () => {
|
const fetchIcon = async () => {
|
||||||
if (url) {
|
if (url) {
|
||||||
const fetchedIcon = await getWebsiteIcon(url);
|
const fetchedIcon = await getWebsiteIcon(url);
|
||||||
setIcon(fetchedIcon);
|
if (fetchedIcon) updateIcon(fetchedIcon);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -111,12 +140,13 @@ const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onCl
|
|||||||
title={edit ? 'Edit Website' : 'Add Website'}
|
title={edit ? 'Edit Website' : 'Add Website'}
|
||||||
edit={edit}
|
edit={edit}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
onSave={() => onSave({ id: website?.id, name, url, icon })}
|
onSave={handleSave}
|
||||||
|
canSave={name.trim() !== '' && url.trim() !== ''}
|
||||||
onDelete={edit ? onDelete : undefined}
|
onDelete={edit ? onDelete : undefined}
|
||||||
>
|
>
|
||||||
<div className="flex justify-center mb-4">
|
<div className="flex justify-center mb-4">
|
||||||
{icon ? (
|
{isIconUrl(icon) && !previewFailed ? (
|
||||||
<img src={icon} alt="Website Icon" className="h-24 w-24 object-contain" />
|
<img src={icon.trim()} alt="Website Icon" className="h-24 w-24 object-contain" onError={() => setPreviewFailed(true)} />
|
||||||
) : (
|
) : (
|
||||||
<div className="liquid-surface h-24 w-24 rounded-2xl flex items-center justify-center">
|
<div className="liquid-surface h-24 w-24 rounded-2xl flex items-center justify-center">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" className="text-white/50">
|
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" className="text-white/50">
|
||||||
@@ -148,7 +178,7 @@ const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onCl
|
|||||||
placeholder="Icon URL or name"
|
placeholder="Icon URL or name"
|
||||||
value={icon}
|
value={icon}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setIcon(e.target.value);
|
updateIcon(e.target.value);
|
||||||
setIconQuery(e.target.value);
|
setIconQuery(e.target.value);
|
||||||
}}
|
}}
|
||||||
onFocus={ensureIconMetadata}
|
onFocus={ensureIconMetadata}
|
||||||
@@ -160,7 +190,8 @@ const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onCl
|
|||||||
<div
|
<div
|
||||||
key={`${iconData.name}-${index}`}
|
key={`${iconData.name}-${index}`}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setIcon(getIconPickUrl(iconData));
|
updateIcon(getIconPickUrl(iconData));
|
||||||
|
setIconQuery('');
|
||||||
setFilteredIcons([]);
|
setFilteredIcons([]);
|
||||||
}}
|
}}
|
||||||
className="cursor-pointer flex items-center p-2 transition-colors duration-150 ease-ios hover:bg-white/20"
|
className="cursor-pointer flex items-center p-2 transition-colors duration-150 ease-ios hover:bg-white/20"
|
||||||
@@ -168,6 +199,8 @@ const WebsiteEditModal: React.FC<WebsiteEditModalProps> = ({ website, edit, onCl
|
|||||||
<img
|
<img
|
||||||
src={getIconPickUrl(iconData)}
|
src={getIconPickUrl(iconData)}
|
||||||
alt={iconData.name}
|
alt={iconData.name}
|
||||||
|
loading="lazy"
|
||||||
|
decoding="async"
|
||||||
className="h-6 w-6 mr-2"
|
className="h-6 w-6 mr-2"
|
||||||
/>
|
/>
|
||||||
<span>{iconData.name}</span>
|
<span>{iconData.name}</span>
|
||||||
|
|||||||
+37
-11
@@ -1,6 +1,6 @@
|
|||||||
import React, { memo, useEffect, useState } from 'react';
|
import React, { memo, useEffect, useRef, useState } from 'react';
|
||||||
import { Website } from '../types';
|
import { Website } from '../types';
|
||||||
import { cacheWebsiteIcon, getCachedWebsiteIcon, removeCachedWebsiteIcon } from './utils/iconService';
|
import { cacheWebsiteIcon, getCachedWebsiteIcon, getInitialIconSource, removeCachedWebsiteIcon } from './utils/iconService';
|
||||||
import { getTileSizeClass, getIconPixelSize, getIconLoadingPixelSize } from './utils/styleUtils';
|
import { getTileSizeClass, getIconPixelSize, getIconLoadingPixelSize } from './utils/styleUtils';
|
||||||
import { ChevronLeftIcon, ChevronRightIcon, PencilIcon } from './icons';
|
import { ChevronLeftIcon, ChevronRightIcon, PencilIcon } from './icons';
|
||||||
|
|
||||||
@@ -12,16 +12,33 @@ interface WebsiteTileProps {
|
|||||||
tileSize?: string;
|
tileSize?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const LOADING_RESET_MS = 10_000;
|
||||||
|
|
||||||
|
const isNavigableUrl = (url: string): boolean => /^https?:/i.test(url);
|
||||||
|
|
||||||
const WebsiteTile: React.FC<WebsiteTileProps> = ({ website, isEditing, onEdit, onMove, tileSize }) => {
|
const WebsiteTile: React.FC<WebsiteTileProps> = ({ website, isEditing, onEdit, onMove, tileSize }) => {
|
||||||
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [iconSource, setIconSource] = useState<string | null>(null);
|
const [iconSource, setIconSource] = useState<string | null | undefined>(() => getInitialIconSource(website.icon));
|
||||||
const [usingCachedIcon, setUsingCachedIcon] = useState(false);
|
const [usingCachedIcon, setUsingCachedIcon] = useState(false);
|
||||||
|
const loadingTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const resetLoading = () => {
|
||||||
|
clearTimeout(loadingTimer.current);
|
||||||
|
setIsLoading(false);
|
||||||
|
};
|
||||||
|
window.addEventListener('pageshow', resetLoading);
|
||||||
|
return () => {
|
||||||
|
clearTimeout(loadingTimer.current);
|
||||||
|
window.removeEventListener('pageshow', resetLoading);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|
||||||
setIconSource(null);
|
setIconSource(getInitialIconSource(website.icon));
|
||||||
setUsingCachedIcon(false);
|
setUsingCachedIcon(false);
|
||||||
|
|
||||||
const loadIcon = async () => {
|
const loadIcon = async () => {
|
||||||
@@ -34,7 +51,7 @@ const WebsiteTile: React.FC<WebsiteTileProps> = ({ website, isEditing, onEdit, o
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setIconSource(website.icon);
|
setIconSource(website.icon || null);
|
||||||
const newlyCachedIcon = await cacheWebsiteIcon(website.icon);
|
const newlyCachedIcon = await cacheWebsiteIcon(website.icon);
|
||||||
if (!cancelled && newlyCachedIcon) {
|
if (!cancelled && newlyCachedIcon) {
|
||||||
setIconSource(newlyCachedIcon);
|
setIconSource(newlyCachedIcon);
|
||||||
@@ -50,7 +67,10 @@ const WebsiteTile: React.FC<WebsiteTileProps> = ({ website, isEditing, onEdit, o
|
|||||||
}, [website.icon]);
|
}, [website.icon]);
|
||||||
|
|
||||||
const handleIconError = () => {
|
const handleIconError = () => {
|
||||||
if (!usingCachedIcon) return;
|
if (!usingCachedIcon) {
|
||||||
|
setIconSource(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
setIconSource(website.icon);
|
setIconSource(website.icon);
|
||||||
setUsingCachedIcon(false);
|
setUsingCachedIcon(false);
|
||||||
void removeCachedWebsiteIcon(website.icon);
|
void removeCachedWebsiteIcon(website.icon);
|
||||||
@@ -61,11 +81,14 @@ const WebsiteTile: React.FC<WebsiteTileProps> = ({ website, isEditing, onEdit, o
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!e.defaultPrevented && e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey && isNavigableUrl(website.url)) {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
clearTimeout(loadingTimer.current);
|
||||||
|
loadingTimer.current = setTimeout(() => setIsLoading(false), LOADING_RESET_MS);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const iconSizeClass = `w-[${getIconPixelSize(tileSize)}px] h-[${getIconPixelSize(tileSize)}px]`;
|
const iconSize = isLoading ? getIconLoadingPixelSize(tileSize) : getIconPixelSize(tileSize);
|
||||||
const iconSizeLoadingClass = `w-[${getIconLoadingPixelSize(tileSize)}px] h-[${getIconLoadingPixelSize(tileSize)}px]`;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`relative ${getTileSizeClass(tileSize)} transition-all duration-200 ease-ios ${isEditing ? 'mb-4' : ''}`}>
|
<div className={`relative ${getTileSizeClass(tileSize)} transition-all duration-200 ease-ios ${isEditing ? 'mb-4' : ''}`}>
|
||||||
@@ -86,15 +109,18 @@ const WebsiteTile: React.FC<WebsiteTileProps> = ({ website, isEditing, onEdit, o
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className={`relative z-10 flex items-center transition-all duration-200 ease-ios ${isLoading ? 'translate-y-5 gap-2' : 'flex-col gap-3'}`}>
|
<div className={`relative z-10 flex items-center transition-all duration-200 ease-ios ${isLoading ? 'translate-y-5 gap-2' : 'flex-col gap-3'}`}>
|
||||||
<div className={`transition-all duration-200 ease-ios drop-shadow-[0_10px_20px_rgba(0,0,0,0.28)] ${isLoading ? iconSizeLoadingClass : iconSizeClass}`}>
|
<div className="flex items-center justify-center transition-all duration-200 ease-ios drop-shadow-[0_10px_20px_rgba(0,0,0,0.28)]" style={{ width: iconSize, height: iconSize }}>
|
||||||
{iconSource && (
|
{iconSource ? (
|
||||||
<img
|
<img
|
||||||
src={iconSource}
|
src={iconSource}
|
||||||
alt={`${website.name} icon`}
|
alt={`${website.name} icon`}
|
||||||
className="object-contain w-full h-full"
|
className="object-contain w-full h-full"
|
||||||
|
decoding="async"
|
||||||
onError={handleIconError}
|
onError={handleIconError}
|
||||||
/>
|
/>
|
||||||
)}
|
) : iconSource === null ? (
|
||||||
|
<span className="text-2xl font-semibold text-slate-300" aria-hidden="true">{website.name.charAt(0).toUpperCase()}</span>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<span className={`max-w-full px-1 text-slate-50 font-semibold text-base text-center leading-tight transition-all duration-200 ease-ios [text-shadow:0_2px_12px_rgba(2,6,23,0.44)] ${isLoading ? 'text-sm' : ''}`}>
|
<span className={`max-w-full px-1 text-slate-50 font-semibold text-base text-center leading-tight transition-all duration-200 ease-ios [text-shadow:0_2px_12px_rgba(2,6,23,0.44)] ${isLoading ? 'text-sm' : ''}`}>
|
||||||
{website.name}
|
{website.name}
|
||||||
|
|||||||
@@ -40,7 +40,6 @@ const ClockTab: React.FC<ClockTabProps> = ({ config, onChange }) => {
|
|||||||
onChange={(e) => updateClock({ font: e.target.value as string })}
|
onChange={(e) => updateClock({ font: e.target.value as string })}
|
||||||
options={[
|
options={[
|
||||||
{ value: 'Helvetica', label: 'Helvetica' },
|
{ value: 'Helvetica', label: 'Helvetica' },
|
||||||
{ value: `'Orbitron', sans-serif`, label: 'Orbitron' },
|
|
||||||
{ value: 'monospace', label: 'Monospace' },
|
{ value: 'monospace', label: 'Monospace' },
|
||||||
{ value: 'cursive', label: 'Cursive' },
|
{ value: 'cursive', label: 'Cursive' },
|
||||||
]}
|
]}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
|
import { DragDropContext, Droppable, Draggable, DropResult } from '@hello-pangea/dnd';
|
||||||
import ToggleSwitch from '../ToggleSwitch';
|
import ToggleSwitch from '../ToggleSwitch';
|
||||||
import { Config, Server } from '../../types';
|
import { Config, Server } from '../../types';
|
||||||
import RangeSlider from './RangeSlider';
|
import RangeSlider from './RangeSlider';
|
||||||
import { TrashIcon } from '../icons';
|
import { TrashIcon } from '../icons';
|
||||||
|
import { createId } from '../utils/idUtils';
|
||||||
|
import { parseServerAddress } from '../utils/urlUtils';
|
||||||
|
|
||||||
interface ServerWidgetTabProps {
|
interface ServerWidgetTabProps {
|
||||||
config: Config;
|
config: Config;
|
||||||
@@ -20,10 +22,16 @@ const ServerWidgetTab: React.FC<ServerWidgetTabProps> = ({ config, onChange }) =
|
|||||||
|
|
||||||
const handleAddServer = () => {
|
const handleAddServer = () => {
|
||||||
if (newServerName.trim() === '' || newServerAddress.trim() === '') return;
|
if (newServerName.trim() === '' || newServerAddress.trim() === '') return;
|
||||||
|
try {
|
||||||
|
parseServerAddress(newServerAddress);
|
||||||
|
} catch (error) {
|
||||||
|
alert(error instanceof Error && error.message.startsWith('Server') ? error.message : 'Please enter a valid server address, e.g. 192.168.1.10:8080 or https://example.com.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
const newServer: Server = {
|
const newServer: Server = {
|
||||||
id: Date.now().toString(),
|
id: createId(),
|
||||||
name: newServerName,
|
name: newServerName.trim(),
|
||||||
address: newServerAddress,
|
address: newServerAddress.trim(),
|
||||||
};
|
};
|
||||||
updateServerWidget({ servers: [...config.serverWidget.servers, newServer] });
|
updateServerWidget({ servers: [...config.serverWidget.servers, newServer] });
|
||||||
setNewServerName('');
|
setNewServerName('');
|
||||||
@@ -36,7 +44,7 @@ const ServerWidgetTab: React.FC<ServerWidgetTabProps> = ({ config, onChange }) =
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const onDragEnd = (result: any) => {
|
const onDragEnd = (result: DropResult) => {
|
||||||
if (!result.destination) return;
|
if (!result.destination) return;
|
||||||
const items = Array.from(config.serverWidget.servers);
|
const items = Array.from(config.serverWidget.servers);
|
||||||
const [reorderedItem] = items.splice(result.source.index, 1);
|
const [reorderedItem] = items.splice(result.source.index, 1);
|
||||||
|
|||||||
@@ -121,7 +121,10 @@ const ThemeTab: React.FC<ThemeTabProps> = ({
|
|||||||
>
|
>
|
||||||
<span className="truncate">{wallpaper.name}</span>
|
<span className="truncate">{wallpaper.name}</span>
|
||||||
<button
|
<button
|
||||||
onClick={() => onDeleteWallpaper(wallpaper)}
|
onClick={() => {
|
||||||
|
if (!wallpaper.url && !confirm(`Delete "${wallpaper.name}"? Uploaded wallpapers are not included in exports and cannot be recovered.`)) return;
|
||||||
|
void onDeleteWallpaper(wallpaper);
|
||||||
|
}}
|
||||||
className="liquid-edit-action liquid-focus text-red-300 hover:text-red-100"
|
className="liquid-edit-action liquid-focus text-red-300 hover:text-red-100"
|
||||||
aria-label={`Delete ${wallpaper.name}`}
|
aria-label={`Delete ${wallpaper.name}`}
|
||||||
>
|
>
|
||||||
@@ -179,13 +182,14 @@ const ThemeTab: React.FC<ThemeTabProps> = ({
|
|||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
<p className="mb-2 text-sm text-gray-400">
|
<p className="mb-2 text-sm text-gray-400">
|
||||||
<span className="font-semibold">Click to upload</span> or drag and drop
|
<span className="font-semibold">Click to upload</span>
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-gray-400">PNG, JPG, WEBP, etc.</p>
|
<p className="text-xs text-gray-400">PNG, JPG, WEBP, etc. (up to 20MB)</p>
|
||||||
</div>
|
</div>
|
||||||
<input
|
<input
|
||||||
id="file-upload"
|
id="file-upload"
|
||||||
type="file"
|
type="file"
|
||||||
|
accept="image/*"
|
||||||
className="hidden"
|
className="hidden"
|
||||||
onChange={handleFileUpload}
|
onChange={handleFileUpload}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
|
import { memo } from 'react';
|
||||||
|
|
||||||
interface ConfigurationButtonProps {
|
interface ConfigurationButtonProps {
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
}
|
}
|
||||||
@@ -21,4 +20,4 @@ const ConfigurationButton: React.FC<ConfigurationButtonProps> = ({ onClick }) =>
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ConfigurationButton;
|
export default memo(ConfigurationButton);
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { memo } from 'react';
|
||||||
import { PencilIcon } from '../icons';
|
import { PencilIcon } from '../icons';
|
||||||
|
|
||||||
interface EditButtonProps {
|
interface EditButtonProps {
|
||||||
@@ -20,4 +21,4 @@ const EditButton: React.FC<EditButtonProps> = ({ isEditing, onClick }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default EditButton;
|
export default memo(EditButton);
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { memo } from 'react';
|
||||||
import Clock from '../Clock';
|
import Clock from '../Clock';
|
||||||
import { Config } from '../../types';
|
import { Config } from '../../types';
|
||||||
import { getTitleSizeClass } from '../utils/styleUtils';
|
import { getTitleSizeClass } from '../utils/styleUtils';
|
||||||
@@ -29,4 +30,4 @@ const Header: React.FC<HeaderProps> = ({ config }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Header;
|
export default memo(Header);
|
||||||
@@ -1,10 +1,15 @@
|
|||||||
import { Config, Wallpaper } from '../../types';
|
import { Category, Config, Wallpaper } from '../../types';
|
||||||
|
import { DEFAULT_CATEGORIES } from '../../constants';
|
||||||
|
import { baseWallpapers } from '../utils/baseWallpapers';
|
||||||
import {
|
import {
|
||||||
addWallpaperToChromeStorageLocal,
|
addWallpaperToChromeStorageLocal,
|
||||||
checkChromeStorageLocalAvailable,
|
checkChromeStorageLocalAvailable,
|
||||||
removeWallpaperFromChromeStorageLocal,
|
removeWallpaperFromChromeStorageLocal,
|
||||||
} from '../utils/StorageLocalManager';
|
} from '../utils/StorageLocalManager';
|
||||||
import { getFileNameFromUrl } from '../utils/urlUtils';
|
import { getFileNameFromUrl, normalizeWebsiteUrl } from '../utils/urlUtils';
|
||||||
|
import { getWallpaperFrequencyHours } from '../utils/wallpaperUtils';
|
||||||
|
|
||||||
|
export const CLOCK_FONTS = ['Helvetica', 'monospace', 'cursive'];
|
||||||
|
|
||||||
const REQUIRED_LOCAL_STORAGE_KEYS = ['config', 'categories', 'userWallpapers', 'wallpaperState'] as const;
|
const REQUIRED_LOCAL_STORAGE_KEYS = ['config', 'categories', 'userWallpapers', 'wallpaperState'] as const;
|
||||||
type RequiredLocalStorageKey = typeof REQUIRED_LOCAL_STORAGE_KEYS[number];
|
type RequiredLocalStorageKey = typeof REQUIRED_LOCAL_STORAGE_KEYS[number];
|
||||||
@@ -12,7 +17,7 @@ type RequiredLocalStorageKey = typeof REQUIRED_LOCAL_STORAGE_KEYS[number];
|
|||||||
export const DEFAULT_CONFIG: Config = {
|
export const DEFAULT_CONFIG: Config = {
|
||||||
title: 'Vision Start',
|
title: 'Vision Start',
|
||||||
currentWallpapers: ['Beach'],
|
currentWallpapers: ['Beach'],
|
||||||
wallpaperFrequency: '1d',
|
wallpaperFrequency: '24h',
|
||||||
wallpaperBlur: 0,
|
wallpaperBlur: 0,
|
||||||
wallpaperBrightness: 108,
|
wallpaperBrightness: 108,
|
||||||
wallpaperOpacity: 96,
|
wallpaperOpacity: 96,
|
||||||
@@ -53,21 +58,136 @@ const deepMerge = <T>(base: T, stored: unknown): T => {
|
|||||||
const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };
|
const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };
|
||||||
const storedObj = isPlainObject(stored) ? stored : {};
|
const storedObj = isPlainObject(stored) ? stored : {};
|
||||||
for (const key of Object.keys(result)) {
|
for (const key of Object.keys(result)) {
|
||||||
if (Object.prototype.hasOwnProperty.call(storedObj, key)) {
|
result[key] = deepMerge(result[key], Object.prototype.hasOwnProperty.call(storedObj, key) ? storedObj[key] : undefined);
|
||||||
result[key] = deepMerge(result[key], storedObj[key]);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return result as T;
|
return result as T;
|
||||||
}
|
}
|
||||||
if (Array.isArray(base)) {
|
if (Array.isArray(base)) {
|
||||||
return (Array.isArray(stored) ? stored : base) as T;
|
return [...(Array.isArray(stored) ? stored : base)] as T;
|
||||||
}
|
}
|
||||||
if (stored === null) return base;
|
if (stored === null) return base;
|
||||||
return typeof stored === typeof base ? (stored as T) : base;
|
return typeof stored === typeof base ? (stored as T) : base;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const normalizeConfig = (stored: unknown): Config =>
|
const boundedNumber = (value: number, fallback: number, min: number, max: number): number =>
|
||||||
deepMerge(DEFAULT_CONFIG, stored);
|
Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
|
||||||
|
|
||||||
|
const choice = (value: string, values: string[], fallback: string): string =>
|
||||||
|
values.includes(value) ? value : fallback;
|
||||||
|
|
||||||
|
const hasStrings = (value: unknown, keys: string[]): value is Record<string, string> =>
|
||||||
|
isPlainObject(value) && keys.every(key => typeof value[key] === 'string');
|
||||||
|
|
||||||
|
export const normalizeConfig = (stored: unknown): Config => {
|
||||||
|
const config = deepMerge(DEFAULT_CONFIG, stored);
|
||||||
|
config.currentWallpapers = [...new Set(config.currentWallpapers.filter(name => typeof name === 'string' && name.length > 0))];
|
||||||
|
config.wallpaperFrequency = `${getWallpaperFrequencyHours(config.wallpaperFrequency)}h`;
|
||||||
|
config.wallpaperBlur = boundedNumber(config.wallpaperBlur, DEFAULT_CONFIG.wallpaperBlur, 0, 50);
|
||||||
|
config.wallpaperBrightness = boundedNumber(config.wallpaperBrightness, DEFAULT_CONFIG.wallpaperBrightness, 0, 200);
|
||||||
|
config.wallpaperOpacity = boundedNumber(config.wallpaperOpacity, DEFAULT_CONFIG.wallpaperOpacity, 1, 100);
|
||||||
|
config.titleSize = choice(config.titleSize, ['tiny', 'small', 'medium', 'large'], DEFAULT_CONFIG.titleSize);
|
||||||
|
config.tileSize = choice(config.tileSize || 'medium', ['small', 'medium', 'large'], 'medium');
|
||||||
|
config.alignment = choice(config.alignment, ['top', 'middle', 'bottom'], DEFAULT_CONFIG.alignment);
|
||||||
|
config.horizontalAlignment = choice(config.horizontalAlignment, ['left', 'middle', 'right'], DEFAULT_CONFIG.horizontalAlignment);
|
||||||
|
config.clock.size = choice(config.clock.size, ['tiny', 'small', 'medium', 'large'], DEFAULT_CONFIG.clock.size);
|
||||||
|
config.clock.font = choice(config.clock.font, CLOCK_FONTS, DEFAULT_CONFIG.clock.font);
|
||||||
|
config.clock.format = choice(config.clock.format, ['HH:mm', 'h:mm A'], DEFAULT_CONFIG.clock.format);
|
||||||
|
config.serverWidget.pingFrequency = boundedNumber(config.serverWidget.pingFrequency, DEFAULT_CONFIG.serverWidget.pingFrequency, 5, 60);
|
||||||
|
const serverIds = new Set<string>();
|
||||||
|
config.serverWidget.servers = config.serverWidget.servers.filter(server => {
|
||||||
|
if (!hasStrings(server, ['id', 'name', 'address']) || !server.id || serverIds.has(server.id)) return false;
|
||||||
|
serverIds.add(server.id);
|
||||||
|
return true;
|
||||||
|
}).map(server => ({ id: server.id, name: server.name, address: server.address }));
|
||||||
|
return config;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const normalizeCategories = (stored: unknown): Category[] => {
|
||||||
|
if (!Array.isArray(stored)) return normalizeCategories(DEFAULT_CATEGORIES);
|
||||||
|
const categoryIds = new Set<string>();
|
||||||
|
const websiteIds = new Set<string>();
|
||||||
|
return stored.flatMap(category => {
|
||||||
|
if (!hasStrings(category, ['id', 'name']) || !category.id || categoryIds.has(category.id)) return [];
|
||||||
|
categoryIds.add(category.id);
|
||||||
|
const websites = isPlainObject(category) && Array.isArray(category.websites) ? category.websites : [];
|
||||||
|
return [{
|
||||||
|
id: category.id,
|
||||||
|
name: category.name,
|
||||||
|
websites: websites.flatMap(website => {
|
||||||
|
if (!hasStrings(website, ['id', 'name', 'url']) || !website.id || websiteIds.has(website.id)) return [];
|
||||||
|
const url = normalizeWebsiteUrl(website.url);
|
||||||
|
if (!url) return [];
|
||||||
|
websiteIds.add(website.id);
|
||||||
|
return [{ id: website.id, name: website.name, url, icon: typeof website.icon === 'string' ? website.icon : '', categoryId: category.id }];
|
||||||
|
}),
|
||||||
|
}];
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const normalizeUserWallpapers = (stored: unknown): Wallpaper[] => {
|
||||||
|
if (!Array.isArray(stored)) return [];
|
||||||
|
const names = new Set(baseWallpapers.map(wallpaper => wallpaper.name));
|
||||||
|
return stored.flatMap(wallpaper => {
|
||||||
|
if (!hasStrings(wallpaper, ['name']) || !wallpaper.name || names.has(wallpaper.name)) return [];
|
||||||
|
names.add(wallpaper.name);
|
||||||
|
return [{
|
||||||
|
name: wallpaper.name,
|
||||||
|
...(typeof wallpaper.url === 'string' ? { url: wallpaper.url } : {}),
|
||||||
|
...(typeof wallpaper.base64 === 'string' ? { base64: wallpaper.base64 } : {}),
|
||||||
|
}];
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const MAX_WALLPAPER_SOURCE_BYTES = 20 * 1024 * 1024;
|
||||||
|
const MAX_WALLPAPER_DATA_URL_LENGTH = 4.5 * 1024 * 1024;
|
||||||
|
const MIN_WALLPAPER_EDGE = 1920;
|
||||||
|
const MAX_WALLPAPER_EDGE = 2560;
|
||||||
|
|
||||||
|
const readFileAsDataUrl = (file: Blob): Promise<string> =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => {
|
||||||
|
if (typeof reader.result === 'string') resolve(reader.result);
|
||||||
|
else reject(new Error('Could not read the image file.'));
|
||||||
|
};
|
||||||
|
reader.onerror = () => reject(reader.error || new Error('Could not read the image file.'));
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
});
|
||||||
|
|
||||||
|
const downscaleWallpaper = async (file: File): Promise<Blob> => {
|
||||||
|
if (typeof createImageBitmap !== 'function' || typeof document === 'undefined' || file.type === 'image/gif' || file.type === 'image/svg+xml') {
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const bitmap = await createImageBitmap(file);
|
||||||
|
try {
|
||||||
|
const screenEdge = Math.max(window.screen?.width ?? 0, window.screen?.height ?? 0) * (window.devicePixelRatio || 1);
|
||||||
|
const maxEdge = Math.min(MAX_WALLPAPER_EDGE, Math.max(MIN_WALLPAPER_EDGE, screenEdge));
|
||||||
|
const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height));
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
||||||
|
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
||||||
|
const context = canvas.getContext('2d');
|
||||||
|
if (!context) return file;
|
||||||
|
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
||||||
|
const blob = await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/webp', 0.85));
|
||||||
|
canvas.width = 0;
|
||||||
|
canvas.height = 0;
|
||||||
|
return blob && blob.type === 'image/webp' && blob.size < file.size ? blob : file;
|
||||||
|
} finally {
|
||||||
|
bitmap.close();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const assertWallpaperNameAvailable = (name: string): void => {
|
||||||
|
const names = [...baseWallpapers, ...ConfigurationService.loadUserWallpapers()];
|
||||||
|
if (name.startsWith('vision-start:icon:') || names.some(wallpaper => wallpaper.name === name)) {
|
||||||
|
throw new Error('A wallpaper with this name already exists or the name is reserved. Please choose a different name.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const ConfigurationService = {
|
export const ConfigurationService = {
|
||||||
loadConfig(): Config {
|
loadConfig(): Config {
|
||||||
@@ -80,19 +200,31 @@ export const ConfigurationService = {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error parsing config from localStorage', error);
|
console.error('Error parsing config from localStorage', error);
|
||||||
}
|
}
|
||||||
return { ...DEFAULT_CONFIG };
|
return normalizeConfig(null);
|
||||||
},
|
},
|
||||||
|
|
||||||
saveConfig(config: Config): void {
|
saveConfig(config: Config): void {
|
||||||
|
try {
|
||||||
localStorage.setItem('config', JSON.stringify(config));
|
localStorage.setItem('config', JSON.stringify(config));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving config to localStorage', error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
loadCategories(): Category[] {
|
||||||
|
try {
|
||||||
|
return normalizeCategories(safeParse(localStorage.getItem('categories')));
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error reading categories from localStorage', error);
|
||||||
|
return normalizeCategories(null);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
loadUserWallpapers(): Wallpaper[] {
|
loadUserWallpapers(): Wallpaper[] {
|
||||||
try {
|
try {
|
||||||
const stored = localStorage.getItem('userWallpapers');
|
const stored = localStorage.getItem('userWallpapers');
|
||||||
if (stored) return JSON.parse(stored);
|
if (stored) return normalizeUserWallpapers(JSON.parse(stored));
|
||||||
} catch {
|
} catch {
|
||||||
// ignore
|
|
||||||
}
|
}
|
||||||
return [];
|
return [];
|
||||||
},
|
},
|
||||||
@@ -113,32 +245,23 @@ export const ConfigurationService = {
|
|||||||
throw new Error('Wallpaper URLs must use HTTP or HTTPS.');
|
throw new Error('Wallpaper URLs must use HTTP or HTTPS.');
|
||||||
}
|
}
|
||||||
const finalName = name.trim() || getFileNameFromUrl(parsedUrl) || 'Wallpaper';
|
const finalName = name.trim() || getFileNameFromUrl(parsedUrl) || 'Wallpaper';
|
||||||
|
assertWallpaperNameAvailable(finalName);
|
||||||
return { name: finalName, url: parsedUrl.href };
|
return { name: finalName, url: parsedUrl.href };
|
||||||
},
|
},
|
||||||
|
|
||||||
async addWallpaperFile(file: File): Promise<Wallpaper> {
|
async addWallpaperFile(file: File): Promise<Wallpaper> {
|
||||||
return new Promise((resolve, reject) => {
|
if (!file.type.startsWith('image/')) throw new Error('Please choose an image file.');
|
||||||
if (file.size > 4 * 1024 * 1024) {
|
assertWallpaperNameAvailable(file.name.trim());
|
||||||
reject(new Error('File size exceeds 4MB. Please choose a smaller file.'));
|
if (file.size > MAX_WALLPAPER_SOURCE_BYTES) {
|
||||||
return;
|
throw new Error('File size exceeds 20MB. Please choose a smaller file.');
|
||||||
}
|
}
|
||||||
const reader = new FileReader();
|
const base64 = await readFileAsDataUrl(await downscaleWallpaper(file));
|
||||||
reader.onload = async () => {
|
if (base64.length > MAX_WALLPAPER_DATA_URL_LENGTH) {
|
||||||
const base64 = reader.result as string;
|
throw new Error('The uploaded image is too large. Please choose a smaller file.');
|
||||||
if (base64.length > 4.5 * 1024 * 1024) {
|
|
||||||
reject(new Error('The uploaded image is too large. Please choose a smaller file.'));
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
try {
|
assertWallpaperNameAvailable(file.name.trim());
|
||||||
const finalName = await addWallpaperToChromeStorageLocal(file.name, base64);
|
const finalName = await addWallpaperToChromeStorageLocal(file.name, base64);
|
||||||
resolve({ name: finalName });
|
return { name: finalName };
|
||||||
} catch (error) {
|
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
reader.onerror = reject;
|
|
||||||
reader.readAsDataURL(file);
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
|
|
||||||
async deleteWallpaper(wallpaper: Wallpaper): Promise<void> {
|
async deleteWallpaper(wallpaper: Wallpaper): Promise<void> {
|
||||||
@@ -168,10 +291,11 @@ export const ConfigurationService = {
|
|||||||
document.body.appendChild(link);
|
document.body.appendChild(link);
|
||||||
link.click();
|
link.click();
|
||||||
document.body.removeChild(link);
|
document.body.removeChild(link);
|
||||||
URL.revokeObjectURL(url);
|
setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||||
},
|
},
|
||||||
|
|
||||||
async importConfig(file: File): Promise<{ config: Config; userWallpapers: Wallpaper[] }> {
|
async importConfig(file: File): Promise<{ config: Config; userWallpapers: Wallpaper[] }> {
|
||||||
|
if (file.size > 10 * 1024 * 1024) throw new Error('Configuration files must be no larger than 10MB.');
|
||||||
const fileContent = await file.text();
|
const fileContent = await file.text();
|
||||||
const parsed = JSON.parse(fileContent);
|
const parsed = JSON.parse(fileContent);
|
||||||
const localStorageData =
|
const localStorageData =
|
||||||
@@ -179,30 +303,47 @@ export const ConfigurationService = {
|
|||||||
? parsed.localStorage
|
? parsed.localStorage
|
||||||
: parsed;
|
: parsed;
|
||||||
|
|
||||||
if (!localStorageData || typeof localStorageData !== 'object') {
|
if (!isPlainObject(localStorageData)) {
|
||||||
throw new Error('Invalid import file format.');
|
throw new Error('Invalid import file format.');
|
||||||
}
|
}
|
||||||
|
|
||||||
let importedAny = false;
|
const updates = new Map<RequiredLocalStorageKey, string>();
|
||||||
REQUIRED_LOCAL_STORAGE_KEYS.forEach((key) => {
|
for (const key of REQUIRED_LOCAL_STORAGE_KEYS) {
|
||||||
if (Object.prototype.hasOwnProperty.call(localStorageData, key)) {
|
if (Object.prototype.hasOwnProperty.call(localStorageData, key)) {
|
||||||
const rawValue = (localStorageData as Record<string, unknown>)[key];
|
const raw = localStorageData[key];
|
||||||
localStorage.setItem(key, toStorageString(rawValue));
|
const value = typeof raw === 'string' ? safeParse(raw) : raw;
|
||||||
importedAny = true;
|
if (value === null) continue;
|
||||||
|
if ((key === 'config' || key === 'wallpaperState') && !isPlainObject(value)) {
|
||||||
|
throw new Error(`Invalid ${key} in import file.`);
|
||||||
|
}
|
||||||
|
if ((key === 'categories' || key === 'userWallpapers') && !Array.isArray(value)) {
|
||||||
|
throw new Error(`Invalid ${key} in import file.`);
|
||||||
|
}
|
||||||
|
const normalized = key === 'config' ? normalizeConfig(value)
|
||||||
|
: key === 'categories' ? normalizeCategories(value)
|
||||||
|
: key === 'userWallpapers' ? normalizeUserWallpapers(value) : value;
|
||||||
|
updates.set(key, toStorageString(normalized));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
if (!importedAny) {
|
if (updates.size === 0) {
|
||||||
throw new Error(`No required keys found. Expected: ${REQUIRED_LOCAL_STORAGE_KEYS.join(', ')}`);
|
throw new Error(`No required keys found. Expected: ${REQUIRED_LOCAL_STORAGE_KEYS.join(', ')}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const importedConfig = (localStorageData as Record<string, unknown>).config;
|
const previous = new Map([...updates.keys()].map(key => [key, localStorage.getItem(key)]));
|
||||||
const importedUserWallpapers = (localStorageData as Record<string, unknown>)
|
try {
|
||||||
.userWallpapers;
|
for (const [key, value] of updates) localStorage.setItem(key, value);
|
||||||
|
} catch (error) {
|
||||||
|
for (const key of updates.keys()) localStorage.removeItem(key);
|
||||||
|
for (const [key, value] of previous) {
|
||||||
|
if (value !== null) localStorage.setItem(key, value);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
config: normalizeConfig(importedConfig),
|
config: this.loadConfig(),
|
||||||
userWallpapers: Array.isArray(importedUserWallpapers) ? importedUserWallpapers : [],
|
userWallpapers: this.loadUserWallpapers(),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -7,7 +7,8 @@ declare global {
|
|||||||
storage?: {
|
storage?: {
|
||||||
local?: {
|
local?: {
|
||||||
set: (items: object, callback?: () => void) => void;
|
set: (items: object, callback?: () => void) => void;
|
||||||
get: (keys: string[] | string, callback: (items: { [key: string]: string }) => void) => void;
|
get: (keys: string[] | string | null, callback: (items: { [key: string]: string }) => void) => void;
|
||||||
|
getKeys?: (callback: (keys: string[]) => void) => void;
|
||||||
remove: (keys: string | string[], callback?: () => void) => void;
|
remove: (keys: string | string[], callback?: () => void) => void;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -57,17 +58,36 @@ const chromeLocalCall = <T>(
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function getCachedIconFromChromeStorageLocal(sourceUrl: string): Promise<string | null> {
|
let pendingIconLookups: Map<string, ((value: string | null) => void)[]> | null = null;
|
||||||
if (!checkChromeStorageLocalAvailable()) return null;
|
|
||||||
|
const flushIconLookups = async (): Promise<void> => {
|
||||||
|
const lookups = pendingIconLookups;
|
||||||
|
pendingIconLookups = null;
|
||||||
|
if (!lookups) return;
|
||||||
|
let result: StorageResult = {};
|
||||||
try {
|
try {
|
||||||
const key = getIconCacheKey(sourceUrl);
|
result = await chromeLocalCall<StorageResult>((cb) =>
|
||||||
const result = await chromeLocalCall<StorageResult>((cb) =>
|
window.chrome?.storage?.local?.get([...lookups.keys()], cb),
|
||||||
window.chrome?.storage?.local?.get([key], cb),
|
|
||||||
);
|
);
|
||||||
return result[key] || null;
|
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
result = {};
|
||||||
}
|
}
|
||||||
|
for (const [key, resolvers] of lookups) {
|
||||||
|
const value = typeof result[key] === 'string' ? result[key] || null : null;
|
||||||
|
resolvers.forEach(resolve => resolve(value));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export function getCachedIconFromChromeStorageLocal(sourceUrl: string): Promise<string | null> {
|
||||||
|
if (!checkChromeStorageLocalAvailable()) return Promise.resolve(null);
|
||||||
|
return new Promise(resolve => {
|
||||||
|
if (!pendingIconLookups) {
|
||||||
|
pendingIconLookups = new Map();
|
||||||
|
queueMicrotask(() => void flushIconLookups());
|
||||||
|
}
|
||||||
|
const key = getIconCacheKey(sourceUrl);
|
||||||
|
pendingIconLookups.set(key, [...(pendingIconLookups.get(key) ?? []), resolve]);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveCachedIconToChromeStorageLocal(sourceUrl: string, dataUrl: string): Promise<boolean> {
|
export async function saveCachedIconToChromeStorageLocal(sourceUrl: string, dataUrl: string): Promise<boolean> {
|
||||||
@@ -94,6 +114,25 @@ export async function removeCachedIconFromChromeStorageLocal(sourceUrl: string):
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function pruneCachedIconsFromChromeStorageLocal(keepSourceUrls: string[]): Promise<number> {
|
||||||
|
if (!checkChromeStorageLocalAvailable()) return 0;
|
||||||
|
try {
|
||||||
|
const keep = new Set(keepSourceUrls.map(getIconCacheKey));
|
||||||
|
const local = window.chrome?.storage?.local;
|
||||||
|
const keys = local?.getKeys
|
||||||
|
? await chromeLocalCall<string[]>((cb) => local.getKeys?.(cb))
|
||||||
|
: Object.keys(await chromeLocalCall<StorageResult>((cb) => local?.get(null, cb)));
|
||||||
|
const stale = keys.filter(key => key.startsWith(ICON_CACHE_KEY_PREFIX) && !keep.has(key));
|
||||||
|
if (stale.length === 0) return 0;
|
||||||
|
await chromeLocalCall<void>((cb) =>
|
||||||
|
window.chrome?.storage?.local?.remove(stale, cb),
|
||||||
|
);
|
||||||
|
return stale.length;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a new wallpaper to chrome.storage.local.
|
* Adds a new wallpaper to chrome.storage.local.
|
||||||
* File uploads are stored as base64 while remote wallpapers remain URLs.
|
* File uploads are stored as base64 while remote wallpapers remain URLs.
|
||||||
@@ -123,9 +162,16 @@ export async function addWallpaperToChromeStorageLocal(name: string, url: string
|
|||||||
finalName = finalName || getFileNameFromUrl(parsedUrl);
|
finalName = finalName || getFileNameFromUrl(parsedUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
await chromeLocalCall<void>((cb) =>
|
await chromeLocalCall<void>((cb) =>
|
||||||
window.chrome?.storage?.local?.set({ [finalName]: url }, cb),
|
window.chrome?.storage?.local?.set({ [finalName]: url }, cb),
|
||||||
);
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && /quota/i.test(error.message)) {
|
||||||
|
throw new Error('Not enough extension storage for this wallpaper. Delete an uploaded wallpaper and try again.');
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
return finalName;
|
return finalName;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +188,7 @@ export async function getWallpaperFromChromeStorageLocal(name: string): Promise<
|
|||||||
const result = await chromeLocalCall<StorageResult>((cb) =>
|
const result = await chromeLocalCall<StorageResult>((cb) =>
|
||||||
window.chrome?.storage?.local?.get([name], cb),
|
window.chrome?.storage?.local?.get([name], cb),
|
||||||
);
|
);
|
||||||
return result[name] || null;
|
return typeof result[name] === 'string' ? result[name] || null : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -4,18 +4,29 @@ import {
|
|||||||
removeCachedIconFromChromeStorageLocal,
|
removeCachedIconFromChromeStorageLocal,
|
||||||
saveCachedIconToChromeStorageLocal,
|
saveCachedIconToChromeStorageLocal,
|
||||||
} from './StorageLocalManager';
|
} from './StorageLocalManager';
|
||||||
|
import { normalizeWebsiteUrl } from './urlUtils';
|
||||||
|
|
||||||
const MAX_CACHED_ICON_BYTES = 256 * 1024;
|
const MAX_CACHED_ICON_BYTES = 256 * 1024;
|
||||||
const MAX_RESOLVED_ICONS = 50;
|
const MAX_RESOLVED_ICONS = 50;
|
||||||
|
const MAX_RESOLVED_ICON_MEMORY = 2 * 1024 * 1024;
|
||||||
|
const MAX_CONCURRENT_ICON_REQUESTS = 4;
|
||||||
|
let resolvedIconBytes = 0;
|
||||||
|
let activeIconRequests = 0;
|
||||||
|
const iconRequestQueue: (() => void)[] = [];
|
||||||
const resolvedIconCache = new Map<string, string>();
|
const resolvedIconCache = new Map<string, string>();
|
||||||
const iconCacheLookups = new Map<string, Promise<string | null>>();
|
const iconCacheLookups = new Map<string, Promise<string | null>>();
|
||||||
const iconCacheRequests = new Map<string, Promise<string | null>>();
|
const iconCacheRequests = new Map<string, Promise<string | null>>();
|
||||||
|
|
||||||
const rememberResolvedIcon = (iconUrl: string, dataUrl: string): void => {
|
const rememberResolvedIcon = (iconUrl: string, dataUrl: string): void => {
|
||||||
|
resolvedIconBytes -= (resolvedIconCache.get(iconUrl)?.length ?? 0) * 2;
|
||||||
|
resolvedIconCache.delete(iconUrl);
|
||||||
resolvedIconCache.set(iconUrl, dataUrl);
|
resolvedIconCache.set(iconUrl, dataUrl);
|
||||||
if (resolvedIconCache.size > MAX_RESOLVED_ICONS) {
|
resolvedIconBytes += dataUrl.length * 2;
|
||||||
|
while (resolvedIconCache.size > MAX_RESOLVED_ICONS || resolvedIconBytes > MAX_RESOLVED_ICON_MEMORY) {
|
||||||
const oldest = resolvedIconCache.keys().next().value;
|
const oldest = resolvedIconCache.keys().next().value;
|
||||||
if (oldest !== undefined) resolvedIconCache.delete(oldest);
|
if (oldest === undefined) break;
|
||||||
|
resolvedIconBytes -= (resolvedIconCache.get(oldest)?.length ?? 0) * 2;
|
||||||
|
resolvedIconCache.delete(oldest);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -31,7 +42,33 @@ const isCacheableIconUrl = (value: string): boolean => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const isValidCachedIcon = (value: string | null): value is string =>
|
const isValidCachedIcon = (value: string | null): value is string =>
|
||||||
typeof value === 'string' && isDataUrl(value);
|
typeof value === 'string' && value.startsWith('data:image/') && value.length <= Math.ceil(MAX_CACHED_ICON_BYTES * 4 / 3) + 256;
|
||||||
|
|
||||||
|
const readIconBlob = async (response: Response): Promise<Blob | null> => {
|
||||||
|
const contentType = (response.headers.get('content-type') || '').split(';', 1)[0].trim().toLowerCase();
|
||||||
|
if (!contentType.startsWith('image/') || Number(response.headers.get('content-length')) > MAX_CACHED_ICON_BYTES || !response.body) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const reader = response.body.getReader();
|
||||||
|
const chunks: Uint8Array<ArrayBuffer>[] = [];
|
||||||
|
let bytes = 0;
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
bytes += value.byteLength;
|
||||||
|
if (bytes > MAX_CACHED_ICON_BYTES) {
|
||||||
|
await reader.cancel();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
chunks.push(value as Uint8Array<ArrayBuffer>);
|
||||||
|
}
|
||||||
|
return bytes > 0 ? new Blob(chunks, { type: contentType }) : null;
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const blobToDataUrl = (blob: Blob): Promise<string> =>
|
const blobToDataUrl = (blob: Blob): Promise<string> =>
|
||||||
new Promise<string>((resolve, reject) => {
|
new Promise<string>((resolve, reject) => {
|
||||||
@@ -102,10 +139,10 @@ const getIconFetchSource = (iconUrl: string): string | null => {
|
|||||||
async function getWebsiteIcon(rawUrl: string): Promise<string> {
|
async function getWebsiteIcon(rawUrl: string): Promise<string> {
|
||||||
const trimmed = rawUrl.trim();
|
const trimmed = rawUrl.trim();
|
||||||
const hasProtocol = /^https?:\/\//i.test(trimmed);
|
const hasProtocol = /^https?:\/\//i.test(trimmed);
|
||||||
const targetUrl = hasProtocol ? trimmed : `https://${trimmed}`;
|
const normalized = normalizeWebsiteUrl(trimmed);
|
||||||
|
if (!normalized) return '';
|
||||||
try {
|
const parsed = new URL(normalized);
|
||||||
const parsed = new URL(targetUrl);
|
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return '';
|
||||||
if (!isTrustedTld(parsed.hostname)) {
|
if (!isTrustedTld(parsed.hostname)) {
|
||||||
if (!hasProtocol) {
|
if (!hasProtocol) {
|
||||||
return `http://${parsed.host}/favicon.ico`;
|
return `http://${parsed.host}/favicon.ico`;
|
||||||
@@ -113,9 +150,14 @@ async function getWebsiteIcon(rawUrl: string): Promise<string> {
|
|||||||
return `${parsed.origin}/favicon.ico`;
|
return `${parsed.origin}/favicon.ico`;
|
||||||
}
|
}
|
||||||
return `https://www.google.com/s2/favicons?domain=${parsed.hostname}&sz=128`;
|
return `https://www.google.com/s2/favicons?domain=${parsed.hostname}&sz=128`;
|
||||||
} catch {
|
|
||||||
return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(rawUrl)}&sz=128`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getInitialIconSource(iconUrl: string): string | null | undefined {
|
||||||
|
if (!iconUrl) return null;
|
||||||
|
if (isDataUrl(iconUrl)) return iconUrl;
|
||||||
|
const inMemoryIcon = resolvedIconCache.get(iconUrl);
|
||||||
|
if (inMemoryIcon) return inMemoryIcon;
|
||||||
|
return isCacheableIconUrl(iconUrl) && checkChromeStorageLocalAvailable() ? undefined : iconUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getCachedWebsiteIcon(iconUrl: string): Promise<string | null> {
|
async function getCachedWebsiteIcon(iconUrl: string): Promise<string | null> {
|
||||||
@@ -134,6 +176,7 @@ async function getCachedWebsiteIcon(iconUrl: string): Promise<string | null> {
|
|||||||
rememberResolvedIcon(iconUrl, cachedIcon);
|
rememberResolvedIcon(iconUrl, cachedIcon);
|
||||||
return cachedIcon;
|
return cachedIcon;
|
||||||
}
|
}
|
||||||
|
if (cachedIcon) void removeCachedIconFromChromeStorageLocal(iconUrl);
|
||||||
return null;
|
return null;
|
||||||
})
|
})
|
||||||
.catch(() => null)
|
.catch(() => null)
|
||||||
@@ -153,6 +196,7 @@ async function cacheWebsiteIcon(iconUrl: string): Promise<string | null> {
|
|||||||
|
|
||||||
const existingRequest = iconCacheRequests.get(iconUrl);
|
const existingRequest = iconCacheRequests.get(iconUrl);
|
||||||
if (existingRequest) return existingRequest;
|
if (existingRequest) return existingRequest;
|
||||||
|
if (iconCacheRequests.size >= MAX_RESOLVED_ICONS) return null;
|
||||||
|
|
||||||
const request = (async () => {
|
const request = (async () => {
|
||||||
const cachedIcon = await getCachedWebsiteIcon(iconUrl);
|
const cachedIcon = await getCachedWebsiteIcon(iconUrl);
|
||||||
@@ -161,18 +205,20 @@ async function cacheWebsiteIcon(iconUrl: string): Promise<string | null> {
|
|||||||
const fetchSource = getIconFetchSource(iconUrl);
|
const fetchSource = getIconFetchSource(iconUrl);
|
||||||
if (!fetchSource) return null;
|
if (!fetchSource) return null;
|
||||||
|
|
||||||
|
if (activeIconRequests >= MAX_CONCURRENT_ICON_REQUESTS) {
|
||||||
|
await new Promise<void>(resolve => iconRequestQueue.push(resolve));
|
||||||
|
} else {
|
||||||
|
activeIconRequests++;
|
||||||
|
}
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), 8000);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(fetchSource);
|
const response = await fetch(fetchSource, { signal: controller.signal, credentials: 'omit' });
|
||||||
if (!response.ok || response.type === 'opaque') return null;
|
if (!response.ok || response.type === 'opaque') return null;
|
||||||
|
|
||||||
const blob = await response.blob();
|
const blob = await readIconBlob(response);
|
||||||
const contentType = (blob.type || response.headers.get('content-type') || '')
|
if (!blob) return null;
|
||||||
.split(';', 1)[0]
|
|
||||||
.trim()
|
|
||||||
.toLowerCase();
|
|
||||||
if (!contentType.startsWith('image/') || blob.size === 0 || blob.size > MAX_CACHED_ICON_BYTES) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const dataUrl = await blobToDataUrl(blob);
|
const dataUrl = await blobToDataUrl(blob);
|
||||||
rememberResolvedIcon(iconUrl, dataUrl);
|
rememberResolvedIcon(iconUrl, dataUrl);
|
||||||
@@ -180,6 +226,12 @@ async function cacheWebsiteIcon(iconUrl: string): Promise<string | null> {
|
|||||||
return dataUrl;
|
return dataUrl;
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
controller.abort();
|
||||||
|
const nextRequest = iconRequestQueue.shift();
|
||||||
|
if (nextRequest) nextRequest();
|
||||||
|
else activeIconRequests--;
|
||||||
}
|
}
|
||||||
})().finally(() => {
|
})().finally(() => {
|
||||||
iconCacheRequests.delete(iconUrl);
|
iconCacheRequests.delete(iconUrl);
|
||||||
@@ -190,6 +242,7 @@ async function cacheWebsiteIcon(iconUrl: string): Promise<string | null> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function removeCachedWebsiteIcon(iconUrl: string): Promise<void> {
|
async function removeCachedWebsiteIcon(iconUrl: string): Promise<void> {
|
||||||
|
resolvedIconBytes -= (resolvedIconCache.get(iconUrl)?.length ?? 0) * 2;
|
||||||
resolvedIconCache.delete(iconUrl);
|
resolvedIconCache.delete(iconUrl);
|
||||||
iconCacheLookups.delete(iconUrl);
|
iconCacheLookups.delete(iconUrl);
|
||||||
await removeCachedIconFromChromeStorageLocal(iconUrl);
|
await removeCachedIconFromChromeStorageLocal(iconUrl);
|
||||||
@@ -198,6 +251,7 @@ async function removeCachedWebsiteIcon(iconUrl: string): Promise<void> {
|
|||||||
export {
|
export {
|
||||||
cacheWebsiteIcon,
|
cacheWebsiteIcon,
|
||||||
getCachedWebsiteIcon,
|
getCachedWebsiteIcon,
|
||||||
|
getInitialIconSource,
|
||||||
getWebsiteIcon,
|
getWebsiteIcon,
|
||||||
removeCachedWebsiteIcon,
|
removeCachedWebsiteIcon,
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
export const createId = (): string =>
|
||||||
|
globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
function request_image(url) {
|
|
||||||
return new Promise(function(resolve, reject) {
|
|
||||||
var img = new Image();
|
|
||||||
var settled = false;
|
|
||||||
function settleOk() {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(failTimer);
|
|
||||||
img.onload = img.onerror = null;
|
|
||||||
resolve(img);
|
|
||||||
}
|
|
||||||
function settleFail() {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(failTimer);
|
|
||||||
img.onload = img.onerror = null;
|
|
||||||
reject(url);
|
|
||||||
}
|
|
||||||
img.onload = settleOk;
|
|
||||||
img.onerror = settleFail;
|
|
||||||
img.src = url + '?random-no-cache=' + Math.floor((1 + Math.random()) * 0x10000).toString(16);
|
|
||||||
var failTimer = setTimeout(settleFail, 5000);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function ping(url, multiplier) {
|
|
||||||
return new Promise(function(resolve, reject) {
|
|
||||||
var start = (new Date()).getTime();
|
|
||||||
var response = function() {
|
|
||||||
var delta = ((new Date()).getTime() - start);
|
|
||||||
delta *= (multiplier || 1);
|
|
||||||
resolve(delta);
|
|
||||||
};
|
|
||||||
request_image(url).then(response).catch(response);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export default ping;
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { parseServerAddress } from './urlUtils';
|
||||||
|
|
||||||
|
async function ping(url: string, multiplier = 1, signal?: AbortSignal): Promise<number> {
|
||||||
|
const target = parseServerAddress(url);
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
const abort = () => controller.abort();
|
||||||
|
if (signal?.aborted) abort();
|
||||||
|
signal?.addEventListener('abort', abort, { once: true });
|
||||||
|
const timeout = setTimeout(abort, 5000);
|
||||||
|
const start = performance.now();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fetch(target.href, {
|
||||||
|
method: 'HEAD',
|
||||||
|
mode: 'no-cors',
|
||||||
|
cache: 'no-store',
|
||||||
|
credentials: 'omit',
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
return (performance.now() - start) * multiplier;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
signal?.removeEventListener('abort', abort);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ping;
|
||||||
@@ -7,3 +7,28 @@ export const getFileNameFromUrl = (url: URL): string => {
|
|||||||
return pathName;
|
return pathName;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const SCHEME_PATTERN = /^[a-z][a-z\d+.-]*:/i;
|
||||||
|
const AUTHORITY_SCHEME_PATTERN = /^[a-z][a-z\d+.-]*:\/\//i;
|
||||||
|
const ALLOWED_WEBSITE_PROTOCOLS = new Set(['http:', 'https:', 'ftp:', 'mailto:']);
|
||||||
|
|
||||||
|
export const normalizeWebsiteUrl = (raw: string): string | null => {
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
if (!trimmed) return null;
|
||||||
|
const hasScheme = AUTHORITY_SCHEME_PATTERN.test(trimmed) || (SCHEME_PATTERN.test(trimmed) && !/^[^:/]+:\d/.test(trimmed));
|
||||||
|
try {
|
||||||
|
const url = new URL(hasScheme ? trimmed : `https://${trimmed}`);
|
||||||
|
return ALLOWED_WEBSITE_PROTOCOLS.has(url.protocol) ? url.href : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseServerAddress = (address: string): URL => {
|
||||||
|
const trimmed = address.trim();
|
||||||
|
const target = new URL(AUTHORITY_SCHEME_PATTERN.test(trimmed) ? trimmed : `http://${trimmed}`);
|
||||||
|
if (target.protocol !== 'http:' && target.protocol !== 'https:') {
|
||||||
|
throw new Error('Server addresses must use HTTP or HTTPS.');
|
||||||
|
}
|
||||||
|
return target;
|
||||||
|
};
|
||||||
@@ -45,7 +45,11 @@ export const saveWallpaperState = (names: string[], currentIndex: number, lastCh
|
|||||||
currentName: names[currentIndex],
|
currentName: names[currentIndex],
|
||||||
lastWallpaperChange: new Date(lastChange).toISOString(),
|
lastWallpaperChange: new Date(lastChange).toISOString(),
|
||||||
});
|
});
|
||||||
|
try {
|
||||||
if (localStorage.getItem('wallpaperState') !== payload) {
|
if (localStorage.getItem('wallpaperState') !== payload) {
|
||||||
localStorage.setItem('wallpaperState', payload);
|
localStorage.setItem('wallpaperState', payload);
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving wallpaper state', error);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
@@ -55,8 +55,6 @@ body {
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
background-size: cover;
|
background-size: cover;
|
||||||
background-position: center;
|
background-position: center;
|
||||||
transform: scale(1.015);
|
|
||||||
will-change: filter, opacity, transform;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.wallpaper-luminance {
|
.wallpaper-luminance {
|
||||||
@@ -368,7 +366,6 @@ body {
|
|||||||
background 260ms var(--ease-ios),
|
background 260ms var(--ease-ios),
|
||||||
border-color 260ms var(--ease-ios),
|
border-color 260ms var(--ease-ios),
|
||||||
box-shadow 340ms var(--ease-liquid);
|
box-shadow 340ms var(--ease-liquid);
|
||||||
will-change: transform, box-shadow;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.liquid-tile:hover {
|
.liquid-tile:hover {
|
||||||
|
|||||||
@@ -4,9 +4,6 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>Vision Start</title>
|
<title>Vision Start</title>
|
||||||
|
|
||||||
|
|
||||||
<link rel="stylesheet" href="/index.css">
|
|
||||||
</head>
|
</head>
|
||||||
<body class="bg-slate-950">
|
<body class="bg-slate-950">
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
Generated
+493
-343
File diff suppressed because it is too large.
Load diff
+3
-4
@@ -7,22 +7,21 @@
|
|||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test": "node scripts/check_regressions.mjs",
|
||||||
"capture:screenshots": "node scripts/capture_screenshots.mjs"
|
"capture:screenshots": "node scripts/capture_screenshots.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hello-pangea/dnd": "^18.0.1",
|
"@hello-pangea/dnd": "^18.0.1",
|
||||||
"@tailwindcss/vite": "^4.1.11",
|
|
||||||
"preact": "^10.26.4"
|
"preact": "^10.26.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@preact/preset-vite": "^2.10.1",
|
"@preact/preset-vite": "^2.10.1",
|
||||||
"@tailwindcss/postcss": "^4.1.11",
|
"@tailwindcss/vite": "^4.1.11",
|
||||||
"@types/node": "^22.14.0",
|
"@types/node": "^22.14.0",
|
||||||
"@types/react": "^19.1.8",
|
"@types/react": "^19.1.8",
|
||||||
"@types/react-dom": "^19.1.5",
|
"@types/react-dom": "^19.1.5",
|
||||||
"autoprefixer": "^10.4.21",
|
|
||||||
"playwright": "1.61.1",
|
"playwright": "1.61.1",
|
||||||
"postcss": "^8.5.6",
|
|
||||||
"tailwindcss": "^4.1.11",
|
"tailwindcss": "^4.1.11",
|
||||||
"typescript": "~5.7.2",
|
"typescript": "~5.7.2",
|
||||||
"vite": "^6.2.0"
|
"vite": "^6.2.0"
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
plugins: {
|
|
||||||
'@tailwindcss/postcss': {}, // ← use the new package name
|
|
||||||
autoprefixer: {},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+50
-38
@@ -1,9 +1,3 @@
|
|||||||
---
|
|
||||||
project_name: Vision Start
|
|
||||||
date: 2026-08-11
|
|
||||||
type: general_overview
|
|
||||||
---
|
|
||||||
|
|
||||||
# Vision Start — Project Context
|
# Vision Start — Project Context
|
||||||
|
|
||||||
A general, non-normative overview of the **Vision Start** project: what it is, how it's structured, what features it offers, and which files do what. This document is intended as a map for humans and AI agents to orient themselves in the codebase. It deliberately avoids coding-style prescriptive rules.
|
A general, non-normative overview of the **Vision Start** project: what it is, how it's structured, what features it offers, and which files do what. This document is intended as a map for humans and AI agents to orient themselves in the codebase. It deliberately avoids coding-style prescriptive rules.
|
||||||
@@ -34,7 +28,7 @@ Live instances / artifacts:
|
|||||||
| Language | TypeScript (~5.7), target ES2020, strict mode |
|
| Language | TypeScript (~5.7), target ES2020, strict mode |
|
||||||
| UI runtime | Preact 10 (via `@preact/preset-vite`); types from `@types/react` 19 |
|
| UI runtime | Preact 10 (via `@preact/preset-vite`); types from `@types/react` 19 |
|
||||||
| Bundler / dev server | Vite 6 |
|
| Bundler / dev server | Vite 6 |
|
||||||
| Styling | Tailwind CSS v4 (`@tailwindcss/vite` plugin + `@tailwindcss/postcss` + `autoprefixer`) |
|
| Styling | Tailwind CSS v4 via the `@tailwindcss/vite` plugin only (no `tailwind.config.js` or PostCSS config) |
|
||||||
| Drag & drop | `@hello-pangea/dnd` 18 |
|
| Drag & drop | `@hello-pangea/dnd` 18 |
|
||||||
| Build output | Plain static files in `dist/` (relative `base: './'`, single CSS bundle; modals code-split into separate JS chunks via `React.lazy`) |
|
| Build output | Plain static files in `dist/` (relative `base: './'`, single CSS bundle; modals code-split into separate JS chunks via `React.lazy`) |
|
||||||
| Container | Node 22 Alpine build stage → nginx Alpine serving `dist/` |
|
| Container | Node 22 Alpine build stage → nginx Alpine serving `dist/` |
|
||||||
@@ -52,27 +46,34 @@ The startpage is composed of widgets and a configuration panel:
|
|||||||
|
|
||||||
- **Website Tiles** — Bookmarks organized into categories. Each tile shows an icon + name and opens the configured URL. Tiles can be added, edited, deleted, and moved left/right within their own category (reordering) while in edit mode.
|
- **Website Tiles** — Bookmarks organized into categories. Each tile shows an icon + name and opens the configured URL. Tiles can be added, edited, deleted, and moved left/right within their own category (reordering) while in edit mode.
|
||||||
- **Categories** — Groupings of website tiles (e.g. "Search"). Add/edit/delete/name.
|
- **Categories** — Groupings of website tiles (e.g. "Search"). Add/edit/delete/name.
|
||||||
- **Clock** — Optional header clock with selectable size, font, and 12h/24h format.
|
- **Clock** — Optional header clock with selectable size, font (Helvetica, Monospace, Cursive — system fonts only, nothing is downloaded), and 12h/24h format.
|
||||||
- **Title** — Optional big header title (text + size configurable).
|
- **Title** — Optional big header title (text + size configurable).
|
||||||
- **Server Status Widget** — Bottom-center glass pill that periodically "pings" configured server addresses and shows online/offline indicators. Ping uses an image-load trick (`components/utils/jsping.js`) with a 5s timeout, at a configurable frequency.
|
- **Server Status Widget** — Bottom-center glass pill that periodically "pings" configured server addresses and shows online/offline indicators. Probes use cancellable, credential-free HTTP HEAD requests with a 5s timeout. Online means the browser received a response; cross-origin HTTP status codes are opaque, so this is reachability rather than an HTTP health check. Network failures, timeouts, and browser-blocked requests appear offline.
|
||||||
- **Wallpaper background** — Fullscreen background image with adjustable blur, brightness, and opacity, rendered behind a soft readability layer for the liquid-glass UI. Randomly rotates through multiple wallpapers at an hourly cadence selected by slider (`1h`–`48h`).
|
- **Wallpaper background** — Fullscreen background image with adjustable blur, brightness, and opacity, rendered behind a soft readability layer for the liquid-glass UI. Randomly rotates through multiple wallpapers at an hourly cadence selected by slider (`1h`–`48h`).
|
||||||
- Built-in wallpapers: Abstract, Abstract Red, Beach, Dark, Mountain, Waves (`components/utils/baseWallpapers.ts`).
|
- Built-in wallpapers: Abstract, Abstract Red, Beach, Dark, Mountain, Waves (`components/utils/baseWallpapers.ts`).
|
||||||
- User wallpapers: upload from a file (≤4MB, ≤4.5MB base64) or add by URL. Remote URLs remain lightweight entries in the `userWallpapers` index; uploaded image data is stored in `chrome.storage.local` when available.
|
- User wallpapers: upload from a file (≤20MB source; non-GIF/SVG images are downscaled to a long edge between 1920px and 2560px depending on the screen and re-encoded as WebP when smaller; ≤4.5MB stored base64) or add by URL. Remote URLs remain lightweight entries in the `userWallpapers` index; uploaded image data is stored in `chrome.storage.local` when available.
|
||||||
- **Icon library, auto-fetch & cache** — Website icons can be picked from the [Dashboard Icons](https://dashboardicons.com/) library (metadata pre-downloaded to `public/icon-metadata.json`) or auto-fetched for trusted public TLDs as a Google S2 favicon URL derived from the site's hostname (no HTML fetching — the S2 URL is used purely as an `<img>` source). Non-trusted TLDs (e.g. local TLDs, IP addresses) fetch `${origin}/favicon.ico` directly. Tiles opportunistically cache CORS-readable icon responses as data URLs in `chrome.storage.local` and retain the original URL when caching is unavailable. Cache population fetches trusted TLDs through a CORS-open favicon service (`icon.horse`) because Google's S2 endpoint 301-redirects without `Access-Control-Allow-Origin`, which would block cross-origin `fetch`.
|
- **Icon library, auto-fetch & cache** — Website icons can be picked from the [Dashboard Icons](https://dashboardicons.com/) library (metadata pre-downloaded to `public/icon-metadata.json`) or auto-fetched for trusted public TLDs as a Google S2 favicon URL derived from the site's hostname (no HTML fetching — the S2 URL is used purely as an `<img>` source). Non-trusted TLDs (e.g. local TLDs, IP addresses) fetch `${origin}/favicon.ico` directly. Tiles opportunistically cache CORS-readable icon responses as data URLs in `chrome.storage.local` and retain the original URL when caching is unavailable. Cache population fetches trusted TLDs through a CORS-open favicon service (`icon.horse`) because Google's S2 endpoint 301-redirects without `Access-Control-Allow-Origin`, which would block cross-origin `fetch`.
|
||||||
- **Configuration panel** — Slide-in right-side modal with four tabs: General, Theme, Clock, Server Widget. Includes **Export** (downloads a JSON bundle of selected `localStorage` keys) and **Import** (restores from JSON and reloads the page).
|
- **Configuration panel** — Slide-in right-side modal with four tabs: General, Theme, Clock, Server Widget. Includes **Export** (downloads a JSON bundle of selected `localStorage` keys) and **Import** (restores from JSON and reloads the page).
|
||||||
- **Edit mode** — Toggle via the top-left pencil button; reveals per-tile glass action toolbars, per-category edit buttons, and ghost glass "add" tiles.
|
- **Edit mode** — Toggle via the top-left pencil button; reveals per-tile glass action toolbars, per-category edit buttons, and ghost glass "add" tiles. Add/edit modals disable Save until required fields are filled, and website URLs without a scheme get `https://` (only `http`, `https`, `ftp`, `mailto` are accepted). Deleting a category that has websites, or an uploaded wallpaper, asks for confirmation first. All modals close with Escape (an open `Dropdown` consumes Escape first). The navigation spinner only appears for `http(s)` links and resets after 10s.
|
||||||
|
- **Cross-tab sync** — `App.tsx` listens for `storage` events on `config` and `categories` and reloads normalized state, so an older open tab never overwrites edits made in another tab.
|
||||||
- **Liquid glass design language** — Soft translucent surfaces, restrained edge highlights, moderate backdrop blur, soft shadows, cyan focus states, and iOS-like easing tokens (`ease-ios`, `ease-spring`, `ease-liquid`) defined in `index.css`.
|
- **Liquid glass design language** — Soft translucent surfaces, restrained edge highlights, moderate backdrop blur, soft shadows, cyan focus states, and iOS-like easing tokens (`ease-ios`, `ease-spring`, `ease-liquid`) defined in `index.css`.
|
||||||
|
|
||||||
Performance notes:
|
Performance notes:
|
||||||
- Website tile icons check a deterministic `vision-start:icon:<encoded-source-url>` entry in `chrome.storage.local` before loading the external URL. Cache population fetches Google S2 favicon URLs for trusted public TLDs through `https://icon.horse/icon/<host>` (a CORS-open favicon service), while non-trusted TLDs and direct icon URLs render directly in `<img>` tags without triggering background `fetch` calls. It deduplicates in-flight requests, stores only `image/*` responses up to 256KiB, and never intercepts or proxies outside requests.
|
- Website tile icons check a deterministic `vision-start:icon:<encoded-source-url>` entry in `chrome.storage.local` before loading the external URL. Lookups made in the same tick are batched into one `chrome.storage.local.get`, and tiles render an empty icon box (not the fallback initial) while the lookup is pending. Cache population fetches Google S2 favicon URLs for trusted public TLDs through `https://icon.horse/icon/<host>` (a CORS-open favicon service), while non-trusted TLDs and direct icon URLs render directly in `<img>` tags without triggering background `fetch` calls. It deduplicates in-flight requests, stores only `image/*` responses up to 256KiB, and never intercepts or proxies outside requests.
|
||||||
- Modals (`ConfigurationModal`, `WebsiteEditModal`, `CategoryEditModal`) are code-split via `React.lazy` + `Suspense` and only loaded when opened. `ConfigurationModal` is the heaviest chunk (it pulls in `@hello-pangea/dnd` via `ServerWidgetTab`); the rest of `@hello-pangea/dnd` is isolated from the initial load. `WebsiteEditModal` and `CategoryEditModal` share a common `ModalShell` component.
|
- Modals (`ConfigurationModal`, `WebsiteEditModal`, `CategoryEditModal`) are code-split via `React.lazy` + `Suspense` and only loaded when opened. `ServerWidgetTab` is independently lazy-loaded, so its `@hello-pangea/dnd` dependency is loaded only when the Server Widget settings tab is selected. `WebsiteEditModal` and `CategoryEditModal` share a common `ModalShell` component.
|
||||||
- `WebsiteTile` and `CategoryGroup` are wrapped in `React.memo`; `App.tsx` handlers are `useCallback`-stabilized and pure alignment helpers are hoisted to module scope, so opening a modal / toggling edit no longer re-renders every tile.
|
- `WebsiteTile` and `CategoryGroup` are wrapped in `React.memo`; `App.tsx` handlers are `useCallback`-stabilized and pure alignment helpers are hoisted to module scope, so opening a modal / toggling edit no longer re-renders every tile.
|
||||||
- `Clock` updates on the minute boundary (one `setTimeout` → `setInterval(60_000)`) instead of every second.
|
- `Clock` schedules one timeout for the next minute boundary, pauses while hidden, and refreshes immediately on focus or visibility return.
|
||||||
- `jsping` cancels its 5s timeout on image resolve/error and nulls the `Image` handlers, preventing leaks across ping cycles.
|
- `jsping` parses addresses with the shared `parseServerAddress` (also used to validate new servers in the settings tab), uses HTTP HEAD without downloading or decoding probe images, propagates failures, and cleans up its timeout and abort listener.
|
||||||
- `ServerWidget` batches pending-status updates into one `setState` and depends on a stable servers signature (ids+addresses) so unrelated config edits don't restart pings.
|
- `ServerWidget` runs at most four probes concurrently, batches completed results into one state update, avoids overlapping polling cycles, cancels work when hidden or unmounted, and depends on a stable ids/addresses signature. Hidden tabs stop polling and refresh on visibility return; removed servers leave no retained status entries.
|
||||||
- Icon metadata (`/icon-metadata.json`) is fetched lazily on first focus of the icon field with `cache: 'force-cache'`, filter debounced ~150ms, and color variants are expanded lazily during filtering rather than upfront. The module-level metadata cache is released when the picker modal unmounts (the browser HTTP cache makes reopening cheap), and the dashboard-icon URL for a picker entry is derived from one shared helper.
|
- The icon picker only previews `http(s)`/`data:image` values (typed names never trigger relative-URL requests), lazy-loads result images, and resolves an exactly matching icon name to its Dashboard Icons URL on save. The Fetch button ignores non-`http(s)` website URLs.
|
||||||
- `Wallpaper` resolves wallpaper URLs through a module-level `Map` bounded to the last 3 entries — so uploaded base64 wallpapers (up to ~4.5MB strings) are not retained in memory for the page's lifetime; its image transition and readability overlay classes live in `index.css`. Wallpaper rotation and frequency parsing (`h`/`d` → hours/ms) share helpers with the Theme tab via `components/utils/wallpaperUtils.ts`.
|
- Icon metadata (`/icon-metadata.json`) is fetched lazily on first focus of the icon field with `cache: 'force-cache'`, filter debounced ~150ms, and color variants are expanded lazily during filtering rather than upfront. Only names, file formats, and color variants are retained in component state; requests are aborted on close, failed loads can retry, and metadata URLs resolve relative to the page so subdirectory deployments work (the browser HTTP cache makes reopening cheap), and the dashboard-icon URL for a picker entry is derived from one shared helper.
|
||||||
- The website icon service keeps an in-memory resolved data-URL cache bounded to 50 entries (FIFO eviction) to avoid unbounded growth from many tiles.
|
- `Wallpaper` resolves remote wallpaper URLs through a module-level `Map` bounded to the last 3 entries. Uploaded data URLs are excluded from that cache, and the cache clears on unmount; its image transition and readability overlay classes live in `index.css`. Wallpaper rotation and frequency parsing (`h`/`d` → hours/ms) share helpers with the Theme tab via `components/utils/wallpaperUtils.ts`.
|
||||||
|
- The website icon service bounds its extra resolved data-URL cache to 50 entries and 2MiB of string storage (conservatively counted at two bytes per character). Cache downloads run at most four at a time, with at most 50 outstanding requests and an 8s timeout. Streaming reads stop at 256KiB before decoding; invalid or oversized persisted entries are discarded. Tile images still retain the data they display, separate from this extra cache.
|
||||||
|
- Tile icon dimensions use numeric inline styles, independent of generated Tailwind classes. Failed icons show the website initial, modified link clicks avoid navigation spinners, and browser history restoration clears the loading state. Category mutations preserve unaffected object references and use stable functional state handlers. Shared IDs use UUIDs with a fallback for ordinary HTTP deployments.
|
||||||
|
- Permanent `will-change` hints are removed from tiles and wallpaper so the browser chooses when to allocate compositing layers. The wallpaper only applies `blur()`/`brightness()` filters and the edge-hiding `scale(1.015)` when they are not neutral.
|
||||||
|
- Uploaded wallpaper data URLs are converted once into `blob:` object URLs (at most two kept, revoked on deselection, cross-tab `userWallpapers` changes, and unmount), so focus/visibility refreshes do not re-read multi-MB base64 from storage and inline styles stay small.
|
||||||
|
- `Wallpaper`, `Header`, `ServerWidget`, `EditButton`, and `ConfigurationButton` are memoized; `Clock` stores a minute key so duplicate focus/visibility refreshes do not re-render; `Dropdown` attaches document listeners only while open.
|
||||||
|
- Startup icon-cache pruning lists keys with `chrome.storage.local.getKeys()` (Chrome 130+) instead of loading every stored value, falling back to `get(null)` on older browsers.
|
||||||
- Shared styling/frequency helpers live in `components/utils/styleUtils.ts` (tile/clock/title size classes, icon pixel sizes, alignment classes, size presets), `wallpaperUtils.ts`, and `urlUtils.ts` (URL→filename extraction, also used by wallpaper storage). Range sliders use the shared `RangeSlider` component; repeated glyphs (pencil, plus, trash, chevrons) use `components/icons.tsx`.
|
- Shared styling/frequency helpers live in `components/utils/styleUtils.ts` (tile/clock/title size classes, icon pixel sizes, alignment classes, size presets), `wallpaperUtils.ts`, and `urlUtils.ts` (URL→filename extraction, also used by wallpaper storage). Range sliders use the shared `RangeSlider` component; repeated glyphs (pencil, plus, trash, chevrons) use `components/icons.tsx`.
|
||||||
|
|
||||||
Planned / To-do (tracked in `README.md`):
|
Planned / To-do (tracked in `README.md`):
|
||||||
@@ -125,11 +126,12 @@ vision-start/
|
|||||||
│ └── utils/
|
│ └── utils/
|
||||||
│ ├── baseWallpapers.ts # Built-in wallpaper catalog (imgur/wallpapershome URLs)
|
│ ├── baseWallpapers.ts # Built-in wallpaper catalog (imgur/wallpapershome URLs)
|
||||||
│ ├── iconService.ts # icon discovery plus CORS-safe website icon cache lookup/population
|
│ ├── iconService.ts # icon discovery plus CORS-safe website icon cache lookup/population
|
||||||
│ ├── jsping.js # Image-load based "ping" with 5s timeout (used by ServerWidget)
|
│ ├── jsping.ts # Cancellable HTTP HEAD reachability probe with 5s timeout
|
||||||
│ ├── StorageLocalManager.ts # chrome.storage.local wrappers + availability check; wallpaper and icon cache storage
|
│ ├── StorageLocalManager.ts # chrome.storage.local wrappers + availability check; wallpaper and icon cache storage
|
||||||
|
│ ├── idUtils.ts # Shared UUID generation with an ordinary-HTTP fallback
|
||||||
│ ├── styleUtils.ts # Shared tile/clock/title size classes, icon pixel sizes, alignment classes, size presets
|
│ ├── styleUtils.ts # Shared tile/clock/title size classes, icon pixel sizes, alignment classes, size presets
|
||||||
│ ├── wallpaperUtils.ts # Wallpaper frequency parsing (h/d → hours/ms) and random-index helpers
|
│ ├── wallpaperUtils.ts # Wallpaper frequency parsing (h/d → hours/ms) and random-index helpers
|
||||||
│ └── urlUtils.ts # URL → filename extraction (shared by wallpaper storage paths)
|
│ └── urlUtils.ts # URL → filename extraction, website URL normalization (scheme allow-list), server address parsing
|
||||||
│
|
│
|
||||||
├── public/
|
├── public/
|
||||||
│ ├── favicon.ico
|
│ ├── favicon.ico
|
||||||
@@ -137,9 +139,10 @@ vision-start/
|
|||||||
│
|
│
|
||||||
├── screenshots/ # README/release screenshots (home, editing, configuration; regenerated at 1280×800)
|
├── screenshots/ # README/release screenshots (home, editing, configuration; regenerated at 1280×800)
|
||||||
├── scripts/
|
├── scripts/
|
||||||
|
│ ├── check_regressions.mjs # Persistence/network regressions, browser memory checks, unpacked-extension smoke test
|
||||||
│ ├── capture_screenshots.mjs # Loads demoData, captures home/edit/configuration with Playwright, and can target a deployed URL
|
│ ├── capture_screenshots.mjs # Loads demoData, captures home/edit/configuration with Playwright, and can target a deployed URL
|
||||||
│ ├── demoData.json # Base64-encoded localStorage fixture used for release screenshots
|
│ ├── demoData.json # Base64-encoded localStorage fixture used for release screenshots
|
||||||
│ ├── prepare_release.sh # Downloads icon-metadata.json from homarr-labs/dashboard-icons
|
│ ├── prepare_release.sh # Downloads icon-metadata.json from homarr-labs/dashboard-icons (fails the build on download errors)
|
||||||
│ └── check_virustotal.sh # Uploads the release zip to VirusTotal, waits for & reports the verdict
|
│ └── check_virustotal.sh # Uploads the release zip to VirusTotal, waits for & reports the verdict
|
||||||
│
|
│
|
||||||
├── .gitea/workflows/
|
├── .gitea/workflows/
|
||||||
@@ -151,11 +154,9 @@ vision-start/
|
|||||||
├── nginx.conf # nginx gzip config (JSON/JS/CSS/SVG/XML), mounted into container
|
├── nginx.conf # nginx gzip config (JSON/JS/CSS/SVG/XML), mounted into container
|
||||||
├── .dockerignore
|
├── .dockerignore
|
||||||
├── .gitignore # Ignores node_modules, dist, .claude/, public/icon-metadata.json, etc.
|
├── .gitignore # Ignores node_modules, dist, .claude/, public/icon-metadata.json, etc.
|
||||||
├── postcss.config.cjs # @tailwindcss/postcss + autoprefixer
|
|
||||||
├── tailwind.config.js # Content globs + safelist of dynamic w-/h- sizes
|
|
||||||
├── tsconfig.json # Strict TS, bundler resolution, `@/*` path alias to project root
|
├── tsconfig.json # Strict TS, bundler resolution, `@/*` path alias to project root
|
||||||
├── vite.config.ts # preact + tailwindcss plugins; single-bundle output; base './'
|
├── vite.config.ts # preact + tailwindcss plugins; single-bundle output; base './'
|
||||||
├── package.json # Scripts: dev, build, preview
|
├── package.json # Scripts: dev, build, preview, typecheck, test, capture:screenshots
|
||||||
├── README.md # Public-facing readme + feature list + roadmap
|
├── README.md # Public-facing readme + feature list + roadmap
|
||||||
└── .env.local # Local env (not tracked in context here)
|
└── .env.local # Local env (not tracked in context here)
|
||||||
```
|
```
|
||||||
@@ -174,7 +175,7 @@ The shape of all persisted data lives in `types.ts`:
|
|||||||
- **`Wallpaper`** — `name`, optional `url` or `base64`
|
- **`Wallpaper`** — `name`, optional `url` or `base64`
|
||||||
- **`Config`** — Everything else: title, wallpaper list + hourly frequency/blur/brightness/opacity, titleSize, vertical & horizontal alignment, tileSize, `clock {enabled, size, font, format}`, `serverWidget {enabled, pingFrequency, servers}`
|
- **`Config`** — Everything else: title, wallpaper list + hourly frequency/blur/brightness/opacity, titleSize, vertical & horizontal alignment, tileSize, `clock {enabled, size, font, format}`, `serverWidget {enabled, pingFrequency, servers}`
|
||||||
|
|
||||||
`ConfigurationService` (`components/services/ConfigurationService.ts`) is the source of truth for default config and persistence helpers. Config loaded from `localStorage` (and imported from export files) is run through `normalizeConfig()`, a schema-driven deep merge against `DEFAULT_CONFIG`: nested blocks (`clock`, `serverWidget`) inherit new sub-fields added to defaults, stored values with the wrong type fall back to defaults, and keys absent from the default schema are pruned. The merge is self-healing — `App.tsx`'s persist-`useEffect` writes the normalized shape back to `localStorage` on first run.
|
`ConfigurationService` (`components/services/ConfigurationService.ts`) is the source of truth for default config and persistence helpers. Config loaded from `localStorage` (and imported from export files) is run through `normalizeConfig()`, a schema-driven deep merge against `DEFAULT_CONFIG`: nested blocks (`clock`, `serverWidget`) inherit new sub-fields added to defaults, stored values with the wrong type fall back to defaults, and keys absent from the default schema are pruned. Nested defaults are cloned, option values (including `clock.font`) and numeric ranges are validated, `wallpaperFrequency` is rewritten to the canonical `<hours>h` form (default `24h`; legacy `1d`/`2d` convert), and malformed wallpaper/server entries are filtered. Categories and the user wallpaper index are normalized before rendering; website URLs go through `normalizeWebsiteUrl` (bare hosts get `https://`, disallowed schemes such as `javascript:` drop the website), and website category IDs are repaired to match their containing category. The merge is self-healing — `App.tsx`'s persist-`useEffect` writes the normalized shape back to `localStorage` on first run.
|
||||||
|
|
||||||
Storage layout (browser-side):
|
Storage layout (browser-side):
|
||||||
|
|
||||||
@@ -185,7 +186,7 @@ Storage layout (browser-side):
|
|||||||
| `userWallpapers` | `localStorage` | `Wallpaper[]` index (names plus URLs for remote wallpapers) |
|
| `userWallpapers` | `localStorage` | `Wallpaper[]` index (names plus URLs for remote wallpapers) |
|
||||||
| `wallpaperState` | `localStorage` | `{ lastWallpaperChange, currentIndex, currentName? }` for rotation (legacy index-only state remains supported) |
|
| `wallpaperState` | `localStorage` | `{ lastWallpaperChange, currentIndex, currentName? }` for rotation (legacy index-only state remains supported) |
|
||||||
| `<wallpaperName>` | `chrome.storage.local` (when available) | Base64 image data for uploaded wallpaper files and legacy URL wallpapers |
|
| `<wallpaperName>` | `chrome.storage.local` (when available) | Base64 image data for uploaded wallpaper files and legacy URL wallpapers |
|
||||||
| `vision-start:icon:<encoded-source-url>` | `chrome.storage.local` (when available) | CORS-readable website icon data URL, capped at 256KiB |
|
| `vision-start:icon:<encoded-source-url>` | `chrome.storage.local` (when available) | CORS-readable website icon data URL, capped at 256KiB; entries no tile references are pruned ~5s after startup |
|
||||||
|
|
||||||
Export/import bundles keys: `config`, `categories`, `userWallpapers`, `wallpaperState`. Remote wallpaper URLs are included through `userWallpapers`; uploaded image data and rebuildable icon cache entries are not included.
|
Export/import bundles keys: `config`, `categories`, `userWallpapers`, `wallpaperState`. Remote wallpaper URLs are included through `userWallpapers`; uploaded image data and rebuildable icon cache entries are not included.
|
||||||
|
|
||||||
@@ -194,7 +195,7 @@ Export/import bundles keys: `config`, `categories`, `userWallpapers`, `wallpaper
|
|||||||
## 6. Application Flow (high level)
|
## 6. Application Flow (high level)
|
||||||
|
|
||||||
1. `index.html` loads `index.tsx`, which mounts `<App/>` into `#root`.
|
1. `index.html` loads `index.tsx`, which mounts `<App/>` into `#root`.
|
||||||
2. `App.tsx` initializes state from `localStorage` (`categories`) and `ConfigurationService.loadConfig()` (`config`), falling back to defaults.
|
2. `App.tsx` initializes normalized categories and configuration through `ConfigurationService`, falling back to independent copies of defaults.
|
||||||
3. `useEffect` hooks persist `config` and `categories` back to `localStorage` whenever they change.
|
3. `useEffect` hooks persist `config` and `categories` back to `localStorage` whenever they change.
|
||||||
4. The screen renders:
|
4. The screen renders:
|
||||||
- `<Wallpaper>` behind everything (fetches URL/base64 from base catalog or chrome.storage.local; rotates per frequency).
|
- `<Wallpaper>` behind everything (fetches URL/base64 from base catalog or chrome.storage.local; rotates per frequency).
|
||||||
@@ -213,11 +214,17 @@ Export/import bundles keys: `config`, `categories`, `userWallpapers`, `wallpaper
|
|||||||
### Local development / preview
|
### Local development / preview
|
||||||
```bash
|
```bash
|
||||||
npm install
|
npm install
|
||||||
npm run dev # Vite dev server (note: PROJECT.md says prefer `npm run build` for real testing)
|
npm run dev # Vite dev server (note: AGENTS.md says prefer `npm run build` for real testing)
|
||||||
npm run build # Production build → dist/
|
npm run build # Production build → dist/
|
||||||
npm run preview # Serve built dist/
|
npm run preview # Serve built dist/
|
||||||
|
npm run typecheck # Strict TypeScript check (tsc --noEmit)
|
||||||
|
npx playwright install chromium
|
||||||
|
npm test # scripts/check_regressions.mjs; run after building; isolated fixtures and temporary extension profile
|
||||||
|
npm audit # Audit the locked dependency tree
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The regression script covers malformed persisted data, website URL/clock font/wallpaper frequency normalization, icon cache pruning (including the `getKeys` path), Fetch-icon URL derivation, batched icon lookups, cross-tab category sync, partial/legacy imports and quota rollback, wallpaper validation, server probe failure/timeout/cancellation, icon request concurrency/stream limits/cache eviction, hidden-tab clock and polling behavior, modal request cancellation and retained JS heap after repeated picker cycles, lazy settings chunks, and loading an unpacked Manifest V3 extension in an isolated Chromium profile. It uses existing Vite/Playwright dependencies and does not modify the normal browser profile or shipped metadata.
|
||||||
|
|
||||||
### Chrome extension install (manual)
|
### Chrome extension install (manual)
|
||||||
Build, then combine `dist/` + `manifest.json` into a folder and "Load unpacked" from `chrome://extensions`. The release workflow automates this zip.
|
Build, then combine `dist/` + `manifest.json` into a folder and "Load unpacked" from `chrome://extensions`. The release workflow automates this zip.
|
||||||
|
|
||||||
@@ -226,9 +233,9 @@ Build, then combine `dist/` + `manifest.json` into a folder and "Load unpacked"
|
|||||||
|
|
||||||
### CI/CD (Gitea Actions)
|
### CI/CD (Gitea Actions)
|
||||||
- `release.yaml` validates each `vX.Y.Z` tag and stamps the version into `manifest.json` (`"version": "0.0.0"` → the tag) in each build checkout before producing the extension archive and production image. The release ZIP contains the contents of `dist/` at its root alongside `manifest.json` and `extension/icons/`, so the manifest's `index.html` new-tab path resolves directly. Before upload, the workflow tests ZIP integrity, extracts it, and validates the manifest version (no leading zeros, components at most 65535, not all zero), metadata, new-tab page, and icon paths. This is the Chrome Web Store upload ZIP; screenshots remain separate release assets.
|
- `release.yaml` validates each `vX.Y.Z` tag and stamps the version into `manifest.json` (`"version": "0.0.0"` → the tag) in each build checkout before producing the extension archive and production image. The release ZIP contains the contents of `dist/` at its root alongside `manifest.json` and `extension/icons/`, so the manifest's `index.html` new-tab path resolves directly. Before upload, the workflow tests ZIP integrity, extracts it, and validates the manifest version (no leading zeros, components at most 65535, not all zero), metadata, new-tab page, and icon paths. This is the Chrome Web Store upload ZIP; screenshots remain separate release assets.
|
||||||
- **`pull-request.yaml`** — Triggers on pull request open, reopen, and synchronization. It builds and uploads a PR extension archive containing `dist/`, unpacks that archive in a separate Playwright job to generate the three demo screenshots, and uploads both artifacts (screenshots are retained for 30 days). For same-repository PRs, it maintains one Gitea PR comment with inline image attachments; fork PRs retain artifacts but skip the comment because their workflow token is read-only.
|
- **`pull-request.yaml`** — Triggers on pull request open, reopen, and synchronization. It builds and uploads a PR extension archive with `dist/` contents, `manifest.json`, and `extension/` at its root, then unpacks that archive into `dist/` in a separate Playwright job to generate the three demo screenshots, and uploads both artifacts (screenshots are retained for 30 days). For same-repository PRs, it maintains one Gitea PR comment with inline image attachments; fork PRs retain artifacts but skip the comment because their workflow token is read-only.
|
||||||
- After `deploy_vision_start` succeeds, `release.yaml` uses Playwright Chromium against the deployed production page and seeds each browser context from `scripts/demoData.json`. It regenerates `home.png`, `editing.png`, and `configuration.png` at exactly 1280×800, uploads them as artifacts (retained for 30 days), and attaches them as individual Gitea release assets.
|
- After `deploy_vision_start` succeeds, `release.yaml` uses Playwright Chromium against the deployed production page and seeds each browser context from `scripts/demoData.json`. It regenerates `home.png`, `editing.png`, and `configuration.png` at exactly 1280×800, uploads them as artifacts (retained for 30 days), and attaches them as individual Gitea release assets.
|
||||||
- **`main.yaml`** — Triggers on push to `main` (and `workflow_dispatch`). Builds, pushes a `staging` multi-arch (amd64/arm64) image to `git.ivanch.me/ivanch/vision-start:staging`, then SSH-deploys on the staging host via `docker compose up -d --force-recreate`.
|
- **`main.yaml`** — Triggers on push to `main` (and `workflow_dispatch`). Type-checks (`npm run typecheck`, also run by `pull-request.yaml`), builds, pushes a `staging` multi-arch (amd64/arm64) image to `git.ivanch.me/ivanch/vision-start:staging`, then SSH-deploys on the staging host via `docker compose up -d --force-recreate`.
|
||||||
- **`release.yaml`** — Triggers on `v*` tags. Builds, zips `dist/` + `manifest.json` as `vision-start-<tag>.zip`, runs `scripts/check_virustotal.sh` against it (publishes analysis URL + detection ratio on the release body), creates a Gitea release, pushes a `latest` multi-arch image, and SSH-deploys to production.
|
- **`release.yaml`** — Triggers on `v*` tags. Builds, zips `dist/` + `manifest.json` as `vision-start-<tag>.zip`, runs `scripts/check_virustotal.sh` against it (publishes analysis URL + detection ratio on the release body), creates a Gitea release, pushes a `latest` multi-arch image, and SSH-deploys to production.
|
||||||
|
|
||||||
Required CI secrets (referenced by the workflows): `REGISTRY_PASSWORD`, `HOST`, `USERNAME`, `KEY`, `PORT`, `STAGING_DIR`, `PROD_DIR`, `VIRUSTOTAL_APIKEY`.
|
Required CI secrets (referenced by the workflows): `REGISTRY_PASSWORD`, `HOST`, `USERNAME`, `KEY`, `PORT`, `STAGING_DIR`, `PROD_DIR`, `VIRUSTOTAL_APIKEY`.
|
||||||
@@ -241,14 +248,16 @@ External assets fetched at build time by `scripts/prepare_release.sh`:
|
|||||||
## 8. Notable Behaviors & Quirks
|
## 8. Notable Behaviors & Quirks
|
||||||
|
|
||||||
- **`EditModal.tsx` has been removed.** It was a legacy drag-and-drop editor that imported non-existent `lucide-react` and `./IconPicker`; it was never wired into `App.tsx`. Use `WebsiteEditModal.tsx` / `CategoryEditModal.tsx` instead, both of which share the `ModalShell` component.
|
- **`EditModal.tsx` has been removed.** It was a legacy drag-and-drop editor that imported non-existent `lucide-react` and `./IconPicker`; it was never wired into `App.tsx`. Use `WebsiteEditModal.tsx` / `CategoryEditModal.tsx` instead, both of which share the `ModalShell` component.
|
||||||
- **`@hello-pangea/dnd`** is used only in `ServerWidgetTab.tsx` (server reorder), which itself is imported by the lazy-loaded `ConfigurationModal`, so it lives in a separate chunk and is absent from the initial page load. `WebsiteTile` moves tiles within their own category via simple left/right buttons (no cross-category movement), not drag-and-drop.
|
- **`@hello-pangea/dnd`** is used only in `ServerWidgetTab.tsx` (server reorder), which is independently lazy-loaded by `ConfigurationModal`, so opening General/Theme/Clock settings does not load the drag-and-drop chunk. `WebsiteTile` moves tiles within their own category via simple left/right buttons (no cross-category movement), not drag-and-drop.
|
||||||
- **Chrome storage is optional.** `StorageLocalManager` checks availability once (`checkChromeStorageLocalAvailable`) and caches it. Remote wallpaper URLs work without it because their URLs live in `userWallpapers`; file upload is gated off when unavailable, and `addWallpaperToChromeStorageLocal` throws if called without it.
|
- **Import validation** accepts both export bundles and legacy objects containing serialized storage values. Files larger than 10MB are rejected before reading. Required keys are normalized and validated before writes; storage failures clear affected keys before restoring previous values so rollback also works near the quota limit. Omitted keys retain their existing settings. Importing marks the settings drawer as saved, preventing its cancel cleanup from restoring pre-import wallpapers.
|
||||||
|
- **Wallpaper mutations** reject duplicate/built-in/reserved names and non-image file uploads. The settings drawer serializes wallpaper mutations and reads the latest persisted index, only updates its list after persistence succeeds, and cancel does not reselect deleted wallpapers.
|
||||||
|
- **Chrome storage is optional.** `StorageLocalManager` checks availability once (`checkChromeStorageLocalAvailable`) and caches it. Remote wallpaper URLs work without it because their URLs live in `userWallpapers`; file upload is gated off when unavailable, and `addWallpaperToChromeStorageLocal` throws if called without it. The extension uses the default ~10MB `chrome.storage.local` quota (no `unlimitedStorage`); quota failures on upload show a friendly "not enough extension storage" message.
|
||||||
- **Wallpaper rotation** uses a timeout scheduled from the persisted last-change timestamp, with checks on mount, focus, and return to a visible tab. Overdue backgrounds rotate once and start a new interval; frequency changes use elapsed time rather than restarting the countdown. Frequency is clamped to 1–48 hours and legacy `1d`/`2d` values remain supported. Invalid or future timestamps recover to the current time. State tracks the wallpaper name as well as its legacy index so reordering or shrinking the selection preserves the current wallpaper when possible. Missing data is skipped and an empty selection hides the background. Manual random changes exclude the current wallpaper and restart the interval. Opening settings does not reset rotation. Wallpaper state writes skip identical serialized values, and empty selections preserve the saved timestamp during refreshes to prevent repeated cross-tab updates. Storage events synchronize wallpaper changes across tabs; outdated asynchronous resolutions are discarded. URL caches are cleared when wallpaper inputs or stored wallpaper data change.
|
- **Wallpaper rotation** uses a timeout scheduled from the persisted last-change timestamp, with checks on mount, focus, and return to a visible tab. Overdue backgrounds rotate once and start a new interval; frequency changes use elapsed time rather than restarting the countdown. Frequency is clamped to 1–48 hours and legacy `1d`/`2d` values remain supported. Invalid or future timestamps recover to the current time. State tracks the wallpaper name as well as its legacy index so reordering or shrinking the selection preserves the current wallpaper when possible. Missing data is skipped and an empty selection hides the background. Manual random changes exclude the current wallpaper and restart the interval. Opening settings does not reset rotation. Wallpaper state writes skip identical serialized values, and empty selections preserve the saved timestamp during refreshes to prevent repeated cross-tab updates. Storage events synchronize wallpaper changes across tabs; outdated asynchronous resolutions are discarded. URL caches are cleared when wallpaper inputs or stored wallpaper data change.
|
||||||
- **Icon picker** in `WebsiteEditModal` loads `/icon-metadata.json` at runtime and expands each icon's `colors` into duplicate-name entries so color variants are searchable.
|
- **Icon picker** in `WebsiteEditModal` loads page-relative `icon-metadata.json` on focus, validates the response, and lazily expands color variants into up to 50 searchable results. Closing it cancels metadata fetching and filtering timers.
|
||||||
- **Website icon cache** is persistent only in `chrome.storage.local`; it is rebuilt from website icon URLs after configuration import. Only `image/*` responses no larger than 256KiB are cached. Trusted public TLDs use Google S2 and the CORS-open `icon.horse` service for favicon caching, while non-trusted TLDs (local TLDs, IP addresses, custom domains) fetch `${origin}/favicon.ico` directly. No site HTML is ever fetched for icon discovery.
|
- **Website icon cache** is persistent only in `chrome.storage.local`; it is rebuilt from website icon URLs after configuration import. Only `image/*` responses no larger than 256KiB are cached. Trusted public TLDs use Google S2 and the CORS-open `icon.horse` service for favicon caching, while non-trusted TLDs (local TLDs, IP addresses, custom domains) fetch `${origin}/favicon.ico` directly. No site HTML is ever fetched for icon discovery.
|
||||||
- **`tsconfig.json` does not emit JS** (`noEmit: true`, bundler resolution); Vite handles all transpilation.
|
- **`tsconfig.json` does not emit JS** (`noEmit: true`, bundler resolution); Vite handles all transpilation.
|
||||||
- **`tailwind.config.js` safelists** a set of `w-[Npx]/h-[Npx]` classes because `WebsiteTile` generates tailwind classes dynamically from `tileSize` (`w-[42px]`, etc.).
|
- **Tile/icon sizing** uses static tile classes and numeric inline icon dimensions. Tailwind v4 only generates classes found literally in source; there is no safelist.
|
||||||
- **Project guidance note** in `PROJECT.md`: do not use `npm run dev` for real verification — use `npm run build`.
|
- **Project guidance note** in `AGENTS.md`: do not use `npm run dev` for real verification — use `npm run build`.
|
||||||
- **`.claude/` and `.env.local`** are local-only / gitignored; not part of shipped artifacts.
|
- **`.claude/` and `.env.local`** are local-only / gitignored; not part of shipped artifacts.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -264,14 +273,17 @@ External assets fetched at build time by `scripts/prepare_release.sh`:
|
|||||||
| Main app wiring (state, handlers, layout) | `App.tsx` |
|
| Main app wiring (state, handlers, layout) | `App.tsx` |
|
||||||
| Settings UI | `components/ConfigurationModal.tsx` + `components/configuration/*Tab.tsx` |
|
| Settings UI | `components/ConfigurationModal.tsx` + `components/configuration/*Tab.tsx` |
|
||||||
| Wallpaper rendering/rotation | `components/Wallpaper.tsx` |
|
| Wallpaper rendering/rotation | `components/Wallpaper.tsx` |
|
||||||
| Server status logic | `components/ServerWidget.tsx` + `components/utils/jsping.js` |
|
| Server status logic | `components/ServerWidget.tsx` + `components/utils/jsping.ts` |
|
||||||
| Icon fetch / picker / metadata | `components/utils/iconService.ts`, `components/WebsiteEditModal.tsx`, `public/icon-metadata.json` |
|
| Icon fetch / picker / metadata | `components/utils/iconService.ts`, `components/WebsiteEditModal.tsx`, `public/icon-metadata.json` |
|
||||||
| chrome.storage.local access | `components/utils/StorageLocalManager.ts` |
|
| chrome.storage.local access | `components/utils/StorageLocalManager.ts` |
|
||||||
| Website icon cache | `components/utils/iconService.ts`, `components/WebsiteTile.tsx`, `components/utils/StorageLocalManager.ts` |
|
| Website icon cache | `components/utils/iconService.ts`, `components/WebsiteTile.tsx`, `components/utils/StorageLocalManager.ts` |
|
||||||
|
| Regression and memory checks | `scripts/check_regressions.mjs` (run after `npm run build`) |
|
||||||
|
| Shared IDs | `components/utils/idUtils.ts` |
|
||||||
|
| URL validation (websites, server addresses) | `components/utils/urlUtils.ts` (`normalizeWebsiteUrl`, `parseServerAddress`) |
|
||||||
| Export/import config | `components/services/ConfigurationService.ts` (`exportConfig`, `importConfig`) |
|
| Export/import config | `components/services/ConfigurationService.ts` (`exportConfig`, `importConfig`) |
|
||||||
| Build/release/PR pipelines | `scripts/prepare_release.sh`, `scripts/capture_screenshots.mjs`, `scripts/check_virustotal.sh`, `.gitea/workflows/pull-request.yaml`, `.gitea/workflows/release.yaml` |
|
| Build/release/PR pipelines | `scripts/prepare_release.sh`, `scripts/capture_screenshots.mjs`, `scripts/check_virustotal.sh`, `.gitea/workflows/pull-request.yaml`, `.gitea/workflows/release.yaml` |
|
||||||
| Docker build | `Dockerfile` |
|
| Docker build | `Dockerfile` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
_Last updated: 2026-08-11. Generated as a general project overview; not a coding-style guide._
|
_Last updated: 2026-10-28. Generated as a general project overview; not a coding-style guide._
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
|
import { mkdtemp, cp, rm } from 'node:fs/promises';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { build, preview } from 'vite';
|
||||||
|
import { chromium } from 'playwright';
|
||||||
|
|
||||||
|
const loadModule = async (entry) => {
|
||||||
|
const result = await build({
|
||||||
|
configFile: false,
|
||||||
|
logLevel: 'silent',
|
||||||
|
build: {
|
||||||
|
write: false,
|
||||||
|
minify: false,
|
||||||
|
lib: { entry: resolve(entry), formats: ['es'] },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const output = Array.isArray(result) ? result[0] : result;
|
||||||
|
const code = output.output.find(chunk => chunk.type === 'chunk' && chunk.isEntry).code;
|
||||||
|
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const storage = new Map();
|
||||||
|
const chromeStorage = new Map();
|
||||||
|
let failWrite = null;
|
||||||
|
let maximumStorageBytes = Infinity;
|
||||||
|
let chromeReads = 0;
|
||||||
|
globalThis.localStorage = {
|
||||||
|
getItem: key => storage.get(key) ?? null,
|
||||||
|
setItem: (key, value) => {
|
||||||
|
if (key === failWrite) {
|
||||||
|
failWrite = null;
|
||||||
|
throw new Error('Quota exceeded');
|
||||||
|
}
|
||||||
|
const next = new Map(storage).set(key, value);
|
||||||
|
if ([...next.values()].reduce((bytes, entry) => bytes + entry.length, 0) > maximumStorageBytes) throw new Error('Quota exceeded');
|
||||||
|
storage.set(key, value);
|
||||||
|
},
|
||||||
|
removeItem: key => storage.delete(key),
|
||||||
|
};
|
||||||
|
globalThis.window = { chrome: { storage: { local: {
|
||||||
|
get: (keys, callback) => {
|
||||||
|
chromeReads++;
|
||||||
|
callback(keys === null ? Object.fromEntries(chromeStorage) : Object.fromEntries(keys.map(key => [key, chromeStorage.get(key)])));
|
||||||
|
},
|
||||||
|
set: (values, callback) => {
|
||||||
|
Object.entries(values).forEach(([key, value]) => chromeStorage.set(key, value));
|
||||||
|
callback();
|
||||||
|
},
|
||||||
|
remove: (keys, callback) => { [keys].flat().forEach(key => chromeStorage.delete(key)); callback(); },
|
||||||
|
} } } };
|
||||||
|
globalThis.FileReader = class {
|
||||||
|
readAsDataURL(blob) {
|
||||||
|
blob.arrayBuffer().then(buffer => {
|
||||||
|
this.result = `data:${blob.type};base64,${Buffer.from(buffer).toString('base64')}`;
|
||||||
|
this.onloadend?.();
|
||||||
|
this.onload?.();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const [{ ConfigurationService, DEFAULT_CONFIG, normalizeConfig, normalizeCategories }, icons, { default: ping }, { normalizeWebsiteUrl }, { pruneCachedIconsFromChromeStorageLocal }] = await Promise.all([
|
||||||
|
loadModule('components/services/ConfigurationService.ts'),
|
||||||
|
loadModule('components/utils/iconService.ts'),
|
||||||
|
loadModule('components/utils/jsping.ts'),
|
||||||
|
loadModule('components/utils/urlUtils.ts'),
|
||||||
|
loadModule('components/utils/StorageLocalManager.ts'),
|
||||||
|
]);
|
||||||
|
const file = value => new File([JSON.stringify(value)], 'config.json', { type: 'application/json' });
|
||||||
|
const iconUrl = name => `https://www.google.com/s2/favicons?domain=${name}.com&sz=128`;
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
|
||||||
|
await test('malformed stored data recovers without shared defaults or unsafe polling rates', () => {
|
||||||
|
const config = normalizeConfig({ currentWallpapers: [null, 'Beach', 'Beach'], serverWidget: { pingFrequency: -1, servers: [null, {}, { id: '1', name: 'Server', address: 'localhost' }] }, clock: { size: 'unknown' }, wallpaperBlur: Infinity });
|
||||||
|
assert.deepEqual(config.currentWallpapers, ['Beach']);
|
||||||
|
assert.equal(config.serverWidget.pingFrequency, 5);
|
||||||
|
assert.equal(config.serverWidget.servers.length, 1);
|
||||||
|
assert.equal(config.clock.size, 'medium');
|
||||||
|
assert.equal(config.wallpaperBlur, 0);
|
||||||
|
const defaults = normalizeConfig(null);
|
||||||
|
defaults.clock.enabled = false;
|
||||||
|
defaults.currentWallpapers.length = 0;
|
||||||
|
assert.equal(DEFAULT_CONFIG.clock.enabled, true);
|
||||||
|
assert.deepEqual(DEFAULT_CONFIG.currentWallpapers, ['Beach']);
|
||||||
|
storage.set('categories', 'null');
|
||||||
|
assert.equal(ConfigurationService.loadCategories()[0].name, 'Search');
|
||||||
|
assert.deepEqual(normalizeCategories([]), []);
|
||||||
|
assert.deepEqual(normalizeCategories([null, { id: 'c', name: 'Group', websites: [null, { id: 'w', name: 'Site', url: 'https://example.com', categoryId: 'wrong' }] }])[0].websites[0].categoryId, 'c');
|
||||||
|
storage.set('userWallpapers', '{}');
|
||||||
|
assert.deepEqual(ConfigurationService.loadUserWallpapers(), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('website URLs, clock fonts, and wallpaper frequency are normalized', async () => {
|
||||||
|
assert.equal(normalizeWebsiteUrl('github.com'), 'https://github.com/');
|
||||||
|
assert.equal(normalizeWebsiteUrl('localhost:8080/app'), 'https://localhost:8080/app');
|
||||||
|
assert.equal(normalizeWebsiteUrl('mailto:me@example.com'), 'mailto:me@example.com');
|
||||||
|
assert.equal(normalizeWebsiteUrl('javascript:alert(1)'), null);
|
||||||
|
assert.equal(normalizeWebsiteUrl('data:text/html,hi'), null);
|
||||||
|
assert.equal(normalizeWebsiteUrl(' '), null);
|
||||||
|
const websites = normalizeCategories([{ id: 'c', name: 'Group', websites: [
|
||||||
|
{ id: 'a', name: 'Bad', url: 'javascript:alert(1)' },
|
||||||
|
{ id: 'b', name: 'Bare', url: 'example.com' },
|
||||||
|
] }])[0].websites;
|
||||||
|
assert.deepEqual(websites.map(website => website.url), ['https://example.com/']);
|
||||||
|
assert.equal(normalizeConfig({ clock: { font: `'Orbitron', sans-serif` } }).clock.font, 'Helvetica');
|
||||||
|
assert.equal(normalizeConfig({ clock: { font: 'monospace' } }).clock.font, 'monospace');
|
||||||
|
assert.equal(normalizeConfig({ wallpaperFrequency: '2d' }).wallpaperFrequency, '48h');
|
||||||
|
assert.equal(normalizeConfig({ wallpaperFrequency: 'weekly' }).wallpaperFrequency, '24h');
|
||||||
|
chromeStorage.clear();
|
||||||
|
chromeStorage.set(`vision-start:icon:${encodeURIComponent(iconUrl('keep'))}`, 'data:image/png;base64,a');
|
||||||
|
chromeStorage.set(`vision-start:icon:${encodeURIComponent(iconUrl('drop'))}`, 'data:image/png;base64,b');
|
||||||
|
chromeStorage.set('My Wallpaper', 'data:image/png;base64,c');
|
||||||
|
assert.equal(await pruneCachedIconsFromChromeStorageLocal([iconUrl('keep')]), 1);
|
||||||
|
assert.deepEqual([...chromeStorage.keys()].sort(), ['My Wallpaper', `vision-start:icon:${encodeURIComponent(iconUrl('keep'))}`].sort());
|
||||||
|
chromeStorage.set(`vision-start:icon:${encodeURIComponent(iconUrl('stale'))}`, 'data:image/png;base64,d');
|
||||||
|
window.chrome.storage.local.getKeys = callback => callback([...chromeStorage.keys()]);
|
||||||
|
try {
|
||||||
|
const reads = chromeReads;
|
||||||
|
assert.equal(await pruneCachedIconsFromChromeStorageLocal([iconUrl('keep')]), 1);
|
||||||
|
assert.equal(chromeReads, reads, 'Pruning must list keys without reading stored values');
|
||||||
|
assert(chromeStorage.has('My Wallpaper'));
|
||||||
|
} finally { delete window.chrome.storage.local.getKeys; }
|
||||||
|
chromeStorage.clear();
|
||||||
|
assert.equal(await icons.getWebsiteIcon('mailto:me@example.com'), '');
|
||||||
|
assert.equal(await icons.getWebsiteIcon('github.com'), 'https://www.google.com/s2/favicons?domain=github.com&sz=128');
|
||||||
|
assert.equal(await icons.getWebsiteIcon('192.168.1.10:8080'), 'http://192.168.1.10:8080/favicon.ico');
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('imports validate before writing, roll back failures, and preserve omitted settings', async () => {
|
||||||
|
await assert.rejects(ConfigurationService.importConfig({ size: 10 * 1024 * 1024 + 1, text: () => assert.fail('Oversized files must not be read into memory') }), /10MB/);
|
||||||
|
storage.clear();
|
||||||
|
storage.set('config', JSON.stringify({ title: 'Original' }));
|
||||||
|
storage.set('categories', '[]');
|
||||||
|
await assert.rejects(ConfigurationService.importConfig(file({ config: { title: 'Bad' }, categories: {} })), /Invalid categories/);
|
||||||
|
assert.equal(JSON.parse(storage.get('config')).title, 'Original');
|
||||||
|
failWrite = 'categories';
|
||||||
|
await assert.rejects(ConfigurationService.importConfig(file({ config: { title: 'Bad' }, categories: [] })), /Quota/);
|
||||||
|
assert.equal(JSON.parse(storage.get('config')).title, 'Original');
|
||||||
|
const partial = await ConfigurationService.importConfig(file({ categories: '[]' }));
|
||||||
|
assert.equal(partial.config.title, 'Original');
|
||||||
|
const legacy = await ConfigurationService.importConfig(file({ config: JSON.stringify({ title: 'Legacy', clock: { enabled: false } }) }));
|
||||||
|
assert.equal(legacy.config.title, 'Legacy');
|
||||||
|
assert.equal(legacy.config.clock.enabled, false);
|
||||||
|
assert.equal(legacy.config.clock.size, 'medium');
|
||||||
|
storage.set('config', JSON.stringify(normalizeConfig({ title: 'Original'.repeat(50) })));
|
||||||
|
storage.set('userWallpapers', '[]');
|
||||||
|
const previous = new Map(storage);
|
||||||
|
maximumStorageBytes = [...storage.values()].reduce((bytes, value) => bytes + value.length, 0) + 32;
|
||||||
|
try {
|
||||||
|
await assert.rejects(ConfigurationService.importConfig(file({ config: { title: 'Small' }, categories: [{ id: 'c', name: 'Group'.repeat(40), websites: [] }], userWallpapers: [{ name: 'Large', url: `https://example.com/${'image'.repeat(200)}` }] })), /Quota/);
|
||||||
|
assert.deepEqual(storage, previous);
|
||||||
|
} finally { maximumStorageBytes = Infinity; }
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('wallpaper collisions and non-image uploads cannot overwrite storage', async () => {
|
||||||
|
await assert.rejects(ConfigurationService.addWallpaper('Beach', 'https://example.com/image.png'), /already exists/);
|
||||||
|
await assert.rejects(ConfigurationService.addWallpaper('vision-start:icon:reserved', 'https://example.com/image.png'), /reserved/);
|
||||||
|
await assert.rejects(ConfigurationService.addWallpaperFile(new File(['text'], 'image.png', { type: 'text/plain' })), /image file/);
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('server probes reject network failures, timeouts, and cancellation', async () => {
|
||||||
|
try {
|
||||||
|
globalThis.fetch = async (_url, options) => {
|
||||||
|
assert.equal(options.method, 'HEAD');
|
||||||
|
assert.equal(options.credentials, 'omit');
|
||||||
|
return new Response(null);
|
||||||
|
};
|
||||||
|
assert.equal(typeof await ping('localhost:8080'), 'number');
|
||||||
|
globalThis.fetch = async () => { throw new Error('Network failure'); };
|
||||||
|
await assert.rejects(ping('https://offline.example'), /Network failure/);
|
||||||
|
await assert.rejects(ping('ftp://example.com'), /HTTP or HTTPS/);
|
||||||
|
globalThis.fetch = async (_url, { signal }) => new Promise((_resolve, reject) => {
|
||||||
|
if (signal.aborted) reject(new Error('Aborted'));
|
||||||
|
else signal.addEventListener('abort', () => reject(new Error('Aborted')), { once: true });
|
||||||
|
});
|
||||||
|
const controller = new AbortController();
|
||||||
|
const request = ping('https://slow.example', 1, controller.signal);
|
||||||
|
controller.abort();
|
||||||
|
await assert.rejects(request, /Aborted/);
|
||||||
|
const originalTimeout = globalThis.setTimeout;
|
||||||
|
globalThis.setTimeout = callback => { queueMicrotask(callback); return 0; };
|
||||||
|
try { await assert.rejects(ping('https://slow.example'), /Aborted/); }
|
||||||
|
finally { globalThis.setTimeout = originalTimeout; }
|
||||||
|
} finally { globalThis.fetch = originalFetch; }
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('icon requests deduplicate, cap concurrency, reject oversized streams, and evict by bytes', async () => {
|
||||||
|
let active = 0;
|
||||||
|
let maximum = 0;
|
||||||
|
let requests = 0;
|
||||||
|
try {
|
||||||
|
globalThis.fetch = async () => {
|
||||||
|
requests++;
|
||||||
|
maximum = Math.max(maximum, ++active);
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 5));
|
||||||
|
active--;
|
||||||
|
return new Response(new Uint8Array(200 * 1024), { headers: { 'content-type': 'image/png' } });
|
||||||
|
};
|
||||||
|
const results = await Promise.all(Array.from({ length: 12 }, (_, index) => icons.cacheWebsiteIcon(iconUrl(`site${index}`))));
|
||||||
|
assert(results.every(result => result?.startsWith('data:image/png')));
|
||||||
|
assert(maximum <= 4);
|
||||||
|
const reads = chromeReads;
|
||||||
|
await icons.getCachedWebsiteIcon(iconUrl('site0'));
|
||||||
|
assert(chromeReads > reads, 'The oldest large icon must leave the extra memory cache');
|
||||||
|
const batchReads = chromeReads;
|
||||||
|
await Promise.all(['batch-a', 'batch-b', 'batch-c'].map(name => icons.getCachedWebsiteIcon(iconUrl(name))));
|
||||||
|
assert.equal(chromeReads - batchReads, 1, 'Icon cache lookups in one tick must share one storage read');
|
||||||
|
const before = requests;
|
||||||
|
await Promise.all([icons.cacheWebsiteIcon(iconUrl('shared')), icons.cacheWebsiteIcon(iconUrl('shared'))]);
|
||||||
|
assert.equal(requests - before, 1);
|
||||||
|
let cancelled = false;
|
||||||
|
globalThis.fetch = async () => new Response(new ReadableStream({
|
||||||
|
pull(controller) { controller.enqueue(new Uint8Array(128 * 1024)); },
|
||||||
|
cancel() { cancelled = true; },
|
||||||
|
}), { headers: { 'content-type': 'image/png' } });
|
||||||
|
assert.equal(await icons.cacheWebsiteIcon(iconUrl('oversized')), null);
|
||||||
|
assert.equal(cancelled, true);
|
||||||
|
} finally { globalThis.fetch = originalFetch; }
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('production UI survives malformed data, distinguishes server status, and releases modal memory', async () => {
|
||||||
|
const server = await preview({ logLevel: 'silent', preview: { host: '127.0.0.1', port: 0, strictPort: true } });
|
||||||
|
const browser = await chromium.launch();
|
||||||
|
try {
|
||||||
|
const address = server.httpServer.address();
|
||||||
|
const baseUrl = `http://127.0.0.1:${address.port}`;
|
||||||
|
const context = await browser.newContext();
|
||||||
|
const errors = [];
|
||||||
|
const page = await context.newPage();
|
||||||
|
await page.clock.install();
|
||||||
|
page.on('pageerror', error => errors.push(error.message));
|
||||||
|
await context.addInitScript(() => {
|
||||||
|
localStorage.setItem('config', JSON.stringify({ currentWallpapers: [], serverWidget: { enabled: true, pingFrequency: 5, servers: [null, { id: 'on', name: 'Online', address: 'https://online.example' }, { id: 'off', name: 'Offline', address: 'https://offline.example' }] } }));
|
||||||
|
localStorage.setItem('categories', JSON.stringify([null, { id: 'c', name: 'Group', websites: [{ id: 'a', name: 'Alpha', url: 'https://example.com', icon: '' }, { id: 'b', name: 'Beta', url: 'https://example.org', icon: '' }] }]));
|
||||||
|
localStorage.setItem('userWallpapers', 'null');
|
||||||
|
});
|
||||||
|
let onlineProbes = 0;
|
||||||
|
await context.route('https://online.example/**', route => {
|
||||||
|
onlineProbes++;
|
||||||
|
return route.fulfill({ status: 200, body: '' });
|
||||||
|
});
|
||||||
|
await context.route('https://offline.example/**', route => route.abort('connectionfailed'));
|
||||||
|
const metadata = Object.fromEntries(Array.from({ length: 4000 }, (_, index) => [`service-${index}`, { base: 'svg', colors: { blue: `service-${index}-blue` }, aliases: ['unused'.repeat(100)], update: { author: { name: 'unused'.repeat(100) } } }]));
|
||||||
|
let metadataLoads = 0;
|
||||||
|
let delayMetadata = false;
|
||||||
|
let releaseMetadata = () => {};
|
||||||
|
await context.route('**/icon-metadata.json', async route => {
|
||||||
|
metadataLoads++;
|
||||||
|
if (delayMetadata) await new Promise(resolve => { releaseMetadata = resolve; });
|
||||||
|
return route.fulfill({ json: metadata });
|
||||||
|
});
|
||||||
|
await context.route('https://cdn.jsdelivr.net/**', route => route.abort());
|
||||||
|
await page.goto(baseUrl);
|
||||||
|
await page.getByRole('link', { name: 'Open Alpha' }).waitFor();
|
||||||
|
await page.waitForFunction(() => [...document.querySelectorAll('.liquid-status-dot')].some(dot => dot.classList.contains('bg-green-400')) && [...document.querySelectorAll('.liquid-status-dot')].some(dot => dot.classList.contains('bg-red-400')));
|
||||||
|
const beforeHidden = onlineProbes;
|
||||||
|
const clockBeforeHidden = await page.locator('.liquid-clock-text').textContent();
|
||||||
|
await page.evaluate(() => {
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
});
|
||||||
|
await page.clock.fastForward(120_000);
|
||||||
|
assert.equal(onlineProbes, beforeHidden);
|
||||||
|
assert.equal(await page.locator('.liquid-clock-text').textContent(), clockBeforeHidden);
|
||||||
|
const resumedProbe = page.waitForRequest('https://online.example/');
|
||||||
|
await page.evaluate(() => {
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
|
||||||
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
});
|
||||||
|
await resumedProbe;
|
||||||
|
await page.waitForFunction(before => document.querySelector('.liquid-clock-text').textContent !== before, clockBeforeHidden);
|
||||||
|
await page.waitForFunction(() => [...document.querySelectorAll('.liquid-status-dot')].some(dot => dot.classList.contains('bg-green-400')));
|
||||||
|
const downloaded = [];
|
||||||
|
page.on('request', request => downloaded.push(request.url()));
|
||||||
|
await page.getByRole('button', { name: 'Open configuration' }).click();
|
||||||
|
await page.getByRole('dialog').waitFor();
|
||||||
|
assert(!downloaded.some(url => url.includes('ServerWidgetTab.js')));
|
||||||
|
await page.getByRole('button', { name: 'Server Widget', exact: true }).click();
|
||||||
|
await page.getByPlaceholder('Server Name').waitFor();
|
||||||
|
assert(downloaded.some(url => url.includes('ServerWidgetTab.js')));
|
||||||
|
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||||
|
await page.getByRole('dialog').waitFor({ state: 'hidden' });
|
||||||
|
await page.getByRole('button', { name: 'Edit page' }).click();
|
||||||
|
await page.getByRole('button', { name: 'Move Beta left' }).click();
|
||||||
|
assert.deepEqual(await page.locator('a[aria-label$="edit controls"]').evaluateAll(links => links.map(link => [...link.querySelectorAll('span')].at(-1).textContent)), ['Beta', 'Alpha']);
|
||||||
|
await page.clock.runFor(100);
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const categories = JSON.parse(localStorage.getItem('categories'));
|
||||||
|
categories[0].websites.push({ id: 'g', name: 'Gamma', url: 'https://example.net', icon: '', categoryId: categories[0].id });
|
||||||
|
localStorage.setItem('categories', JSON.stringify(categories));
|
||||||
|
window.dispatchEvent(new StorageEvent('storage', { key: 'categories' }));
|
||||||
|
});
|
||||||
|
await page.locator('a[aria-label="Gamma edit controls"]').waitFor();
|
||||||
|
assert.deepEqual(await page.locator('a[aria-label$="edit controls"]').evaluateAll(links => links.map(link => [...link.querySelectorAll('span')].at(-1).textContent)), ['Beta', 'Alpha', 'Gamma']);
|
||||||
|
const openPicker = async () => {
|
||||||
|
await page.getByRole('button', { name: 'Edit Alpha', exact: true }).click();
|
||||||
|
const input = page.getByPlaceholder('Icon URL or name');
|
||||||
|
await input.fill('service');
|
||||||
|
await input.focus();
|
||||||
|
await page.locator('.liquid-dropdown-list').waitFor();
|
||||||
|
assert.equal(await page.locator('.liquid-dropdown-list img').count(), 50);
|
||||||
|
await page.getByRole('button', { name: 'Close', exact: true }).click();
|
||||||
|
await page.getByPlaceholder('Icon URL or name').waitFor({ state: 'hidden' });
|
||||||
|
};
|
||||||
|
await openPicker();
|
||||||
|
const session = await context.newCDPSession(page);
|
||||||
|
const heap = async () => {
|
||||||
|
await session.send('HeapProfiler.collectGarbage');
|
||||||
|
return (await session.send('Runtime.getHeapUsage')).usedSize;
|
||||||
|
};
|
||||||
|
const before = await heap();
|
||||||
|
for (let cycle = 0; cycle < 15; cycle++) await openPicker();
|
||||||
|
const growth = (await heap()) - before;
|
||||||
|
assert(growth < 2 * 1024 * 1024, `Retained JS heap grew by ${growth} bytes`);
|
||||||
|
assert.equal(metadataLoads, 16);
|
||||||
|
assert(!downloaded.some(url => url === `${baseUrl}/service`), 'Typing an icon name must not request it as a relative URL');
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const original = window.fetch;
|
||||||
|
window.fetch = (url, options) => {
|
||||||
|
if (String(url).endsWith('/icon-metadata.json')) window.metadataSignal = options.signal;
|
||||||
|
return original(url, options);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
delayMetadata = true;
|
||||||
|
await page.getByRole('button', { name: 'Edit Alpha', exact: true }).click();
|
||||||
|
const pendingMetadata = page.waitForRequest('**/icon-metadata.json');
|
||||||
|
await page.getByPlaceholder('Icon URL or name').focus();
|
||||||
|
await pendingMetadata;
|
||||||
|
await page.getByRole('button', { name: 'Close', exact: true }).click();
|
||||||
|
await page.waitForFunction(() => window.metadataSignal?.aborted === true);
|
||||||
|
releaseMetadata();
|
||||||
|
delayMetadata = false;
|
||||||
|
await openPicker();
|
||||||
|
assert.equal(metadataLoads, 18);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
console.log(`Retained JS heap change after 15 picker cycles: ${Math.round(growth / 1024)} KiB`);
|
||||||
|
await context.close();
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
await new Promise(resolve => server.httpServer.close(resolve));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('unpacked MV3 extension loads its new-tab page with working chrome storage', async () => {
|
||||||
|
const temporary = await mkdtemp(resolve(tmpdir(), 'vision-start-check-'));
|
||||||
|
const extension = resolve(temporary, 'extension');
|
||||||
|
let context;
|
||||||
|
try {
|
||||||
|
await cp(resolve('dist'), extension, { recursive: true });
|
||||||
|
await cp(resolve('manifest.json'), resolve(extension, 'manifest.json'));
|
||||||
|
await cp(resolve('extension'), resolve(extension, 'extension'), { recursive: true });
|
||||||
|
context = await chromium.launchPersistentContext(resolve(temporary, 'profile'), {
|
||||||
|
channel: 'chromium',
|
||||||
|
headless: true,
|
||||||
|
args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`],
|
||||||
|
});
|
||||||
|
await context.route(/^https?:/, route => route.abort());
|
||||||
|
const page = await context.newPage();
|
||||||
|
const errors = [];
|
||||||
|
page.on('pageerror', error => errors.push(error.message));
|
||||||
|
await page.goto('chrome://newtab');
|
||||||
|
await page.getByRole('button', { name: 'Open configuration' }).waitFor();
|
||||||
|
const origin = await page.evaluate(() => document.location.origin);
|
||||||
|
assert(origin.startsWith('chrome-extension://'), `Unexpected new-tab origin: ${origin}`);
|
||||||
|
assert.equal(await page.evaluate(async () => {
|
||||||
|
await chrome.storage.local.set({ regression: 'working' });
|
||||||
|
return (await chrome.storage.local.get('regression')).regression;
|
||||||
|
}), 'working');
|
||||||
|
await page.getByRole('button', { name: 'Open configuration' }).click();
|
||||||
|
await page.getByRole('dialog').waitFor();
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
} finally {
|
||||||
|
await context?.close();
|
||||||
|
await rm(temporary, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1 +1,3 @@
|
|||||||
wget https://raw.githubusercontent.com/homarr-labs/dashboard-icons/refs/heads/main/metadata.json -O public/icon-metadata.json
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
wget -q https://raw.githubusercontent.com/homarr-labs/dashboard-icons/refs/heads/main/metadata.json -O public/icon-metadata.json
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
/** @type {import('tailwindcss').Config} */
|
|
||||||
export default {
|
|
||||||
content: [
|
|
||||||
"./index.html",
|
|
||||||
"./**/*.{js,ts,jsx,tsx}",
|
|
||||||
],
|
|
||||||
theme: {
|
|
||||||
extend: {},
|
|
||||||
},
|
|
||||||
plugins: [],
|
|
||||||
safelist: [
|
|
||||||
'w-[24px]', 'h-[24px]',
|
|
||||||
'w-[28px]', 'h-[28px]',
|
|
||||||
'w-[32px]', 'h-[32px]',
|
|
||||||
'w-[34px]', 'h-[34px]',
|
|
||||||
'w-[36px]', 'h-[36px]',
|
|
||||||
'w-[40px]', 'h-[40px]',
|
|
||||||
'w-[42px]', 'h-[42px]',
|
|
||||||
'w-[48px]', 'h-[48px]',
|
|
||||||
// add any other sizes you use
|
|
||||||
],
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user