This commit is contained in:
1
.env.example
Normal file
1
.env.example
Normal file
@@ -0,0 +1 @@
|
||||
GIPHY_API_KEY=your_giphy_api_key_here
|
||||
44
.gitea/workflows/docker-publish.yml
Normal file
44
.gitea/workflows/docker-publish.yml
Normal file
@@ -0,0 +1,44 @@
|
||||
name: Docker Build and Push
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
- name: Login to Registry
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: ${{ secrets.DOCKER_REGISTRY }}
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: ${{ secrets.DOCKER_REGISTRY }}/${{ secrets.DOCKER_USERNAME }}/matrix-gif-widget
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=sha,format=long
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
25
.gitignore
vendored
Normal file
25
.gitignore
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
.env
|
||||
33
Dockerfile
Normal file
33
Dockerfile
Normal file
@@ -0,0 +1,33 @@
|
||||
# Stage 1: Build the React Application
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
# Copy source and build
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Serve with Node.js
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package.json and install ONLY production dependencies (server deps)
|
||||
COPY package*.json ./
|
||||
RUN npm ci --only=production
|
||||
|
||||
# Copy built frontend assets
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
# Copy server code
|
||||
COPY server.js ./
|
||||
|
||||
# Expose port
|
||||
EXPOSE 3000
|
||||
|
||||
# Start server
|
||||
CMD ["node", "server.js"]
|
||||
73
README.md
Normal file
73
README.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
eslint.config.js
Normal file
23
eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
index.html
Normal file
13
index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>gif</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
4250
package-lock.json
generated
Normal file
4250
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
37
package.json
Normal file
37
package.json
Normal file
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "gif",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.13.2",
|
||||
"dotenv": "^17.2.3",
|
||||
"express": "^5.2.1",
|
||||
"lodash.debounce": "^4.0.8",
|
||||
"lucide-react": "^0.562.0",
|
||||
"matrix-widget-api": "^1.16.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@types/lodash.debounce": "^4.0.9",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/react": "^19.2.5",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.24",
|
||||
"globals": "^16.5.0",
|
||||
"typescript": "~5.9.3",
|
||||
"typescript-eslint": "^8.46.4",
|
||||
"vite": "^7.2.4"
|
||||
}
|
||||
}
|
||||
1
public/vite.svg
Normal file
1
public/vite.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
125
server.js
Normal file
125
server.js
Normal file
@@ -0,0 +1,125 @@
|
||||
import express from 'express';
|
||||
import path from 'path';
|
||||
import axios from 'axios';
|
||||
import { fileURLToPath } from 'url';
|
||||
import dotenv from 'dotenv';
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const GIPHY_API_KEY = process.env.GIPHY_API_KEY;
|
||||
const GIPHY_BASE_URL = 'https://api.giphy.com/v1/gifs';
|
||||
|
||||
// Serve static files from the build directory
|
||||
app.use(express.static(path.join(__dirname, 'dist')));
|
||||
|
||||
// API Proxy Middleware
|
||||
app.get('/api/search', async (req, res) => {
|
||||
if (!GIPHY_API_KEY) {
|
||||
return res.status(500).json({ error: 'Server misconfiguration: No API Key' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { q, limit = 20, offset = 0 } = req.query;
|
||||
const response = await axios.get(`${GIPHY_BASE_URL}/search`, {
|
||||
params: {
|
||||
api_key: GIPHY_API_KEY,
|
||||
q,
|
||||
limit,
|
||||
offset,
|
||||
rating: 'g' // Safe search by default
|
||||
}
|
||||
});
|
||||
res.json(response.data);
|
||||
} catch (error) {
|
||||
console.error('Search Proxy Error:', error.message);
|
||||
res.status(500).json({ error: 'Failed to fetch from Giphy' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/trending', async (req, res) => {
|
||||
if (!GIPHY_API_KEY) {
|
||||
return res.status(500).json({ error: 'Server misconfiguration: No API Key' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { limit = 20, offset = 0 } = req.query;
|
||||
const response = await axios.get(`${GIPHY_BASE_URL}/trending`, {
|
||||
params: {
|
||||
api_key: GIPHY_API_KEY,
|
||||
limit,
|
||||
offset,
|
||||
rating: 'g'
|
||||
}
|
||||
});
|
||||
res.json(response.data);
|
||||
} catch (error) {
|
||||
console.error('Trending Proxy Error:', error.message);
|
||||
res.status(500).json({ error: 'Failed to fetch from Giphy' });
|
||||
}
|
||||
});
|
||||
|
||||
// Proxy endpoint to fetch GIF and upload to Matrix homeserver
|
||||
app.get('/api/gif-upload', async (req, res) => {
|
||||
try {
|
||||
const { url, homeserver, accessToken } = req.query;
|
||||
|
||||
if (!url) {
|
||||
return res.status(400).json({ error: 'URL parameter required' });
|
||||
}
|
||||
|
||||
if (!homeserver || !accessToken) {
|
||||
return res.status(400).json({ error: 'homeserver and accessToken required' });
|
||||
}
|
||||
|
||||
console.log(`Fetching GIF from ${url}...`);
|
||||
|
||||
// Fetch the GIF
|
||||
const gifResponse = await axios.get(url, {
|
||||
responseType: 'arraybuffer',
|
||||
timeout: 10000,
|
||||
maxContentLength: 10 * 1024 * 1024, // 10MB max
|
||||
});
|
||||
|
||||
const gifBuffer = Buffer.from(gifResponse.data);
|
||||
console.log(`Fetched ${(gifBuffer.length / 1024).toFixed(1)}KB, uploading to Matrix...`);
|
||||
|
||||
// Upload to Matrix homeserver
|
||||
const uploadUrl = `${homeserver}/_matrix/media/v3/upload`;
|
||||
|
||||
const uploadResponse = await axios.post(uploadUrl, gifBuffer, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
'Content-Type': 'image/gif',
|
||||
},
|
||||
timeout: 15000,
|
||||
});
|
||||
|
||||
const mxcUrl = uploadResponse.data.content_uri;
|
||||
console.log(`Uploaded successfully: ${mxcUrl}`);
|
||||
|
||||
res.json({
|
||||
mxcUrl,
|
||||
size: gifBuffer.length
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('GIF Upload Error:', error.response?.data || error.message);
|
||||
res.status(500).json({
|
||||
error: 'Failed to upload GIF',
|
||||
details: error.response?.data || error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Handle React Routing (SPA fallback)
|
||||
app.get(/.*/, (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server running on port ${PORT}`);
|
||||
});
|
||||
207
src/App.tsx
Normal file
207
src/App.tsx
Normal file
@@ -0,0 +1,207 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useMatrixWidget } from './hooks/useMatrixWidget';
|
||||
import { useFavorites } from './hooks/useFavorites';
|
||||
import { gifService } from './services/gifService';
|
||||
import type { GifObject } from './types';
|
||||
import { SearchBar } from './components/SearchBar';
|
||||
import { CategoryPills } from './components/CategoryPills';
|
||||
import { GifGrid } from './components/GifGrid';
|
||||
import './styles/global.css';
|
||||
|
||||
function App() {
|
||||
const [logs, setLogs] = useState<string[]>([]);
|
||||
|
||||
const addLog = (msg: string) => {
|
||||
setLogs(prev => [`[${new Date().toLocaleTimeString()}] ${msg}`, ...prev].slice(0, 5));
|
||||
console.log(msg);
|
||||
};
|
||||
|
||||
const { theme, sendGif, ready, refreshPermissions } = useMatrixWidget(addLog);
|
||||
const { favorites, toggleFavorite, isFavorite } = useFavorites();
|
||||
|
||||
const [categories, setCategories] = useState<string[]>([]);
|
||||
const [selectedCategory, setSelectedCategory] = useState<string>('Trending');
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [gifs, setGifs] = useState<GifObject[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [sendingState, setSendingState] = useState<{ id: string, status: 'sending' | 'sent' | 'error', errorMsg?: string } | null>(null);
|
||||
|
||||
// Apply theme
|
||||
|
||||
// Apply theme
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
}, [theme]);
|
||||
|
||||
// Load categories on mount
|
||||
useEffect(() => {
|
||||
gifService.getCategories().then(setCategories);
|
||||
addLog("App mounted, waiting for Matrix...");
|
||||
}, []);
|
||||
|
||||
// Fetch GIFs
|
||||
useEffect(() => {
|
||||
const fetchGifs = async () => {
|
||||
if (selectedCategory === 'Favorites') {
|
||||
setGifs(favorites);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
let results: GifObject[];
|
||||
if (searchQuery) {
|
||||
results = await gifService.searchGifs(searchQuery);
|
||||
} else if (selectedCategory === 'Trending') {
|
||||
results = await gifService.getTrending();
|
||||
} else {
|
||||
results = await gifService.searchGifs(selectedCategory);
|
||||
}
|
||||
setGifs(results);
|
||||
} catch (error: any) {
|
||||
addLog(`Fetch error: ${error.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchGifs();
|
||||
}, [searchQuery, selectedCategory, favorites]);
|
||||
|
||||
const handleSearch = (query: string) => {
|
||||
setSearchQuery(query);
|
||||
if (query) {
|
||||
setSelectedCategory('');
|
||||
} else {
|
||||
setSelectedCategory('Trending');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCategorySelect = (category: string) => {
|
||||
setSelectedCategory(category);
|
||||
setSearchQuery('');
|
||||
};
|
||||
|
||||
const handleGifSelect = async (gif: GifObject) => {
|
||||
if (!ready) {
|
||||
addLog("Error: Not connected to Matrix");
|
||||
return;
|
||||
}
|
||||
|
||||
setSendingState({ id: gif.id, status: 'sending' });
|
||||
addLog(`Sending GIF: ${gif.id}`);
|
||||
|
||||
try {
|
||||
await sendGif(gif);
|
||||
setSendingState({ id: gif.id, status: 'sent' });
|
||||
addLog("Send success!");
|
||||
setTimeout(() => setSendingState(null), 2000);
|
||||
} catch (e: any) {
|
||||
const msg = e.message || JSON.stringify(e);
|
||||
setSendingState({ id: gif.id, status: 'error', errorMsg: msg });
|
||||
addLog(`Send Failed: ${msg}`);
|
||||
setTimeout(() => setSendingState(null), 5000);
|
||||
}
|
||||
};
|
||||
|
||||
const displayCategories = ['Favorites', ...categories];
|
||||
|
||||
return (
|
||||
<div className="app-container">
|
||||
<div style={{
|
||||
padding: '8px 12px',
|
||||
fontSize: '12px',
|
||||
color: ready ? '#4ECDC4' : '#FF6B6B',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center'
|
||||
}}>
|
||||
<span>Status: {ready ? 'Connected' : 'Connecting...'}</span>
|
||||
{sendingState && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<span style={{
|
||||
fontWeight: 'bold',
|
||||
color: sendingState.status === 'error' ? '#FF6B6B' : '#FFEEAD'
|
||||
}}>
|
||||
{sendingState.status === 'sending' && 'Sending...'}
|
||||
{sendingState.status === 'sent' && 'Sent!'}
|
||||
{sendingState.status === 'error' && 'Failed'}
|
||||
</span>
|
||||
{sendingState.status === 'error' && (
|
||||
<div style={{ display: 'flex', gap: '4px' }}>
|
||||
<button
|
||||
onClick={() => {
|
||||
const id = prompt("Please paste the Widget ID from the logs (looks like !abc...):");
|
||||
if (id) {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('widgetId', id);
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
background: '#2F3136', border: '1px solid #555', borderRadius: '4px',
|
||||
color: 'white', padding: '2px 6px', fontSize: '10px', cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Set ID
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
addLog("Requesting permissions...");
|
||||
refreshPermissions();
|
||||
}}
|
||||
style={{
|
||||
background: '#5865F2', border: 'none', borderRadius: '4px',
|
||||
color: 'white', padding: '2px 6px', fontSize: '10px', cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
Fix Permissions
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Debug Log Box - Always visible */}
|
||||
<div style={{
|
||||
fontSize: '11px',
|
||||
color: '#ccc',
|
||||
padding: '8px 12px',
|
||||
marginBottom: '8px',
|
||||
fontFamily: 'monospace',
|
||||
maxHeight: '120px',
|
||||
minHeight: '60px',
|
||||
overflowY: 'auto',
|
||||
backgroundColor: 'rgba(0,0,0,0.3)',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid rgba(255,255,255,0.1)'
|
||||
}}>
|
||||
{logs.length === 0 ? (
|
||||
<div style={{ color: '#666' }}>Waiting for logs...</div>
|
||||
) : (
|
||||
logs.map((log, i) => <div key={i}>{log}</div>)
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SearchBar onSearch={handleSearch} />
|
||||
|
||||
<CategoryPills
|
||||
categories={displayCategories}
|
||||
selected={selectedCategory}
|
||||
onSelect={handleCategorySelect}
|
||||
/>
|
||||
|
||||
<GifGrid
|
||||
gifs={gifs}
|
||||
loading={loading}
|
||||
onSelect={handleGifSelect}
|
||||
isFavorite={isFavorite}
|
||||
onToggleFavorite={toggleFavorite}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
1
src/assets/react.svg
Normal file
1
src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
24
src/components/CategoryPills.tsx
Normal file
24
src/components/CategoryPills.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
import '../styles/CategoryPills.css';
|
||||
|
||||
interface CategoryPillsProps {
|
||||
categories: string[];
|
||||
selected?: string;
|
||||
onSelect: (category: string) => void;
|
||||
}
|
||||
|
||||
export const CategoryPills: React.FC<CategoryPillsProps> = ({ categories, selected, onSelect }) => {
|
||||
return (
|
||||
<div className="category-pills-scroll">
|
||||
{categories.map((cat) => (
|
||||
<button
|
||||
key={cat}
|
||||
className={`category-pill ${selected === cat ? 'active' : ''}`}
|
||||
onClick={() => onSelect(cat)}
|
||||
>
|
||||
{cat}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
77
src/components/GifGrid.tsx
Normal file
77
src/components/GifGrid.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React, { useState } from 'react';
|
||||
import type { GifObject } from '../types';
|
||||
import { Star } from 'lucide-react';
|
||||
import '../styles/GifGrid.css';
|
||||
|
||||
interface GifItemProps {
|
||||
gif: GifObject;
|
||||
onSelect: (gif: GifObject) => void;
|
||||
isFavorite: boolean;
|
||||
onToggleFavorite: (gif: GifObject) => void;
|
||||
}
|
||||
|
||||
const GifItem: React.FC<GifItemProps> = ({ gif, onSelect, isFavorite, onToggleFavorite }) => {
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
// Use poster if available and not hovered, otherwise use animated
|
||||
const displayUrl = (!isHovered && gif.poster_url) ? gif.poster_url : gif.media_formats.tinygif.url;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="gif-item"
|
||||
onClick={() => onSelect(gif)}
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<img
|
||||
src={displayUrl}
|
||||
alt={gif.title}
|
||||
loading="lazy"
|
||||
className="gif-image"
|
||||
/>
|
||||
<div className="gif-overlay">
|
||||
<button
|
||||
className={`favorite-btn ${isFavorite ? 'active' : ''}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onToggleFavorite(gif);
|
||||
}}
|
||||
>
|
||||
<Star size={16} fill={isFavorite ? "#FFAC33" : "none"} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface GifGridProps {
|
||||
gifs: GifObject[];
|
||||
onSelect: (gif: GifObject) => void;
|
||||
loading?: boolean;
|
||||
isFavorite: (id: string) => boolean;
|
||||
onToggleFavorite: (gif: GifObject) => void;
|
||||
}
|
||||
|
||||
export const GifGrid: React.FC<GifGridProps> = ({ gifs, onSelect, loading, isFavorite, onToggleFavorite }) => {
|
||||
if (loading) {
|
||||
return <div className="loading-state">Loading...</div>;
|
||||
}
|
||||
|
||||
if (gifs.length === 0) {
|
||||
return <div className="empty-state">No GIFs found.</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="gif-grid">
|
||||
{gifs.map((gif) => (
|
||||
<GifItem
|
||||
key={gif.id}
|
||||
gif={gif}
|
||||
onSelect={onSelect}
|
||||
isFavorite={isFavorite(gif.id)}
|
||||
onToggleFavorite={onToggleFavorite}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
45
src/components/SearchBar.tsx
Normal file
45
src/components/SearchBar.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import debounce from 'lodash.debounce';
|
||||
import { Search } from 'lucide-react';
|
||||
import '../styles/SearchBar.css';
|
||||
|
||||
interface SearchBarProps {
|
||||
onSearch: (query: string) => void;
|
||||
}
|
||||
|
||||
export const SearchBar: React.FC<SearchBarProps> = ({ onSearch }) => {
|
||||
const [value, setValue] = useState('');
|
||||
|
||||
// Debounce the callback
|
||||
const debouncedSearch = React.useMemo(
|
||||
() => debounce((query: string) => {
|
||||
onSearch(query);
|
||||
}, 300),
|
||||
[onSearch]
|
||||
);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newVal = e.target.value;
|
||||
setValue(newVal);
|
||||
debouncedSearch(newVal);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
debouncedSearch.cancel();
|
||||
};
|
||||
}, [debouncedSearch]);
|
||||
|
||||
return (
|
||||
<div className="search-bar-container">
|
||||
<Search className="search-icon" size={20} />
|
||||
<input
|
||||
type="text"
|
||||
className="search-input"
|
||||
placeholder="Search GIFs..."
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
32
src/hooks/useFavorites.ts
Normal file
32
src/hooks/useFavorites.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { GifObject } from '../types';
|
||||
|
||||
const STORAGE_KEY = 'matrix_gif_favorites';
|
||||
|
||||
export const useFavorites = () => {
|
||||
const [favorites, setFavorites] = useState<GifObject[]>(() => {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
return saved ? JSON.parse(saved) : [];
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(favorites));
|
||||
}, [favorites]);
|
||||
|
||||
const toggleFavorite = (gif: GifObject) => {
|
||||
setFavorites((prev) => {
|
||||
const isFav = prev.some((f) => f.id === gif.id);
|
||||
if (isFav) {
|
||||
return prev.filter((f) => f.id !== gif.id);
|
||||
} else {
|
||||
return [gif, ...prev];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const isFavorite = (gifId: string) => {
|
||||
return favorites.some((f) => f.id === gifId);
|
||||
};
|
||||
|
||||
return { favorites, toggleFavorite, isFavorite };
|
||||
};
|
||||
156
src/hooks/useMatrixWidget.ts
Normal file
156
src/hooks/useMatrixWidget.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { WidgetApi } from 'matrix-widget-api';
|
||||
import type { GifObject } from '../types';
|
||||
|
||||
export const useMatrixWidget = (onLog?: (msg: string) => void) => {
|
||||
const widgetApiRef = useRef<WidgetApi | null>(null);
|
||||
const [theme] = useState<'light' | 'dark'>(() => {
|
||||
const themeParam = new URLSearchParams(window.location.search).get('theme');
|
||||
return (themeParam === 'light' || themeParam === 'dark') ? themeParam : 'dark';
|
||||
});
|
||||
const [ready, setReady] = useState(false);
|
||||
const initialized = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialized.current) return;
|
||||
initialized.current = true;
|
||||
|
||||
const log = (msg: string) => {
|
||||
console.log(`[Widget] ${msg}`);
|
||||
onLog?.(msg);
|
||||
};
|
||||
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const hashParams = new URLSearchParams(window.location.hash.substring(1));
|
||||
|
||||
log(`URL Search: ${window.location.search}`);
|
||||
log(`URL Hash: ${window.location.hash}`);
|
||||
|
||||
const widgetId = searchParams.get('widgetId') || hashParams.get('widgetId');
|
||||
const finalId = widgetId || 'my-widget-id';
|
||||
|
||||
log(`Widget ID: ${finalId}`);
|
||||
|
||||
try {
|
||||
const api = new WidgetApi(finalId);
|
||||
|
||||
log("Requesting capabilities...");
|
||||
api.requestCapabilities([
|
||||
'm.send_event:m.room.message',
|
||||
'm.sticker',
|
||||
'm.send_event:m.sticker',
|
||||
]);
|
||||
|
||||
log("Starting Widget API...");
|
||||
api.start();
|
||||
|
||||
api.on("ready", () => {
|
||||
log("Widget API Ready!");
|
||||
setReady(true);
|
||||
});
|
||||
|
||||
api.on("error", (err: Error) => {
|
||||
log(`Widget Error: ${err.message}`);
|
||||
});
|
||||
|
||||
widgetApiRef.current = api;
|
||||
|
||||
// Set a timeout to warn if not ready after 5 seconds
|
||||
setTimeout(() => {
|
||||
if (!ready) {
|
||||
log("⚠️ Still not ready after 5s. Are you running inside a Matrix widget?");
|
||||
}
|
||||
}, 5000);
|
||||
|
||||
} catch (error: any) {
|
||||
log(`Init Error: ${error.message}`);
|
||||
}
|
||||
}, [onLog]);
|
||||
|
||||
const refreshPermissions = async () => {
|
||||
if (!widgetApiRef.current) return;
|
||||
onLog?.("Manual permission refresh triggered...");
|
||||
try {
|
||||
await widgetApiRef.current.requestCapabilities([
|
||||
'm.sticker',
|
||||
'm.send_event:m.sticker',
|
||||
'm.send_event:m.room.message',
|
||||
]);
|
||||
onLog?.("Capabilities request sent.");
|
||||
} catch (e) {
|
||||
onLog?.(`Cap Request Error: ${e}`);
|
||||
}
|
||||
};
|
||||
|
||||
const sendGif = async (gif: GifObject) => {
|
||||
const { tinygif } = gif.media_formats;
|
||||
const title = gif.title || "GIF";
|
||||
|
||||
onLog?.(`Sending: ${title}`);
|
||||
|
||||
try {
|
||||
// Get Matrix homeserver and access token from URL params
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const homeserver = searchParams.get('homeserver') || prompt('Enter your Matrix homeserver URL (e.g., https://matrix.org):');
|
||||
const accessToken = searchParams.get('access_token') || prompt('Enter your Matrix access token:');
|
||||
const roomId = searchParams.get('roomId') || prompt('Enter room ID (e.g., !abc123:matrix.org):');
|
||||
|
||||
if (!homeserver || !accessToken || !roomId) {
|
||||
throw new Error('Missing homeserver, access token, or room ID');
|
||||
}
|
||||
|
||||
// Use tinygif for smaller size
|
||||
const gifUrl = tinygif.url;
|
||||
|
||||
onLog?.('Uploading to Matrix...');
|
||||
|
||||
// Upload GIF through our proxy
|
||||
const uploadResponse = await fetch(
|
||||
`/api/gif-upload?url=${encodeURIComponent(gifUrl)}&homeserver=${encodeURIComponent(homeserver)}&accessToken=${encodeURIComponent(accessToken)}`
|
||||
);
|
||||
|
||||
if (!uploadResponse.ok) {
|
||||
const error = await uploadResponse.json();
|
||||
throw new Error(error.details || 'Upload failed');
|
||||
}
|
||||
|
||||
const { mxcUrl, size } = await uploadResponse.json();
|
||||
|
||||
onLog?.(`Uploaded ${(size / 1024).toFixed(1)}KB, sending...`);
|
||||
|
||||
// Send directly via Matrix Client-Server API
|
||||
const txnId = `m${Date.now()}.${Math.random()}`;
|
||||
const sendUrl = `${homeserver}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/send/m.sticker/${txnId}`;
|
||||
|
||||
const sendResponse = await fetch(sendUrl, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
body: title,
|
||||
url: mxcUrl,
|
||||
info: {
|
||||
mimetype: 'image/gif',
|
||||
size: size,
|
||||
w: tinygif.width,
|
||||
h: tinygif.height,
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
if (!sendResponse.ok) {
|
||||
const error = await sendResponse.json();
|
||||
throw new Error(error.error || 'Send failed');
|
||||
}
|
||||
|
||||
onLog?.('✓ GIF sent!');
|
||||
} catch (error: any) {
|
||||
onLog?.(`✗ Failed: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return { theme, sendGif, ready, refreshPermissions };
|
||||
};
|
||||
9
src/main.tsx
Normal file
9
src/main.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
97
src/services/gifService.ts
Normal file
97
src/services/gifService.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import type { GifObject } from '../types';
|
||||
|
||||
const MOCK_CATEGORIES = [
|
||||
"Trending", "LOL", "Facepalm", "Dance", "Cat", "Dog", "Party", "Sad", "Happy", "Clap"
|
||||
];
|
||||
|
||||
const COLORS = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEEAD', '#D4A5A5', '#9B59B6', '#3498DB'];
|
||||
|
||||
// --- Mock Logic (Fallback) ---
|
||||
function generateMockGif(id: string, tag: string, index: number): GifObject {
|
||||
const color = COLORS[index % COLORS.length].replace('#', '');
|
||||
const width = index % 3 === 0 ? 350 : 300;
|
||||
const height = index % 2 === 0 ? 200 : 250;
|
||||
|
||||
return {
|
||||
id: `mock_${id}`,
|
||||
title: `${tag} GIF ${index}`,
|
||||
created: Date.now(),
|
||||
tags: [tag],
|
||||
poster_url: `https://placehold.co/${width}x${height}/${color}/FFFFFF/png?text=${tag}`, // Static is same as tiny for mock
|
||||
media_formats: {
|
||||
tinygif: {
|
||||
url: `https://placehold.co/${width}x${height}/${color}/FFFFFF/png?text=${tag}+Anim`,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
gif: {
|
||||
url: `https://placehold.co/${width * 2}x${height * 2}/${color}/FFFFFF/png?text=${tag}+Full`,
|
||||
width: width * 2,
|
||||
height: height * 2,
|
||||
size: 102400,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// --- Giphy Mapper ---
|
||||
function mapGiphyResult(result: any): GifObject {
|
||||
// Giphy provides 'fixed_width_still' for the static image
|
||||
const preview = result.images.fixed_width_downsampled || result.images.fixed_width;
|
||||
const original = result.images.original;
|
||||
const still = result.images.fixed_width_still;
|
||||
|
||||
return {
|
||||
id: result.id,
|
||||
title: result.title || 'GIF',
|
||||
created: Date.parse(result.import_datetime) || Date.now(),
|
||||
tags: [],
|
||||
poster_url: still ? still.url : preview.url,
|
||||
media_formats: {
|
||||
tinygif: {
|
||||
url: preview.url,
|
||||
width: parseInt(preview.width),
|
||||
height: parseInt(preview.height),
|
||||
size: parseInt(preview.size || '0'),
|
||||
},
|
||||
gif: {
|
||||
url: original.url,
|
||||
width: parseInt(original.width),
|
||||
height: parseInt(original.height),
|
||||
size: parseInt(original.size || '0'),
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const gifService = {
|
||||
getCategories: async (): Promise<string[]> => {
|
||||
return MOCK_CATEGORIES;
|
||||
},
|
||||
|
||||
searchGifs: async (query: string, limit = 20): Promise<GifObject[]> => {
|
||||
try {
|
||||
// Call local proxy
|
||||
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}&limit=${limit}`);
|
||||
if (!response.ok) throw new Error('Network response was not ok');
|
||||
const data = await response.json();
|
||||
return data.data.map(mapGiphyResult);
|
||||
} catch (error) {
|
||||
console.warn('API search failed, falling back to mock data:', error);
|
||||
return Array.from({ length: limit }).map((_, i) => generateMockGif(`search_${query}_${i}`, query, i));
|
||||
}
|
||||
},
|
||||
|
||||
getTrending: async (limit = 20): Promise<GifObject[]> => {
|
||||
try {
|
||||
// Call local proxy
|
||||
const response = await fetch(`/api/trending?limit=${limit}`);
|
||||
if (!response.ok) throw new Error('Network response was not ok');
|
||||
const data = await response.json();
|
||||
return data.data.map(mapGiphyResult);
|
||||
} catch (error) {
|
||||
console.warn('API trending failed, falling back to mock data:', error);
|
||||
return Array.from({ length: limit }).map((_, i) => generateMockGif(`trending_${i}`, 'Trending', i));
|
||||
}
|
||||
}
|
||||
};
|
||||
41
src/styles/CategoryPills.css
Normal file
41
src/styles/CategoryPills.css
Normal file
@@ -0,0 +1,41 @@
|
||||
.category-pills-scroll {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
gap: 8px;
|
||||
padding-bottom: 8px;
|
||||
margin-bottom: 8px;
|
||||
scrollbar-width: thin; /* Firefox */
|
||||
scrollbar-color: #202225 transparent;
|
||||
}
|
||||
|
||||
.category-pills-scroll::-webkit-scrollbar {
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
.category-pills-scroll::-webkit-scrollbar-thumb {
|
||||
background-color: #202225;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.category-pill {
|
||||
background-color: var(--pill-bg, #2F3136);
|
||||
color: var(--text-color, #B9BBBE);
|
||||
border: none;
|
||||
border-radius: 16px;
|
||||
padding: 6px 16px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: background-color 0.2s, color 0.2s;
|
||||
}
|
||||
|
||||
.category-pill:hover {
|
||||
background-color: var(--pill-hover-bg, #40444B);
|
||||
color: var(--text-hover, #FFF);
|
||||
}
|
||||
|
||||
.category-pill.active {
|
||||
background-color: var(--accent-color, #5865F2);
|
||||
color: #FFF;
|
||||
}
|
||||
71
src/styles/GifGrid.css
Normal file
71
src/styles/GifGrid.css
Normal file
@@ -0,0 +1,71 @@
|
||||
.gif-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 8px;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
@media (min-width: 400px) {
|
||||
.gif-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.gif-item {
|
||||
position: relative;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
aspect-ratio: 16/9; /* Force a consistent aspect ratio or use masonry if desired, keeping simple grid for now */
|
||||
background-color: #2F3136;
|
||||
}
|
||||
|
||||
.gif-image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
|
||||
.gif-item:hover .gif-image {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.gif-overlay {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.gif-item:hover .gif-overlay {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.favorite-btn {
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
padding: 4px;
|
||||
color: #FFF;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.favorite-btn:hover {
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
|
||||
.favorite-btn.active {
|
||||
color: #FFAC33;
|
||||
}
|
||||
|
||||
.loading-state, .empty-state {
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
color: var(--text-muted, #72767D);
|
||||
}
|
||||
34
src/styles/SearchBar.css
Normal file
34
src/styles/SearchBar.css
Normal file
@@ -0,0 +1,34 @@
|
||||
.search-bar-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background-color: var(--input-bg, #202225); /* Fallback to Discord dark */
|
||||
border-radius: 4px;
|
||||
padding: 0 12px;
|
||||
height: 40px;
|
||||
margin-bottom: 12px;
|
||||
border: 1px solid transparent;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.search-bar-container:focus-within {
|
||||
border-color: var(--accent-color, #5865F2);
|
||||
}
|
||||
|
||||
.search-icon {
|
||||
color: #B9BBBE;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-color, #DCDDDE);
|
||||
flex: 1;
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.search-input::placeholder {
|
||||
color: #72767D;
|
||||
}
|
||||
51
src/styles/global.css
Normal file
51
src/styles/global.css
Normal file
@@ -0,0 +1,51 @@
|
||||
:root {
|
||||
--bg-color: #36393F;
|
||||
--text-color: #DCDDDE;
|
||||
--text-muted: #72767D;
|
||||
--accent-color: #5865F2;
|
||||
--input-bg: #202225;
|
||||
--pill-bg: #2F3136;
|
||||
--pill-hover-bg: #40444B;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: var(--bg-color);
|
||||
color: var(--text-color);
|
||||
font-family: 'gg sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* Scrollbar styling */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background-color: #2F3136;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: #202225;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* Light Theme Overrides */
|
||||
[data-theme='light'] {
|
||||
--bg-color: #FFFFFF;
|
||||
--text-color: #2E3338;
|
||||
--text-muted: #747F8D;
|
||||
--input-bg: #E3E5E8;
|
||||
--pill-bg: #F2F3F5;
|
||||
--pill-hover-bg: #E3E5E8;
|
||||
}
|
||||
|
||||
.app-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
padding: 12px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
23
src/types/index.ts
Normal file
23
src/types/index.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
export interface GifImage {
|
||||
url: string;
|
||||
width: number;
|
||||
height: number;
|
||||
size?: number; // bytes
|
||||
}
|
||||
|
||||
export interface GifObject {
|
||||
id: string;
|
||||
title: string;
|
||||
media_formats: {
|
||||
tinygif: GifImage; // For preview/grid
|
||||
gif: GifImage; // High res for sending
|
||||
};
|
||||
poster_url?: string; // Static preview (still image)
|
||||
created: number;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
export interface MatrixWidgetConfig {
|
||||
widgetId: string;
|
||||
theme: 'light' | 'dark';
|
||||
}
|
||||
28
tsconfig.app.json
Normal file
28
tsconfig.app.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
tsconfig.json
Normal file
7
tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
26
tsconfig.node.json
Normal file
26
tsconfig.node.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
15
vite.config.ts
Normal file
15
vite.config.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user