file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
src/lib/slack.ts
TypeScript
import request from './request' interface Params { readonly channel: string readonly reachedNum: number readonly removedNum: number readonly webhookUrl: string } const slack = (data: Params) => { const attachments = [{ author_icon: 'https://developer.apple.com/assets/elements/icons/testflight/testflight-64x64.png', author_link: 'https://developer.apple.com/testflight/', author_name: 'Monitor', color: 'warning', fallback: `TestFlight - The number of testers reached ${data.reachedNum}`, fields: [{ short: false, title: ' ', value: `🚑 we just deleted ${data.removedNum} guys!`, }], pretext: `TestFlight - The number of testers reached ${data.reachedNum}`, ts: (Date.now() / 1000).toFixed(0), }] const options = { data: JSON.stringify({ channel: data.channel, username: 'Monitor', attachments, }), headers: { 'Content-Type': 'application/json' }, hostname: 'hooks.slack.com', method: 'POST', path: data.webhookUrl, port: 443, } return request(options) } export default slack
xwartz/testflight-monitor
7
🚑 Manage beta builds of your app, testers, and groups.
TypeScript
xwartz
xwartz
src/lib/utils.ts
TypeScript
export function sleep(ms: number): Promise<null> { return new Promise(resolve => { setTimeout(resolve, ms) }) } export async function asyncForEach(array: any[], callback: Function): Promise<any> { for (let index = 0; index < array.length; index++) { await callback(array[index], index, array) } }
xwartz/testflight-monitor
7
🚑 Manage beta builds of your app, testers, and groups.
TypeScript
xwartz
xwartz
src/types/example.d.ts
TypeScript
/** * If you import a dependency which does not include its own type definitions, * TypeScript will try to find a definition for it by following the `typeRoots` * compiler option in tsconfig.json. For this project, we've configured it to * fall back to this folder if nothing is found in node_modules/@types. * * Often, you can install the DefinitelyTyped * (https://github.com/DefinitelyTyped/DefinitelyTyped) type definition for the * dependency in question. However, if no one has yet contributed definitions * for the package, you may want to declare your own. (If you're using the * `noImplicitAny` compiler options, you'll be required to declare it.) * * This is an example type definition for the `sha.js` package, used in hash.ts. * * (This definition was primarily extracted from: * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v8/index.d.ts */ declare module 'sha.js' { export default function shaJs(algorithm: string): Hash; type Utf8AsciiLatin1Encoding = 'utf8' | 'ascii' | 'latin1'; type HexBase64Latin1Encoding = 'latin1' | 'hex' | 'base64'; export interface Hash extends NodeJS.ReadWriteStream { // tslint:disable:no-method-signature update( data: string | Buffer | DataView, inputEncoding?: Utf8AsciiLatin1Encoding ): Hash; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; // tslint:enable:no-method-signature } }
xwartz/testflight-monitor
7
🚑 Manage beta builds of your app, testers, and groups.
TypeScript
xwartz
xwartz
eslint.config.mjs
JavaScript
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'; export default tseslint.config( { ignores: ['dist', 'node_modules', '*.config.js', '*.config.mjs'] }, { extends: [js.configs.recommended, ...tseslint.configs.recommended], files: ['**/*.{ts,tsx}'], languageOptions: { ecmaVersion: 2020, globals: globals.browser, }, plugins: { 'react-hooks': reactHooks, 'react-refresh': reactRefresh, }, rules: { ...reactHooks.configs.recommended.rules, 'react-refresh/only-export-components': [ 'warn', { allowConstantExport: true }, ], '@typescript-eslint/no-unused-vars': [ 'error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }, ], }, }, { files: ['**/*.js', '**/*.mjs'], ...tseslint.configs.disableTypeChecked, } );
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
index.html
HTML
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="A clean and elegant X (Twitter) timeline aggregator" /> <title>X-Line - X Timeline Aggregator</title> <script> (function() { try { const stored = localStorage.getItem('theme'); let theme = 'system'; if (stored) { try { // useLocalStorage 使用 JSON.stringify,所以需要解析 theme = JSON.parse(stored); } catch (e) { // 如果不是 JSON 格式,直接使用原始值(向后兼容) theme = stored; } } let resolvedTheme = theme; if (theme === 'system') { resolvedTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; } if (resolvedTheme === 'dark') { document.documentElement.classList.add('dark'); document.documentElement.style.colorScheme = 'dark'; } else { document.documentElement.style.colorScheme = 'light'; } } catch (e) { // Ignore errors } })(); </script> <style> html { color-scheme: light dark; } html.dark { color-scheme: dark; } body { background-color: #ffffff; color: #0f172a; } html.dark body { background-color: #15202b; color: #e7e9ea; } </style> </head> <body class="min-h-screen bg-[var(--background)] text-[var(--foreground)]"> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
postcss.config.js
JavaScript
export default { plugins: { tailwindcss: {}, autoprefixer: {}, }, }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
scripts/build-followers.mjs
JavaScript
#!/usr/bin/env node /** * 将 followers.txt 转换为 followers.json * * 此脚本在构建时自动运行,将简单的文本格式转换为 JSON 格式 * 以便前端代码使用 */ import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '..'); const DATA_DIR = path.join(ROOT_DIR, 'data'); const FOLLOWERS_TXT_FILE = path.join(DATA_DIR, 'followers.txt'); const FOLLOWERS_JSON_FILE = path.join(DATA_DIR, 'followers.json'); function parseTextFile() { if (!fs.existsSync(FOLLOWERS_TXT_FILE)) { console.warn(`⚠️ ${FOLLOWERS_TXT_FILE} not found, skipping...`); return null; } const content = fs.readFileSync(FOLLOWERS_TXT_FILE, 'utf-8'); const lines = content.split('\n'); const followers = []; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); // 跳过空行和注释 if (!line || line.startsWith('#')) { continue; } // 解析行:支持 username 或 username,group // displayName 会从推文数据中自动获取,不需要在配置中指定 const parts = line.split(',').map(p => p.trim()); const username = parts[0]; if (!username) { continue; } const follower = { username: username, }; // 可选字段:分组(第二个参数是 group,不再是 displayName) if (parts[1]) { follower.group = parts[1]; } followers.push(follower); } return followers.length > 0 ? followers : null; } function buildFollowersJson() { console.log('Building followers.json from followers.txt...\n'); const followers = parseTextFile(); if (!followers) { console.warn('⚠️ No followers found in text file, keeping existing JSON if exists'); return; } // 确保 data 目录存在 if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } // 生成 JSON const jsonData = { followers: followers, }; // 写入 JSON 文件 fs.writeFileSync( FOLLOWERS_JSON_FILE, JSON.stringify(jsonData, null, 2) + '\n', 'utf-8' ); console.log(`✅ Generated ${FOLLOWERS_JSON_FILE}`); console.log(` Total followers: ${followers.length}`); console.log(` Groups: ${[...new Set(followers.map(f => f.group).filter(Boolean))].join(', ') || 'None'}`); } buildFollowersJson();
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
scripts/fetch-tweets.mjs
JavaScript
#!/usr/bin/env node /** * 推文抓取脚本 * * 使用方式: * node scripts/fetch-tweets.mjs * * 此脚本从 Nitter 实例抓取推文并保存到 data/tweets.json * 可在本地运行或通过 GitHub Actions 定时执行 */ import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { exec } from 'child_process'; import { promisify } from 'util'; const execAsync = promisify(exec); const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '..'); const DATA_DIR = path.join(ROOT_DIR, 'data'); const TWEETS_FILE = path.join(DATA_DIR, 'tweets.json'); const FOLLOWERS_JSON_FILE = path.join(DATA_DIR, 'followers.json'); const FOLLOWERS_TXT_FILE = path.join(DATA_DIR, 'followers.txt'); // 兜底的 Nitter 实例列表 (当动态获取失败时使用) const FALLBACK_NITTER_INSTANCES = [ 'nitter.net', 'nitter.privacyredirect.com', 'xcancel.com', 'nitter.1d4.us', 'nitter.cz', 'nitter.poast.org', ]; // 动态获取实例列表的来源 const INSTANCE_LIST_SOURCES = [ { name: 'GitHub Wiki', url: 'https://raw.githubusercontent.com/wiki/zedeus/nitter/Instances.md', parser: parseGitHubWikiInstances, }, ]; /** * 从 GitHub Wiki Markdown 解析实例列表 * 表格格式: | [domain.com](https://domain.com) | :white_check_mark: | ✅ | ... * 只提取标记为 Online 且 Working 的实例 */ function parseGitHubWikiInstances(text) { const instances = []; const lines = text.split('\n'); for (const line of lines) { // 跳过非数据行 if (!line.startsWith('|') || line.includes('---') || line.includes('URL')) { continue; } // 检查是否标记为工作中 (✅ 或 :white_check_mark:) // 格式: | [url](https://...) | :white_check_mark: | ✅ | country | ... const isOnline = line.includes(':white_check_mark:') || line.includes('✅'); if (!isOnline) { continue; } // 排除 Tor (.onion) 和 I2P (.i2p) 实例 if (line.includes('.onion') || line.includes('.i2p')) { continue; } // 提取域名,格式: [domain.com](https://domain.com) const match = line.match(/\[([^\]]+)\]\(https?:\/\/([^)\/]+)/); if (match) { const domain = match[2].replace(/\/$/, ''); // 过滤掉非域名格式的链接(如 ssllabs.com 验证链接) if (domain && !domain.includes(' ') && domain.includes('.') && !domain.includes('ssllabs.com') && !domain.includes('github.com')) { instances.push(domain); } } } // 去重 return [...new Set(instances)]; } /** * 简单的 HTTP 请求(用于获取实例列表) */ async function simpleFetch(url, timeout = 10) { try { const { stdout } = await execAsync( `curl -sL --connect-timeout ${timeout} --max-time ${timeout * 2} "${url}"`, { maxBuffer: 5 * 1024 * 1024 } ); return stdout; } catch { return null; } } /** * 动态获取 Nitter 实例列表 * 优先从在线源获取,失败则使用兜底列表 */ async function getNitterInstances() { console.log('Fetching Nitter instance list...'); // 官方实例始终优先(在 wiki 的单独 Official 区域) const officialInstances = ['nitter.net']; for (const source of INSTANCE_LIST_SOURCES) { try { console.log(` Trying ${source.name}...`); const text = await simpleFetch(source.url); if (text) { const instances = source.parser(text); if (instances.length > 0) { console.log(` ✓ Found ${instances.length} instances from ${source.name}`); // 官方实例放最前面,然后是从 wiki 获取的实例(去重) const combined = [ ...officialInstances, ...instances.filter(i => !officialInstances.includes(i)), ]; return combined.slice(0, 10); // 最多返回 10 个实例 } } console.log(` ✗ No instances found from ${source.name}`); } catch (error) { console.log(` ✗ Failed to fetch from ${source.name}: ${error.message}`); } } console.log(' Using fallback instance list'); return FALLBACK_NITTER_INSTANCES; } // 运行时的实例列表(将在 main 中初始化) let NITTER_INSTANCES = []; /** * 从文本文件读取关注者列表(优先) * 格式支持: * - 简单格式: username * - 完整格式: username,displayName,group * - 注释行以 # 开头 * - 空行会被忽略 */ function loadFollowersFromText() { if (!fs.existsSync(FOLLOWERS_TXT_FILE)) { return null; } try { const content = fs.readFileSync(FOLLOWERS_TXT_FILE, 'utf-8'); const lines = content.split('\n'); const followers = []; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); // 跳过空行和注释 if (!line || line.startsWith('#')) { continue; } // 解析行:支持 username 或 username,group // displayName 会从推文数据中自动获取,不需要在配置中指定 const parts = line.split(',').map(p => p.trim()); const username = parts[0]; if (!username) { continue; } const follower = { username: username, }; // 可选字段:分组(第二个参数是 group,不再是 displayName) if (parts[1]) { follower.group = parts[1]; } followers.push(follower); } return followers.length > 0 ? followers : null; } catch (error) { console.error(`Error reading ${FOLLOWERS_TXT_FILE}:`, error.message); return null; } } /** * 从 JSON 文件读取关注者列表(向后兼容) */ function loadFollowersFromJson() { if (!fs.existsSync(FOLLOWERS_JSON_FILE)) { return null; } try { const data = JSON.parse(fs.readFileSync(FOLLOWERS_JSON_FILE, 'utf-8')); if (!data.followers || !Array.isArray(data.followers)) { return null; } // 验证每个关注者对象 for (const follower of data.followers) { if (!follower.username) { throw new Error('Invalid follower: missing "username"'); } } return data.followers; } catch (error) { console.error(`Error reading ${FOLLOWERS_JSON_FILE}:`, error.message); return null; } } /** * 加载关注者列表(优先使用文本格式) */ function loadFollowers() { // 优先使用文本格式 let followers = loadFollowersFromText(); // 如果文本格式不存在,尝试 JSON 格式(向后兼容) if (!followers) { followers = loadFollowersFromJson(); } // 如果都不存在,报错 if (!followers || followers.length === 0) { console.error('Error: No followers found!'); console.error(`Please create ${FOLLOWERS_TXT_FILE} with the following format:`); console.error(''); console.error('# 每行一个用户名'); console.error('elonmusk,Elon Musk,Tech'); console.error('jack,Jack Dorsey,Tech'); console.error('# 或者简单格式'); console.error('naval'); console.error('VitalikButerin'); process.exit(1); } return followers; } // 加载关注者列表 const FOLLOWERS = loadFollowers(); const FETCH_TIMEOUT = 30; // 每个用户最多抓取的页数(每页约 20-30 条推文) const MAX_PAGES_PER_USER = 5; /** * 使用 curl 获取页面(绕过 bot 检测) */ async function fetchWithCurl(url, timeout = FETCH_TIMEOUT) { try { // 添加浏览器 User-Agent 和常见请求头以避免 bot 检测 const headers = [ '-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"', '-H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"', '-H "Accept-Language: en-US,en;q=0.9"', '-H "Accept-Encoding: gzip, deflate, br"', '-H "Cache-Control: no-cache"', '-H "Pragma: no-cache"', '-H "Sec-Fetch-Dest: document"', '-H "Sec-Fetch-Mode: navigate"', '-H "Sec-Fetch-Site: none"', '-H "Sec-Fetch-User: ?1"', '-H "Upgrade-Insecure-Requests: 1"', ].join(' '); const { stdout } = await execAsync( `curl -sL --compressed --connect-timeout ${timeout} --max-time ${timeout * 2} ${headers} "${url}"`, { maxBuffer: 10 * 1024 * 1024 } ); return { ok: true, text: () => Promise.resolve(stdout) }; } catch (error) { return { ok: false, error: error.message }; } } /** * 解码 Nitter 图片 URL * Nitter 格式: /pic/https%3A%2F%2Fpbs.twimg.com%2F... 或 /pic/pbs.twimg.com%2F... */ /** * 将 Nitter 的相对 URL 转换为完整的代理 URL */ function decodeNitterUrl(url, instance) { if (!url || !url.startsWith('/pic/')) { return url; } // 保留 Nitter 代理 URL,因为 Twitter 图片需要通过代理访问 // 使用提供的实例域名 return `https://${instance}${url}`; } /** * 从 HTML 中提取文本内容 */ function extractText(html) { return html .replace(/<br\s*\/?>/gi, '\n') .replace(/<a[^>]*href="([^"]*)"[^>]*>([^<]*)<\/a>/gi, '$2') .replace(/<[^>]+>/g, '') .replace(/&amp;/g, '&') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&quot;/g, '"') .replace(/&#39;/g, "'") .replace(/&nbsp;/g, ' ') .trim(); } /** * 解析推文时间 */ function parseTime(timeStr) { // 格式: "Dec 7, 2025 · 5:13 AM UTC" const match = timeStr.match(/(\w+ \d+, \d+)\s*·\s*(\d+:\d+ [AP]M)/); if (match) { const dateStr = `${match[1]} ${match[2]}`; return new Date(dateStr + ' UTC'); } const parsed = new Date(timeStr); if (!isNaN(parsed.getTime())) { return parsed; } return new Date(); } /** * 从数字字符串中提取数字 */ function parseNumber(str) { const cleaned = str.replace(/,/g, '').trim(); const match = cleaned.match(/([\d.]+)\s*([KMB])?/i); if (!match) return 0; let num = parseFloat(match[1]); const suffix = match[2]?.toUpperCase(); if (suffix === 'K') num *= 1000; else if (suffix === 'M') num *= 1000000; else if (suffix === 'B') num *= 1000000000; return Math.round(num); } /** * 从 Nitter HTML 解析推文列表 */ function parseNitterHTML(html, instance, currentUser) { const tweets = []; // 匹配所有 timeline-item const tweetRegex = /<div class="timeline-item[^"]*"[^>]*>([\s\S]*?)(?=<div class="timeline-item|<div class="show-more"|<div class="timeline-footer"|$)/g; let match; while ((match = tweetRegex.exec(html)) !== null) { try { const tweetHtml = match[1]; // 提取推文 ID const idMatch = tweetHtml.match(/\/status\/(\d+)/); const id = idMatch ? idMatch[1] : ''; if (!id) continue; // 提取用户名 const usernameMatch = tweetHtml.match(/<a class="username"[^>]*>@(\w+)<\/a>/); const username = usernameMatch ? usernameMatch[1] : ''; if (!username) continue; // 提取显示名称 const fullnameMatch = tweetHtml.match(/<a class="fullname"[^>]*title="([^"]*)"[^>]*>/); const displayName = fullnameMatch ? fullnameMatch[1] : username; // 提取头像 const avatarMatch = tweetHtml.match(/<img class="avatar[^"]*"[^>]*src="([^"]*)"[^>]*>/); let avatar = avatarMatch ? decodeNitterUrl(avatarMatch[1], instance) : ''; // 提取时间 const timeMatch = tweetHtml.match(/<span class="tweet-date"[^>]*>[\s\S]*?title="([^"]*)"[^>]*>/); const timeStr = timeMatch ? timeMatch[1] : ''; const publishedAt = parseTime(timeStr); // 提取内容 const contentMatch = tweetHtml.match(/<div class="tweet-content[^"]*"[^>]*>([\s\S]*?)<\/div>/); const contentHtml = contentMatch ? contentMatch[1] : ''; const content = extractText(contentHtml); // 提取媒体(需要排除 quote 区块内的媒体) const media = []; // 先移除 quote 区块,避免提取引用推文的媒体 let tweetHtmlWithoutQuote = tweetHtml; const quoteBlockMatch = tweetHtml.match(/<div class="quote[^"]*"[^>]*>([\s\S]*?)(?=<div class="tweet-stats|<p class="tweet-published"|$)/); if (quoteBlockMatch) { tweetHtmlWithoutQuote = tweetHtml.replace(quoteBlockMatch[0], ''); } // 图片 const imgRegex = /<a[^>]*class="still-image"[^>]*href="([^"]*)"[^>]*>/g; let imgMatch; while ((imgMatch = imgRegex.exec(tweetHtmlWithoutQuote)) !== null) { const url = decodeNitterUrl(imgMatch[1], instance); media.push({ type: 'image', url }); } // 视频缩略图 if (tweetHtmlWithoutQuote.includes('gallery-video') || tweetHtmlWithoutQuote.includes('video-container')) { const posterMatch = tweetHtmlWithoutQuote.match(/poster="([^"]*)"/); if (posterMatch) { const thumbnail = decodeNitterUrl(posterMatch[1], instance); media.push({ type: 'video', url: '', thumbnail }); } } // 提取统计数据 const stats = { replies: 0, retweets: 0, likes: 0 }; const statsMatch = tweetHtml.match(/<div class="tweet-stat">([\s\S]*?)<\/div>/g); if (statsMatch) { for (const stat of statsMatch) { const numMatch = stat.match(/>(\d[\d,KMB]*)</i); if (!numMatch) continue; const num = parseNumber(numMatch[1]); if (stat.includes('comment')) stats.replies = num; else if (stat.includes('retweet')) stats.retweets = num; else if (stat.includes('heart')) stats.likes = num; } } // 检查是否为转推 // Nitter HTML 结构: <div class="retweet-header"><span><div class="icon-container">...</div> vitalik.eth retweeted</span></div> let retweet; const retweetHeaderMatch = tweetHtml.match(/<div class="retweet-header"[^>]*>([\s\S]*?)<\/div>/); if (retweetHeaderMatch) { // 提取 "xxx retweeted" 文本 const headerText = retweetHeaderMatch[1].replace(/<[^>]*>/g, '').trim(); const rtNameMatch = headerText.match(/(.+?)\s+retweeted/i); if (rtNameMatch) { const retweeterName = rtNameMatch[1].trim(); retweet = { username: currentUser, // 转推者是当前抓取的用户 displayName: retweeterName, }; } } // 检查引用推文 let quote; const quoteMatch = tweetHtml.match(/<div class="quote[^"]*"[^>]*>([\s\S]*?)(?=<div class="tweet-stats|$)/); if (quoteMatch) { const quoteHtml = quoteMatch[1]; // 提取引用推文的用户名 const quoteUserMatch = quoteHtml.match(/<a class="username"[^>]*>@(\w+)<\/a>/); if (!quoteUserMatch) continue; const quoteUsername = quoteUserMatch[1]; // 提取引用推文的显示名称 const quoteDisplayNameMatch = quoteHtml.match(/<a class="fullname"[^>]*title="([^"]*)"[^>]*>/); const quoteDisplayName = quoteDisplayNameMatch ? quoteDisplayNameMatch[1] : quoteUsername; // 提取引用推文的 ID const quoteLinkMatch = quoteHtml.match(/href="\/[^/]+\/status\/(\d+)/); const quoteId = quoteLinkMatch ? quoteLinkMatch[1] : ''; // 提取引用推文的文本内容 const quoteTextMatch = quoteHtml.match(/<div class="quote-text"[^>]*>([\s\S]*?)<\/div>/); const quoteContent = quoteTextMatch ? extractText(quoteTextMatch[1]) : ''; // 提取引用推文的媒体 const quoteMedia = []; const quoteMediaMatch = quoteHtml.match(/<div class="quote-media-container">([\s\S]*?)<\/div>\s*<\/div>/); if (quoteMediaMatch) { const quoteMediaHtml = quoteMediaMatch[1]; // 图片 const quoteImgRegex = /<a[^>]*class="still-image"[^>]*href="([^"]*)"[^>]*>/g; let quoteImgMatch; while ((quoteImgMatch = quoteImgRegex.exec(quoteMediaHtml)) !== null) { const url = decodeNitterUrl(quoteImgMatch[1], instance); quoteMedia.push({ type: 'image', url }); } // 视频 if (quoteMediaHtml.includes('gallery-video') || quoteMediaHtml.includes('video-container')) { const quotePosterMatch = quoteMediaHtml.match(/poster="([^"]*)"/); if (quotePosterMatch) { const thumbnail = decodeNitterUrl(quotePosterMatch[1], instance); quoteMedia.push({ type: 'video', url: '', thumbnail }); } } } quote = { username: quoteUsername, displayName: quoteDisplayName, content: quoteContent, link: quoteId ? `https://x.com/${quoteUsername}/status/${quoteId}` : `https://x.com/${quoteUsername}`, media: quoteMedia.length > 0 ? quoteMedia : undefined, }; } tweets.push({ id, username, displayName, avatar, content, contentHtml, publishedAt: publishedAt.toISOString(), link: `https://x.com/${username}/status/${id}`, media: media.length > 0 ? media : undefined, retweet, quote, stats, }); } catch (e) { console.error('[Parser] Failed to parse tweet:', e.message); } } return tweets; } /** * 从 HTML 中提取分页链接(加载更多) * Nitter 的分页链接格式通常是: /{username}?cursor=... 或 /{username}/more?cursor=... */ function extractNextPageUrl(html, username, instance) { // 查找"加载更多"或"Show more"链接 // 可能的格式: // 1. <a href="/{username}?cursor=...">Show more</a> // 2. <a href="/{username}/more?cursor=...">Show more</a> // 3. <div class="show-more"><a href="...">...</a></div> // 4. <a href="/{username}?cursor=..." class="show-more">...</a> // 先尝试在 show-more 区域内查找 const showMoreBlockMatch = html.match(/<div[^>]*class="[^"]*show-more[^"]*"[^>]*>([\s\S]*?)<\/div>/i); if (showMoreBlockMatch) { const showMoreBlock = showMoreBlockMatch[1]; const linkMatch = showMoreBlock.match(/<a[^>]*href="([^"]*)"[^>]*>/i); if (linkMatch && linkMatch[1]) { const href = linkMatch[1]; // 处理相对路径和绝对路径 if (href.startsWith('/')) { if (href.includes(username) || href.includes('cursor=')) { return `https://${instance}${href}`; } } else if (href.startsWith('http')) { // 已经是完整 URL if (href.includes(username) || href.includes('cursor=')) { return href; } } } } // 查找包含 "Show more" 文本的链接 const showMoreTextPatterns = [ /<a[^>]*href="([^"]*)"[^>]*>[\s\S]*?Show more/i, /<a[^>]*>[\s\S]*?Show more[\s\S]*?href="([^"]*)"/i, ]; for (const pattern of showMoreTextPatterns) { const match = html.match(pattern); if (match && match[1]) { const href = match[1]; if (href.startsWith('/')) { if (href.includes(username) || href.includes('cursor=')) { return `https://${instance}${href}`; } } else if (href.startsWith('http')) { if (href.includes(username) || href.includes('cursor=')) { return href; } } } } // 查找包含 cursor 参数的链接(通常在 timeline-footer 或 show-more 附近) const cursorPatterns = [ /href="(\/[^"]*\?cursor=[^"]*)"/i, /href="(\/[^"]*\/more\?cursor=[^"]*)"/i, ]; for (const pattern of cursorPatterns) { const matches = html.matchAll(new RegExp(pattern.source, 'gi')); for (const match of matches) { if (match[1]) { const href = match[1]; // 确保链接属于当前用户 if (href.includes(username) || href.startsWith(`/${username}`)) { return `https://${instance}${href}`; } } } } return null; } /** * 从 Nitter 实例获取用户页面(单页) */ async function fetchUserPageSingle(username, instance, cursor = null) { let url; if (cursor) { // 如果有 cursor,使用分页 URL url = cursor.startsWith('http') ? cursor : `https://${instance}/${username}${cursor.startsWith('?') ? cursor : `?cursor=${cursor}`}`; } else { url = `https://${instance}/${username}`; } const response = await fetchWithCurl(url); if (!response.ok) { return { ok: false, error: response.error }; } const html = await response.text(); // 验证是否为有效的用户页面 if (html.includes('timeline-item') && html.includes('tweet-content')) { return { ok: true, html, instance }; } // 检查是否为错误页面或 bot 检测 if (html.includes('error-panel') || html.includes('User not found')) { return { ok: false, error: 'user not found' }; } if (html.includes('Checking your browser') || html.includes('challenge-platform') || html.includes('not a bot')) { return { ok: false, error: 'bot detection' }; } return { ok: false, error: 'unexpected response' }; } /** * 获取单个用户的推文(支持多页) */ async function fetchUserTweets(username, maxPages = 5) { console.log(`\nFetching @${username}...`); const errors = []; let workingInstance = null; const allTweets = []; const seenTweetIds = new Set(); // 先找到一个可用的实例 for (const instance of NITTER_INSTANCES) { try { console.log(` [${instance}] Fetching page 1...`); let result = await fetchUserPageSingle(username, instance); if (!result.ok) { console.log(` [${instance}] Error: ${result.error}`); errors.push(`${instance}: ${result.error}`); continue; } workingInstance = instance; let currentPage = 1; // 解析第一页 const pageTweets = parseNitterHTML(result.html, instance, username); for (const tweet of pageTweets) { if (!seenTweetIds.has(tweet.id)) { allTweets.push(tweet); seenTweetIds.add(tweet.id); } } console.log(` [${instance}] Page ${currentPage}: ${pageTweets.length} tweets (total: ${allTweets.length})`); // 继续抓取后续页面 let nextPageUrl = extractNextPageUrl(result.html, username, instance); while (nextPageUrl && currentPage < maxPages) { currentPage++; console.log(` [${instance}] Fetching page ${currentPage}...`); // 等待一段时间,避免请求过快 await new Promise(resolve => setTimeout(resolve, 1500)); result = await fetchUserPageSingle(username, instance, nextPageUrl); if (!result.ok) { console.log(` [${instance}] Page ${currentPage} failed: ${result.error}`); break; } // 解析当前页的推文 const nextPageTweets = parseNitterHTML(result.html, instance, username); let newTweetsCount = 0; for (const tweet of nextPageTweets) { if (!seenTweetIds.has(tweet.id)) { allTweets.push(tweet); seenTweetIds.add(tweet.id); newTweetsCount++; } } console.log(` [${instance}] Page ${currentPage}: ${nextPageTweets.length} tweets (${newTweetsCount} new, total: ${allTweets.length})`); // 如果这一页没有新推文,可能已经到底了 if (newTweetsCount === 0 && nextPageTweets.length > 0) { console.log(` [${instance}] No new tweets on page ${currentPage}, stopping`); break; } // 查找下一页链接 nextPageUrl = extractNextPageUrl(result.html, username, instance); if (!nextPageUrl) { console.log(` [${instance}] No more pages`); break; } } console.log(` [${instance}] ✓ Success (${currentPage} page(s), ${allTweets.length} unique tweets)`); return allTweets; } catch (error) { const msg = error.message || 'Unknown error'; console.log(` [${instance}] Error: ${msg}`); errors.push(`${instance}: ${msg}`); } } console.error(` All instances failed: ${errors.join(', ')}`); return []; } /** * 主函数 */ async function main() { console.log('========================================'); console.log('Tweet Fetcher'); console.log('========================================'); console.log(`Time: ${new Date().toISOString()}`); console.log(`Users: ${FOLLOWERS.map(f => '@' + f.username).join(', ')}`); // 动态获取 Nitter 实例列表 NITTER_INSTANCES = await getNitterInstances(); console.log(`Instances: ${NITTER_INSTANCES.join(', ')}`); // 确保 data 目录存在 if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } // 读取现有数据(如果有) let existingTweets = []; if (fs.existsSync(TWEETS_FILE)) { try { const data = JSON.parse(fs.readFileSync(TWEETS_FILE, 'utf-8')); existingTweets = data.tweets || []; console.log(`\nExisting tweets: ${existingTweets.length}`); } catch (e) { console.log('\nNo existing data or invalid format'); } } // 抓取所有用户的推文 const allTweets = []; let successCount = 0; let failCount = 0; for (const follower of FOLLOWERS) { try { const tweets = await fetchUserTweets(follower.username, MAX_PAGES_PER_USER); if (tweets.length > 0) { allTweets.push(...tweets); successCount++; } else { failCount++; } } catch (error) { console.error(` Error fetching @${follower.username}:`, error.message); failCount++; } // 请求间隔,避免被限制 await new Promise(resolve => setTimeout(resolve, 2000)); } // 创建当前 followers 的用户名集合(用于过滤已删除的 followers 的推文) const currentFollowerUsernames = new Set(FOLLOWERS.map(f => f.username.toLowerCase())); // 合并新旧数据,去重 const tweetMap = new Map(); // 先添加旧数据(只保留当前 followers 的推文) for (const tweet of existingTweets) { // 只保留当前 followers 列表中的用户的推文 if (currentFollowerUsernames.has(tweet.username.toLowerCase())) { tweetMap.set(tweet.id, tweet); } } // 新数据覆盖旧数据 for (const tweet of allTweets) { tweetMap.set(tweet.id, tweet); } // 按时间排序 const mergedTweets = Array.from(tweetMap.values()) .sort((a, b) => new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime()) .slice(0, 500); // 最多保留 500 条 // 保存数据 const output = { lastUpdated: new Date().toISOString(), followers: FOLLOWERS, stats: { total: mergedTweets.length, newFetched: allTweets.length, successUsers: successCount, failedUsers: failCount, }, tweets: mergedTweets, }; fs.writeFileSync(TWEETS_FILE, JSON.stringify(output, null, 2)); console.log('\n========================================'); console.log('Summary'); console.log('========================================'); console.log(`Success: ${successCount}/${FOLLOWERS.length} users`); console.log(`New tweets: ${allTweets.length}`); console.log(`Total tweets: ${mergedTweets.length}`); console.log(`Saved to: ${TWEETS_FILE}`); // 如果没有成功获取任何推文,返回错误码 if (successCount === 0) { console.error('\nError: Failed to fetch any tweets!'); process.exit(1); } } main().catch(error => { console.error('Fatal error:', error); process.exit(1); });
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
scripts/manage-followers.mjs
JavaScript
#!/usr/bin/env node /** * 管理关注者列表脚本 * * 使用方式: * node scripts/manage-followers.mjs add <username> [group] * node scripts/manage-followers.mjs remove <username> * * 此脚本用于添加或删除关注者,更新 followers.txt 文件 */ import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '..'); const DATA_DIR = path.join(ROOT_DIR, 'data'); const FOLLOWERS_TXT_FILE = path.join(DATA_DIR, 'followers.txt'); /** * 读取现有的关注者列表 */ function readFollowers() { if (!fs.existsSync(FOLLOWERS_TXT_FILE)) { return { header: [], followers: [], comments: {}, }; } const content = fs.readFileSync(FOLLOWERS_TXT_FILE, 'utf-8'); const lines = content.split('\n'); const header = []; const followers = []; const comments = {}; let currentSection = null; let lineIndex = 0; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const trimmed = line.trim(); // 收集头部注释和空行 if (i < 20 && (trimmed.startsWith('#') || trimmed === '')) { header.push(line); continue; } // 处理分组注释 if (trimmed.startsWith('#') && trimmed.length > 1) { currentSection = trimmed.substring(1).trim(); header.push(line); continue; } // 跳过空行 if (trimmed === '') { header.push(line); continue; } // 解析关注者行 if (!trimmed.startsWith('#')) { const parts = trimmed.split(',').map(p => p.trim()); const username = parts[0]; if (username) { followers.push({ username: username.toLowerCase(), originalUsername: username, // 保留原始大小写 group: parts[1] || null, lineIndex: lineIndex++, }); // 记录分组注释 if (currentSection) { comments[username.toLowerCase()] = currentSection; } } } } return { header, followers, comments }; } /** * 写入关注者列表到文件 */ function writeFollowers(header, followers, comments) { // 确保 data 目录存在 if (!fs.existsSync(DATA_DIR)) { fs.mkdirSync(DATA_DIR, { recursive: true }); } const lines = [...header]; const groupedFollowers = {}; // 按分组组织关注者 followers.forEach(f => { const group = f.group || 'default'; if (!groupedFollowers[group]) { groupedFollowers[group] = []; } groupedFollowers[group].push(f); }); // 写入分组和关注者 const groups = Object.keys(groupedFollowers).sort(); groups.forEach(group => { const groupFollowers = groupedFollowers[group]; // 如果有分组注释,添加分组标题 if (group !== 'default' && groupFollowers.length > 0) { const groupComment = `# ${group}`; if (!lines.some(l => l.trim() === groupComment)) { if (lines.length > 0 && lines[lines.length - 1].trim() !== '') { lines.push(''); } lines.push(groupComment); } } // 写入该分组的关注者 groupFollowers.forEach(f => { if (f.group) { lines.push(`${f.originalUsername},${f.group}`); } else { lines.push(f.originalUsername); } }); }); // 确保文件末尾有换行 const content = lines.join('\n') + '\n'; fs.writeFileSync(FOLLOWERS_TXT_FILE, content, 'utf-8'); } /** * 添加关注者 */ function addFollower(username, group = null) { if (!username || typeof username !== 'string') { throw new Error('Username is required'); } const usernameLower = username.toLowerCase().trim(); const { header, followers, comments } = readFollowers(); // 检查是否已存在 const existing = followers.find(f => f.username === usernameLower); if (existing) { // 如果提供了分组且不同,更新分组 if (group && existing.group !== group) { existing.group = group; console.log(`✅ Updated @${username} group to "${group}"`); } else { console.log(`⚠️ @${username} already exists in the list`); return false; } } else { // 添加新关注者 followers.push({ username: usernameLower, originalUsername: username.trim(), group: group || null, lineIndex: followers.length, }); console.log(`✅ Added @${username}${group ? ` to group "${group}"` : ''}`); } writeFollowers(header, followers, comments); return true; } /** * 删除关注者 */ function removeFollower(username) { if (!username || typeof username !== 'string') { throw new Error('Username is required'); } const usernameLower = username.toLowerCase().trim(); const { header, followers, comments } = readFollowers(); const index = followers.findIndex(f => f.username === usernameLower); if (index === -1) { console.log(`⚠️ @${username} not found in the list`); return false; } followers.splice(index, 1); console.log(`✅ Removed @${username} from the list`); writeFollowers(header, followers, comments); return true; } /** * 主函数 */ function main() { const args = process.argv.slice(2); if (args.length < 2) { console.error('Usage:'); console.error(' node scripts/manage-followers.mjs add <username> [group]'); console.error(' node scripts/manage-followers.mjs remove <username>'); process.exit(1); } const action = args[0].toLowerCase(); const username = args[1]; const group = args[2] || null; try { let changed = false; if (action === 'add') { changed = addFollower(username, group); } else if (action === 'remove') { changed = removeFollower(username); } else { console.error(`❌ Unknown action: ${action}`); console.error('Supported actions: add, remove'); process.exit(1); } if (changed) { console.log(`\n✅ Successfully updated ${FOLLOWERS_TXT_FILE}`); } } catch (error) { console.error(`❌ Error: ${error.message}`); process.exit(1); } } main();
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
scripts/validate-followers.mjs
JavaScript
#!/usr/bin/env node /** * 验证关注者列表 JSON 文件格式 * * 使用方式: * node scripts/validate-followers.mjs */ import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '..'); const FOLLOWERS_TXT_FILE = path.join(ROOT_DIR, 'data', 'followers.txt'); const FOLLOWERS_JSON_FILE = path.join(ROOT_DIR, 'data', 'followers.json'); function parseTextFile() { if (!fs.existsSync(FOLLOWERS_TXT_FILE)) { return null; } const content = fs.readFileSync(FOLLOWERS_TXT_FILE, 'utf-8'); const lines = content.split('\n'); const followers = []; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); // 跳过空行和注释 if (!line || line.startsWith('#')) { continue; } // 解析行:支持 username 或 username,group // displayName 会从推文数据中自动获取,不需要在配置中指定 const parts = line.split(',').map(p => p.trim()); const username = parts[0]; if (!username) { continue; } const follower = { username: username, }; // 可选字段:分组(第二个参数是 group,不再是 displayName) if (parts[1]) { follower.group = parts[1]; } followers.push(follower); } return followers.length > 0 ? followers : null; } function parseJsonFile() { if (!fs.existsSync(FOLLOWERS_JSON_FILE)) { return null; } const data = JSON.parse(fs.readFileSync(FOLLOWERS_JSON_FILE, 'utf-8')); if (!data.followers || !Array.isArray(data.followers)) { return null; } return data.followers; } function validateFollowers() { console.log('Validating followers configuration...\n'); // 优先使用文本格式 let followers = parseTextFile(); const sourceFile = followers ? FOLLOWERS_TXT_FILE : FOLLOWERS_JSON_FILE; const sourceType = followers ? 'text' : 'JSON'; // 如果文本格式不存在,尝试 JSON 格式(向后兼容) if (!followers) { try { followers = parseJsonFile(); } catch (error) { console.error(`❌ Error: Invalid JSON format in ${FOLLOWERS_JSON_FILE}`); console.error(` ${error.message}`); process.exit(1); } } // 检查文件是否存在 if (!followers || followers.length === 0) { console.error(`❌ Error: No followers found!`); console.error(`\nPlease create ${FOLLOWERS_TXT_FILE} with the following format:`); console.error(''); console.error('# 每行一个用户名'); console.error('elonmusk,Elon Musk,Tech'); console.error('jack,Jack Dorsey,Tech'); console.error('# 或者简单格式'); console.error('naval'); console.error('VitalikButerin'); process.exit(1); } // 验证每个关注者 const errors = []; const usernames = new Set(); followers.forEach((follower, index) => { if (!follower.username) { errors.push(`Follower at index ${index}: missing "username"`); return; } if (typeof follower.username !== 'string' || follower.username.trim() === '') { errors.push(`Follower at index ${index}: invalid "username"`); return; } // 检查重复用户名 const username = follower.username.toLowerCase(); if (usernames.has(username)) { errors.push(`Duplicate username: ${follower.username}`); } usernames.add(username); // 验证可选字段 if (follower.displayName && typeof follower.displayName !== 'string') { errors.push(`Follower "${follower.username}": "displayName" must be a string`); } if (follower.group && typeof follower.group !== 'string') { errors.push(`Follower "${follower.username}": "group" must be a string`); } }); if (errors.length > 0) { console.error('❌ Validation errors:'); errors.forEach(error => console.error(` - ${error}`)); process.exit(1); } // 成功 console.log(`✅ ${sourceFile} is valid! (${sourceType} format)`); console.log(`\n Total followers: ${followers.length}`); const groups = [...new Set(followers.map(f => f.group).filter(Boolean))]; console.log(` Groups: ${groups.length > 0 ? groups.join(', ') : 'None'}`); console.log(`\n Followers:`); followers.forEach(f => { const group = f.group ? ` [${f.group}]` : ''; console.log(` - @${f.username}${group}`); }); console.log(`\n Note: displayName will be automatically fetched from tweet data`); } validateFollowers();
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/App.tsx
TypeScript (TSX)
import { useCallback, useMemo } from 'react' import { Header } from './components/Header' import { Timeline } from './components/Timeline' import { FollowerList } from './components/FollowerList' import { ScrollToTop } from './components/ScrollToTop' import { useTweets } from './hooks/useTweets' import { useLocalStorage } from './hooks/useLocalStorage' import { useScrollDirection } from './hooks/useScrollDirection' import { followers } from './config/followers' import { clsx } from 'clsx' export function App() { const [selectedUsers, setSelectedUsers] = useLocalStorage<string[]>( 'selectedUsers', [] ) const { tweets, lastUpdated, isLoading } = useTweets() const { scrollDirection, isAtTop } = useScrollDirection() const shouldShowFollowerList = isAtTop || scrollDirection === 'up' const handleToggleUser = useCallback( (username: string) => { if (!username) { setSelectedUsers([]) return } setSelectedUsers(prev => { if (prev.includes(username)) { return prev.filter(u => u !== username) } return [...prev, username] }) }, [setSelectedUsers] ) // 过滤推文 const filteredTweets = useMemo(() => { if (selectedUsers.length === 0) { return tweets } const lowercaseSelected = selectedUsers.map(u => u.toLowerCase()) return tweets.filter(tweet => lowercaseSelected.includes(tweet.username.toLowerCase()) ) }, [tweets, selectedUsers]) return ( <div className="min-h-screen bg-[var(--background)]"> <Header /> {/* Left Sidebar - Fixed on desktop */} <aside className="hidden lg:block fixed top-16 left-0 w-64 h-[calc(100vh-4rem)] border-r border-[var(--border)] bg-[var(--background)] overflow-y-auto z-10"> <div className="p-4"> <FollowerList followers={followers} selectedUsers={selectedUsers} onToggleUser={handleToggleUser} tweets={tweets} /> </div> </aside> {/* Main Content */} <main className="pt-16 lg:pl-64"> <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8"> {/* Mobile Follower filter - Fixed with scroll hide */} <div className={clsx( 'lg:hidden fixed left-0 right-0 z-10 bg-[var(--background)]/95 backdrop-blur-md px-3 sm:px-4 pt-2 pb-1.5 border-b border-[var(--border)] transition-transform duration-300 ease-in-out', shouldShowFollowerList ? 'translate-y-0 top-16' : '-translate-y-full top-16' )} > <FollowerList followers={followers} selectedUsers={selectedUsers} onToggleUser={handleToggleUser} tweets={tweets} /> </div> {/* Content with mobile top spacing */} <div className="lg:pt-4 pt-4 pb-8"> {/* Timeline */} <Timeline tweets={filteredTweets} lastUpdated={lastUpdated} isLoading={isLoading} /> {/* Footer */} <footer className="border-t border-[var(--border)] mt-8 mb-8 pt-8"> <div className="text-center"> <p className="text-sm text-[var(--muted-foreground)] mb-2"> 一个简洁优雅的 X 时间线聚合器 </p> <p className="text-xs text-[var(--muted-foreground)]"> 数据来源于{' '} <a href="https://github.com/zedeus/nitter" target="_blank" rel="noopener noreferrer" className="text-[var(--accent)] hover:underline transition-colors" > Nitter </a>{' '} 公开实例 </p> </div> </footer> </div> </div> </main> {/* Scroll to top button */} <ScrollToTop /> </div> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/Avatar.tsx
TypeScript (TSX)
import { clsx } from 'clsx' interface AvatarProps { src?: string alt: string size?: 'sm' | 'md' | 'lg' className?: string } const sizeMap = { sm: 32, md: 48, lg: 64, } const defaultAvatar = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png' export function Avatar({ src, alt, size = 'md', className }: AvatarProps) { const dimension = sizeMap[size] const imageSrc = src || defaultAvatar return ( <div className={clsx( 'relative rounded-full overflow-hidden bg-[var(--muted)] avatar-hover flex-shrink-0', className )} style={{ width: dimension, height: dimension, minWidth: dimension, minHeight: dimension, }} > <img src={imageSrc} alt={alt} width={dimension} height={dimension} className="object-cover w-full h-full block" loading="lazy" onError={e => { // Fallback to default avatar if image fails to load const target = e.target as HTMLImageElement if (target.src !== defaultAvatar) { target.src = defaultAvatar } }} /> </div> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/Button.tsx
TypeScript (TSX)
import { clsx } from 'clsx' import { Loader2 } from 'lucide-react' import type { ButtonHTMLAttributes, ReactNode } from 'react' interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> { variant?: 'primary' | 'secondary' | 'ghost' size?: 'sm' | 'md' | 'lg' loading?: boolean children: ReactNode } export function Button({ variant = 'primary', size = 'md', loading = false, children, className, disabled, ...props }: ButtonProps) { return ( <button className={clsx( 'inline-flex items-center justify-center rounded-full font-medium transition-colors', 'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--accent)]', 'disabled:opacity-50 disabled:cursor-not-allowed', { 'bg-[var(--accent)] text-white hover:bg-[var(--accent)]/90': variant === 'primary', 'bg-[var(--muted)] text-[var(--foreground)] hover:bg-[var(--border)]': variant === 'secondary', 'bg-transparent hover:bg-[var(--muted)]': variant === 'ghost', 'px-3 py-1.5 text-sm': size === 'sm', 'px-4 py-2 text-base': size === 'md', 'px-6 py-3 text-lg': size === 'lg', }, className )} disabled={disabled || loading} {...props} > {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} {children} </button> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/FollowerList.tsx
TypeScript (TSX)
import { useMemo } from 'react' import { clsx } from 'clsx' import { Avatar } from './Avatar' import type { Follower, Tweet } from '../types' interface FollowerListProps { followers: Follower[] selectedUsers: string[] onToggleUser: (username: string) => void tweets?: Tweet[] } export function FollowerList({ followers, selectedUsers, onToggleUser, tweets = [], }: FollowerListProps) { const isAllSelected = selectedUsers.length === 0 // 从推文数据中提取每个关注者的最新头像和显示名称 const followerData = useMemo(() => { const avatarMap = new Map<string, string>() const displayNameMap = new Map<string, string>() // 按时间排序推文(最新的在前),为每个用户名记录最新的头像和显示名称 const sortedTweets = [...tweets].sort((a, b) => { const dateA = typeof a.publishedAt === 'string' ? new Date(a.publishedAt) : a.publishedAt const dateB = typeof b.publishedAt === 'string' ? new Date(b.publishedAt) : b.publishedAt return dateB.getTime() - dateA.getTime() }) // 遍历推文,为每个用户名记录最新的头像和显示名称 for (const tweet of sortedTweets) { const username = tweet.username.toLowerCase() if (!avatarMap.has(username) && tweet.avatar) { avatarMap.set(username, tweet.avatar) } if (!displayNameMap.has(username) && tweet.displayName) { displayNameMap.set(username, tweet.displayName) } } return { avatarMap, displayNameMap } }, [tweets]) // 获取关注者的头像,优先使用推文中的头像 const getFollowerAvatar = (follower: Follower): string | undefined => { if (follower.avatar) { return follower.avatar } return followerData.avatarMap.get(follower.username.toLowerCase()) } // 获取关注者的显示名称,优先使用配置中的,否则从推文中获取 const getFollowerDisplayName = (follower: Follower): string => { if (follower.displayName) { return follower.displayName } return ( followerData.displayNameMap.get(follower.username.toLowerCase()) || follower.username ) } return ( <div> {/* Desktop: Title */} <h3 className="hidden lg:block text-sm font-semibold text-[var(--muted-foreground)] mb-4 uppercase tracking-wide lg:mb-6"> 关注者 </h3> {/* Desktop: Vertical layout */} <div className="hidden lg:flex flex-col gap-2"> {/* All button */} <button onClick={() => onToggleUser('')} className={clsx( 'flex items-center gap-3 p-3 rounded-xl transition-all duration-150 text-left w-full', isAllSelected ? 'bg-[var(--accent)]/10 text-[var(--accent)]' : 'hover:bg-[var(--muted)] text-[var(--muted-foreground)]' )} > <div className={clsx( 'w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all duration-150 flex-shrink-0', isAllSelected ? 'bg-[var(--accent)] text-white shadow-sm' : 'bg-[var(--muted)] text-[var(--muted-foreground)]' )} > 全 </div> <span className="text-sm font-medium">全部</span> {isAllSelected && ( <span className="ml-auto text-xs text-[var(--accent)]"> {followers.length} </span> )} </button> {/* User avatars */} {followers.map(follower => { const isSelected = selectedUsers.includes(follower.username) return ( <button key={follower.username} onClick={() => onToggleUser(follower.username)} className={clsx( 'flex items-center gap-3 p-3 rounded-xl transition-all duration-150 text-left w-full', isSelected ? 'bg-[var(--accent)]/10' : 'hover:bg-[var(--muted)]' )} > <div className={clsx( 'rounded-full transition-all duration-150 flex-shrink-0', isSelected && 'ring-2 ring-[var(--accent)] ring-offset-2 ring-offset-[var(--background)] shadow-sm' )} > <Avatar src={getFollowerAvatar(follower)} alt={follower.displayName || follower.username} size="md" /> </div> <div className="flex-1 min-w-0"> <div className="text-sm font-medium truncate"> {getFollowerDisplayName(follower)} </div> <div className="text-xs text-[var(--muted-foreground)] truncate"> @{follower.username} </div> </div> {isSelected && ( <span className="text-xs text-[var(--accent)] flex-shrink-0 font-semibold"> ✓ </span> )} </button> ) })} </div> {/* Mobile: Compact horizontal scroll layout */} <div className="flex gap-1.5 overflow-x-auto scrollbar-hide pb-2 -mx-2 px-2 lg:hidden snap-x snap-mandatory"> {/* All button */} <button onClick={() => onToggleUser('')} className={clsx( 'flex flex-col items-center gap-1 min-w-[52px] p-1.5 rounded-lg transition-all duration-150 flex-shrink-0 snap-start active:scale-95', isAllSelected ? 'bg-[var(--accent)]/10 text-[var(--accent)]' : 'hover:bg-[var(--muted)] active:bg-[var(--muted)] text-[var(--muted-foreground)]' )} > <div className={clsx( 'w-9 h-9 rounded-full flex items-center justify-center text-xs font-semibold transition-all duration-150 flex-shrink-0', isAllSelected ? 'bg-[var(--accent)] text-white shadow-sm' : 'bg-[var(--muted)] text-[var(--muted-foreground)]' )} > 全 </div> <span className="text-[9px] font-medium truncate w-full text-center leading-tight"> 全部 </span> </button> {/* User avatars */} {followers.map(follower => { const isSelected = selectedUsers.includes(follower.username) return ( <button key={follower.username} onClick={() => onToggleUser(follower.username)} className={clsx( 'flex flex-col items-center gap-1 min-w-[52px] p-1.5 rounded-lg transition-all duration-150 flex-shrink-0 snap-start active:scale-95', isSelected ? 'bg-[var(--accent)]/10' : 'hover:bg-[var(--muted)] active:bg-[var(--muted)]' )} > <div className={clsx( 'flex-shrink-0 transition-all duration-150 inline-flex items-center justify-center', isSelected && 'ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--background)] shadow-sm rounded-full' )} > <Avatar src={getFollowerAvatar(follower)} alt={follower.displayName || follower.username} size="sm" /> </div> <span className="text-[9px] font-medium truncate max-w-[52px] text-center leading-tight"> {getFollowerDisplayName(follower)} </span> {isSelected && ( <span className="text-[8px] text-[var(--accent)] font-bold mt-[-2px]"> ✓ </span> )} </button> ) })} </div> </div> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/Header.tsx
TypeScript (TSX)
import { Github } from 'lucide-react' import { Logo } from './Logo' import { ThemeToggle } from './ThemeToggle' import { useScrollDirection } from '../hooks/useScrollDirection' import { clsx } from 'clsx' export function Header() { const { scrollDirection, isAtTop } = useScrollDirection() const shouldShow = isAtTop || scrollDirection === 'up' return ( <header className={clsx( 'fixed top-0 left-0 right-0 z-20 bg-[var(--background)]/95 backdrop-blur-md border-b border-[var(--border)] shadow-sm h-16 transition-transform duration-300 ease-in-out', // 移动端:向下滚动时隐藏,向上滚动或顶部时显示 shouldShow ? 'translate-y-0' : '-translate-y-full lg:translate-y-0' )} > <div className="w-full px-4 sm:px-6 lg:px-8 h-full flex items-center justify-between"> <a href="/" className="flex items-center gap-2.5 font-bold text-xl text-[var(--foreground)] hover:opacity-80 transition-opacity" > <Logo size={24} /> </a> <div className="flex items-center gap-3"> <ThemeToggle /> <a href="https://github.com/xwartz/x-line" target="_blank" rel="noopener noreferrer" className="p-2 rounded-lg hover:bg-[var(--muted)] transition-colors duration-150" title="GitHub" > <Github className="w-5 h-5 text-[var(--foreground)]" /> </a> </div> </div> </header> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/Logo.tsx
TypeScript (TSX)
import { clsx } from 'clsx' interface LogoProps { className?: string size?: number } export function Logo({ className, size = 24 }: LogoProps) { return ( <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 64 64" fill="none" className={clsx('text-[var(--accent)]', className)} > {/* 极简X字母 */} <path d="M22 22 L42 42 M42 22 L22 42" stroke="currentColor" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" /> {/* 流动箭头 */} <path d="M46 20 L52 26 L46 32" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" fill="none" opacity="0.7" /> {/* 辅助流线 */} <path d="M48 16 L54 22" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity="0.4" /> <path d="M48 36 L54 42" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity="0.4" /> </svg> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/ScrollToTop.tsx
TypeScript (TSX)
import { useState, useEffect } from 'react' import { ArrowUp } from 'lucide-react' export function ScrollToTop() { const [isVisible, setIsVisible] = useState(false) useEffect(() => { const toggleVisibility = () => { // Check window scroll position if (window.scrollY > 400) { setIsVisible(true) } else { setIsVisible(false) } } // Listen to window scroll window.addEventListener('scroll', toggleVisibility, { passive: true }) // Initial check toggleVisibility() return () => { window.removeEventListener('scroll', toggleVisibility) } }, []) const scrollToTop = () => { window.scrollTo({ top: 0, behavior: 'smooth', }) } if (!isVisible) { return null } return ( <button onClick={scrollToTop} className="fixed bottom-8 right-8 z-50 p-3 bg-[var(--accent)] text-white rounded-full shadow-lg hover:bg-[var(--accent)]/90 transition-all duration-200 hover:scale-110 active:scale-95 focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2" aria-label="滚动到顶部" > <ArrowUp className="w-5 h-5" /> </button> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/ThemeProvider.tsx
TypeScript (TSX)
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode, } from 'react' import { useLocalStorage } from '../hooks/useLocalStorage' type Theme = 'light' | 'dark' | 'system' interface ThemeContextType { theme: Theme setTheme: (theme: Theme) => void resolvedTheme: 'light' | 'dark' } const ThemeContext = createContext<ThemeContextType | undefined>(undefined) export function ThemeProvider({ children }: { children: ReactNode }) { const [theme, setTheme] = useLocalStorage<Theme>('theme', 'system') const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(() => typeof window !== 'undefined' ? window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' : 'light' ) const resolvedTheme = useMemo(() => { if (theme === 'system') { return systemTheme } return theme }, [theme, systemTheme]) // 立即应用主题,确保与内联脚本一致 useEffect(() => { const shouldBeDark = resolvedTheme === 'dark' const hasDarkClass = document.documentElement.classList.contains('dark') if (shouldBeDark && !hasDarkClass) { document.documentElement.classList.add('dark') } else if (!shouldBeDark && hasDarkClass) { document.documentElement.classList.remove('dark') } }, [resolvedTheme]) useEffect(() => { if (theme !== 'system') { return } const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)') const handleChange = () => { const newResolved = mediaQuery.matches ? 'dark' : 'light' setSystemTheme(newResolved) } mediaQuery.addEventListener('change', handleChange) return () => mediaQuery.removeEventListener('change', handleChange) }, [theme]) return ( <ThemeContext.Provider value={{ theme, setTheme, resolvedTheme }}> {children} </ThemeContext.Provider> ) } export function useTheme() { const context = useContext(ThemeContext) if (context === undefined) { throw new Error('useTheme must be used within a ThemeProvider') } return context }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/ThemeToggle.tsx
TypeScript (TSX)
import { Moon, Sun, Monitor } from 'lucide-react' import { useTheme } from './ThemeProvider' export function ThemeToggle() { const { theme, setTheme } = useTheme() const cycleTheme = () => { const themes: Array<'light' | 'dark' | 'system'> = [ 'light', 'dark', 'system', ] const currentIndex = themes.indexOf(theme) const nextIndex = (currentIndex + 1) % themes.length setTheme(themes[nextIndex]) } return ( <button onClick={cycleTheme} className="p-2 rounded-full hover:bg-[var(--muted)] transition-colors" aria-label={`Current theme: ${theme}`} title={`Theme: ${theme}`} > {theme === 'light' && <Sun className="w-5 h-5" />} {theme === 'dark' && <Moon className="w-5 h-5" />} {theme === 'system' && <Monitor className="w-5 h-5" />} </button> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/Timeline.tsx
TypeScript (TSX)
import { formatDistanceToNow } from 'date-fns' import { zhCN } from 'date-fns/locale' import { MessageSquare } from 'lucide-react' import { TweetCard } from './TweetCard' import { TimelineSkeleton } from './TweetSkeleton' import type { Tweet } from '../types' interface TimelineProps { tweets: Tweet[] lastUpdated: Date | null isLoading: boolean } export function Timeline({ tweets, lastUpdated, isLoading }: TimelineProps) { return ( <div className="w-full"> {/* Header */} <div className="mb-6 pb-4 border-b border-[var(--border)]"> <div className="flex items-center justify-between flex-wrap gap-2"> <h3 className="text-lg font-bold text-[var(--foreground)]">时间线</h3> {lastUpdated && ( <span className="text-sm text-[var(--muted-foreground)]"> 更新于{' '} {formatDistanceToNow(lastUpdated, { addSuffix: true, locale: zhCN, })} </span> )} </div> </div> {/* Content */} <div> {isLoading ? ( <TimelineSkeleton count={10} /> ) : tweets.length === 0 ? ( <div className="py-24 px-4 text-center"> <div className="flex flex-col items-center gap-4"> <div className="w-16 h-16 rounded-full bg-[var(--muted)] flex items-center justify-center"> <MessageSquare className="w-8 h-8 text-[var(--muted-foreground)]" /> </div> <div> <h3 className="text-lg font-semibold text-[var(--foreground)] mb-2"> 暂无推文 </h3> <p className="text-[var(--muted-foreground)] text-sm leading-6 max-w-md mx-auto"> 请运行脚本获取数据 </p> </div> </div> </div> ) : ( <> <div className="space-y-0"> {tweets.map(tweet => ( <TweetCard key={tweet.id} tweet={tweet} /> ))} </div> <div className="py-8 text-center"> <p className="text-xs text-[var(--muted-foreground)]"> 已显示 {tweets.length} 条推文 </p> </div> </> )} </div> </div> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/TweetCard.tsx
TypeScript (TSX)
import { formatDistanceToNow, format } from 'date-fns' import { zhCN } from 'date-fns/locale' import { Repeat2 } from 'lucide-react' import { Avatar } from './Avatar' import type { Tweet } from '../types' interface TweetCardProps { tweet: Tweet } export function TweetCard({ tweet }: TweetCardProps) { const publishedDate = new Date(tweet.publishedAt) const timeAgo = formatDistanceToNow(publishedDate, { addSuffix: true, locale: zhCN, }) // 格式化具体时间:年-月-日 时:分:秒 +时区 const formattedTime = format(publishedDate, 'yyyy-MM-dd HH:mm:ss XX') return ( <article className="px-3 py-4 sm:px-4 sm:py-6 lg:px-6 border-b border-[var(--border)] card-hover animate-fade-in transition-colors duration-150"> {/* Retweet indicator */} {tweet.retweet && ( <div className="flex items-center gap-2 mb-2 sm:mb-3 ml-10 sm:ml-14 text-xs text-[var(--muted-foreground)]"> <Repeat2 className="w-3.5 h-3.5" /> <span>{tweet.retweet.displayName} 转推了</span> </div> )} <div className="flex gap-3 sm:gap-4"> {/* Avatar */} <a href={`https://x.com/${tweet.username}`} target="_blank" rel="noopener noreferrer" className="flex-shrink-0" > <Avatar src={tweet.avatar} alt={tweet.displayName} size="sm" className="sm:hidden" /> <Avatar src={tweet.avatar} alt={tweet.displayName} size="md" className="hidden sm:block" /> </a> <div className="flex-1 min-w-0"> {/* Header */} <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap mb-1.5 sm:mb-2"> <a href={`https://x.com/${tweet.username}`} target="_blank" rel="noopener noreferrer" className="font-semibold text-[var(--foreground)] hover:underline truncate text-sm sm:text-base leading-5" > {tweet.displayName} </a> <span className="text-[var(--muted-foreground)] text-xs sm:text-sm leading-5"> @{tweet.username} </span> <span className="text-[var(--muted-foreground)] text-xs sm:text-sm leading-5 hidden sm:inline"> · </span> <a href={tweet.link} target="_blank" rel="noopener noreferrer" className="text-[var(--muted-foreground)] hover:text-[var(--accent)] text-xs sm:text-sm leading-5 transition-colors" title={timeAgo} > {formattedTime} </a> </div> {/* Content */} <div className="mt-1.5 sm:mt-2 mb-2 sm:mb-3 tweet-content text-[var(--foreground)] text-sm sm:text-[15px] leading-5 sm:leading-6"> {tweet.content} </div> {/* Media */} {tweet.media && tweet.media.length > 0 && ( <div className="mt-3 sm:mt-4 rounded-xl sm:rounded-2xl overflow-hidden border border-[var(--border)] bg-[var(--muted)]"> <div className={`grid gap-0.5 sm:gap-1 ${ tweet.media.length === 1 ? 'grid-cols-1' : tweet.media.length === 2 ? 'grid-cols-2' : 'grid-cols-2' }`} > {tweet.media.slice(0, 4).map((media, index) => ( <a key={index} href={tweet.link} target="_blank" rel="noopener noreferrer" className={`relative block overflow-hidden ${ tweet.media!.length === 3 && index === 0 ? 'row-span-2' : '' }`} > <img src={media.thumbnail || media.url} alt={media.alt || 'Tweet media'} className="w-full h-full object-cover hover:opacity-95 transition-opacity duration-200" style={{ maxHeight: tweet.media!.length === 1 ? '400px' : '180px', }} loading="lazy" /> {(media.type === 'video' || media.type === 'gif') && ( <div className="absolute inset-0 flex items-center justify-center bg-black/20"> <div className="bg-black/60 backdrop-blur-sm rounded-full px-3 py-1.5 sm:px-4 sm:py-2"> <span className="text-white text-[10px] sm:text-xs font-medium"> {media.type === 'video' ? '▶ Video' : 'GIF'} </span> </div> </div> )} </a> ))} </div> </div> )} {/* Quote tweet */} {tweet.quote && ( <a href={tweet.quote.link} target="_blank" rel="noopener noreferrer" className="mt-3 sm:mt-4 block p-3 sm:p-4 border border-[var(--border)] rounded-xl sm:rounded-2xl hover:bg-[var(--muted)] transition-colors duration-150" > <div className="flex items-center gap-1.5 sm:gap-2 mb-1.5 sm:mb-2"> <span className="font-semibold text-xs sm:text-sm text-[var(--foreground)]"> {tweet.quote.displayName} </span> <span className="text-[var(--muted-foreground)] text-xs sm:text-sm"> @{tweet.quote.username} </span> </div> {tweet.quote.content && ( <p className="text-xs sm:text-sm text-[var(--foreground)] leading-4 sm:leading-5 line-clamp-3"> {tweet.quote.content} </p> )} {/* Quote tweet media */} {tweet.quote.media && tweet.quote.media.length > 0 && ( <div className="mt-2 sm:mt-3 rounded-lg sm:rounded-xl overflow-hidden border border-[var(--border)] bg-[var(--muted)]"> <div className={`grid gap-0.5 sm:gap-1 ${ tweet.quote.media.length === 1 ? 'grid-cols-1' : tweet.quote.media.length === 2 ? 'grid-cols-2' : tweet.quote.media.length === 3 ? 'grid-cols-2' : 'grid-cols-2' }`} > {tweet.quote.media.map((media, i) => ( <a key={i} href={tweet.quote!.link} target="_blank" rel="noopener noreferrer" className={`relative block overflow-hidden ${ tweet.quote!.media!.length === 3 && i === 0 ? 'row-span-2' : '' }`} style={{ maxHeight: tweet.quote!.media!.length === 1 ? '250px' : '120px', }} > <img src={media.thumbnail || media.url} alt={media.alt || ''} className="w-full h-full object-cover hover:opacity-95 transition-opacity duration-200" style={{ maxHeight: tweet.quote!.media!.length === 1 ? '250px' : '120px', }} loading="lazy" /> {(media.type === 'video' || media.type === 'gif') && ( <div className="absolute inset-0 flex items-center justify-center bg-black/20"> <div className="bg-black/60 backdrop-blur-sm rounded-full px-2 py-1 sm:px-3 sm:py-1.5"> <span className="text-white text-[10px] sm:text-xs font-medium"> {media.type === 'video' ? '▶' : 'GIF'} </span> </div> </div> )} </a> ))} </div> </div> )} </a> )} </div> </div> </article> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/components/TweetSkeleton.tsx
TypeScript (TSX)
export function TweetSkeleton() { return ( <div className="px-4 py-6 sm:px-6 border-b border-[var(--border)] animate-pulse"> <div className="flex gap-4"> {/* Avatar skeleton */} <div className="w-12 h-12 rounded-full skeleton flex-shrink-0" /> <div className="flex-1 space-y-3"> {/* Header skeleton */} <div className="flex items-center gap-2 flex-wrap"> <div className="h-5 w-24 skeleton rounded" /> <div className="h-5 w-20 skeleton rounded" /> <div className="h-5 w-16 skeleton rounded" /> </div> {/* Content skeleton */} <div className="space-y-2"> <div className="h-4 w-full skeleton rounded" /> <div className="h-4 w-full skeleton rounded" /> <div className="h-4 w-3/4 skeleton rounded" /> </div> {/* Media skeleton (optional) */} <div className="h-48 w-full skeleton rounded-2xl" /> {/* Actions skeleton */} <div className="flex items-center gap-8 mt-4"> <div className="h-4 w-12 skeleton rounded" /> <div className="h-4 w-12 skeleton rounded" /> <div className="h-4 w-12 skeleton rounded" /> </div> </div> </div> </div> ) } export function TimelineSkeleton({ count = 5 }: { count?: number }) { return ( <div className="divide-y divide-[var(--border)]"> {Array.from({ length: count }).map((_, i) => ( <TweetSkeleton key={i} /> ))} </div> ) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/config/followers.ts
TypeScript
import type { Follower } from '../types' import followersData from '../../data/followers.json' /** * 关注者列表配置 * * 数据源: data/followers.json * 可以直接在 GitHub Web UI 编辑此文件来更新关注者列表 */ export const followers: Follower[] = followersData.followers /** * 获取所有关注者用户名 */ export function getFollowerUsernames(): string[] { return followers.map(f => f.username) }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/hooks/useLocalStorage.ts
TypeScript
import { useState, useEffect, useCallback } from 'react' /** * 通用的本地存储 Hook * @param key 存储键名 * @param initialValue 初始值 * @returns [storedValue, setValue, removeValue] 存储的值、设置函数、删除函数 */ export function useLocalStorage<T>( key: string, initialValue: T ): [T, (value: T | ((val: T) => T)) => void, () => void] { // 状态初始化函数,只在首次渲染时执行 const [storedValue, setStoredValue] = useState<T>(() => { if (typeof window === 'undefined') { return initialValue } try { const item = window.localStorage.getItem(key) return item ? (JSON.parse(item) as T) : initialValue } catch (error) { console.error(`Error reading localStorage key "${key}":`, error) return initialValue } }) // 设置值的函数 const setValue = useCallback( (value: T | ((val: T) => T)) => { try { // 支持函数式更新 const valueToStore = value instanceof Function ? value(storedValue) : value setStoredValue(valueToStore) if (typeof window !== 'undefined') { window.localStorage.setItem(key, JSON.stringify(valueToStore)) } } catch (error) { console.error(`Error setting localStorage key "${key}":`, error) } }, [key, storedValue] ) // 删除值的函数 const removeValue = useCallback(() => { try { setStoredValue(initialValue) if (typeof window !== 'undefined') { window.localStorage.removeItem(key) } } catch (error) { console.error(`Error removing localStorage key "${key}":`, error) } }, [key, initialValue]) // 监听 localStorage 变化(用于多标签页同步) useEffect(() => { if (typeof window === 'undefined') { return } const handleStorageChange = (e: StorageEvent) => { if (e.key === key && e.newValue !== null) { try { setStoredValue(JSON.parse(e.newValue) as T) } catch (error) { console.error( `Error parsing localStorage value for key "${key}":`, error ) } } } window.addEventListener('storage', handleStorageChange) return () => window.removeEventListener('storage', handleStorageChange) }, [key]) return [storedValue, setValue, removeValue] }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/hooks/useScrollDirection.ts
TypeScript
import { useState, useEffect } from 'react' interface UseScrollDirectionOptions { threshold?: number initialDirection?: 'up' | 'down' } export function useScrollDirection(options: UseScrollDirectionOptions = {}) { const { threshold = 10, initialDirection = 'up' } = options const [scrollDirection, setScrollDirection] = useState<'up' | 'down'>( initialDirection ) const [isAtTop, setIsAtTop] = useState(true) useEffect(() => { let lastScrollY = window.scrollY let ticking = false const updateScrollDirection = () => { const scrollY = window.scrollY // 检查是否在顶部 setIsAtTop(scrollY < threshold) // 计算滚动方向 const direction = scrollY > lastScrollY ? 'down' : 'up' if ( direction !== scrollDirection && Math.abs(scrollY - lastScrollY) > threshold ) { setScrollDirection(direction) } lastScrollY = scrollY > 0 ? scrollY : 0 ticking = false } const onScroll = () => { if (!ticking) { window.requestAnimationFrame(updateScrollDirection) ticking = true } } window.addEventListener('scroll', onScroll, { passive: true }) updateScrollDirection() return () => window.removeEventListener('scroll', onScroll) }, [scrollDirection, threshold]) return { scrollDirection, isAtTop } }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/hooks/useTweets.ts
TypeScript
import { useMemo } from 'react' import tweetsData from '../../data/tweets.json' import type { Tweet } from '../types' interface TweetsDataType { lastUpdated: string tweets: Tweet[] } export function useTweets() { const data = tweetsData as TweetsDataType const tweets = useMemo(() => { return data.tweets.map(tweet => ({ ...tweet, publishedAt: new Date(tweet.publishedAt), })) }, [data.tweets]) return { tweets, lastUpdated: data.lastUpdated ? new Date(data.lastUpdated) : null, isLoading: false, } }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/index.css
CSS
@tailwind base; @tailwind components; @tailwind utilities; :root { --background: #ffffff; --foreground: #0f172a; --card: #ffffff; --card-foreground: #0f172a; --border: #e2e8f0; --muted: #f1f5f9; --muted-foreground: #64748b; --accent: #1da1f2; --accent-foreground: #ffffff; } .dark { --background: #15202b; --foreground: #e7e9ea; --card: #192734; --card-foreground: #e7e9ea; --border: #38444d; --muted: #253341; --muted-foreground: #8899a6; --accent: #1da1f2; --accent-foreground: #ffffff; } * { box-sizing: border-box; padding: 0; margin: 0; } html { scroll-behavior: smooth; } html, body { max-width: 100vw; overflow-x: hidden; } body { background-color: var(--background); color: var(--foreground); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; line-height: 1.5; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } /* Custom scrollbar */ ::-webkit-scrollbar { width: 8px; height: 8px; } ::-webkit-scrollbar-track { background: var(--muted); } ::-webkit-scrollbar-thumb { background: var(--muted-foreground); border-radius: 4px; } ::-webkit-scrollbar-thumb:hover { background: var(--accent); } /* Sidebar scrollbar */ aside::-webkit-scrollbar { width: 6px; } aside::-webkit-scrollbar-track { background: transparent; } aside::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; } aside::-webkit-scrollbar-thumb:hover { background: var(--muted-foreground); } /* Link styles */ a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; } /* Tweet content styles */ .tweet-content { word-break: break-word; white-space: pre-wrap; line-height: 1.5; } .tweet-content a { color: var(--accent); text-decoration: none; } .tweet-content a:hover { text-decoration: underline; } /* Avatar hover effect */ .avatar-hover { transition: transform 0.2s ease; } .avatar-hover:hover { transform: scale(1.05); } /* Card hover effect */ .card-hover { transition: background-color 0.15s ease; } .card-hover:hover { background-color: var(--muted); } /* Loading skeleton */ @keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } } .skeleton { background: linear-gradient( 90deg, var(--muted) 25%, var(--border) 50%, var(--muted) 75% ); background-size: 200% 100%; animation: shimmer 1.5s infinite; } /* Hide scrollbar for horizontal scroll */ .scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; } .scrollbar-hide::-webkit-scrollbar { display: none; } /* Fade in animation */ @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .animate-fade-in { animation: fadeIn 0.3s ease-out; } /* Focus styles for accessibility */ button:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } /* Selection styles */ ::selection { background-color: var(--accent); color: white; } ::-moz-selection { background-color: var(--accent); color: white; }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/main.tsx
TypeScript (TSX)
import React from 'react' import ReactDOM from 'react-dom/client' import { App } from './App' import { ThemeProvider } from './components/ThemeProvider' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <ThemeProvider> <App /> </ThemeProvider> </React.StrictMode> )
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/types.ts
TypeScript
// 推文类型 export interface Tweet { id: string username: string displayName: string avatar: string content: string contentHtml: string publishedAt: Date | string link: string // 媒体内容 media?: TweetMedia[] // 转推信息 retweet?: { username: string displayName: string } // 引用推文 quote?: { username: string displayName: string content: string link: string media?: TweetMedia[] } // 统计数据 stats?: { replies: number retweets: number likes: number } } export interface TweetMedia { type: 'image' | 'video' | 'gif' url: string thumbnail?: string alt?: string } // 关注者配置 export interface Follower { username: string displayName?: string avatar?: string group?: string }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
src/vite-env.d.ts
TypeScript
/// <reference types="vite/client" />
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
tailwind.config.js
JavaScript
/** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'], darkMode: 'class', theme: { extend: { colors: { twitter: { blue: '#1DA1F2', dark: '#15202B', darker: '#192734', border: '#38444D', }, }, animation: { 'fade-in': 'fadeIn 0.3s ease-in-out', 'slide-up': 'slideUp 0.3s ease-out', }, keyframes: { fadeIn: { '0%': { opacity: '0' }, '100%': { opacity: '1' }, }, slideUp: { '0%': { opacity: '0', transform: 'translateY(10px)' }, '100%': { opacity: '1', transform: 'translateY(0)' }, }, }, }, }, plugins: [], }
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
vite.config.ts
TypeScript
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' export default defineConfig({ plugins: [react()], resolve: { alias: { '@': path.resolve(__dirname, './src'), }, }, server: { port: 3000, open: true, }, build: { outDir: 'dist', sourcemap: true, }, })
xwartz/x-line
0
A clean and elegant X timeline aggregator
JavaScript
xwartz
xwartz
index.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Logseq Assets Plus</title> </head> <body> <div id="app"></div> <script src="./libs/uFuzzy.iife.min.js"></script> <script src="./src/index.tsx" type="module"></script> </body> </html>
xyhp915/logseq-assets-plus
28
A Logseq plugin to enhance assets features 🚀
TypeScript
xyhp915
Charlie
logseq
libs/animate.min.css
CSS
@charset "UTF-8";/*! * animate.css - https://animate.style/ * Version - 4.1.1 * Licensed under the MIT license - http://opensource.org/licenses/MIT * * Copyright (c) 2020 Animate.css */:root{--animate-duration:1s;--animate-delay:1s;--animate-repeat:1}.animate__animated{-webkit-animation-duration:1s;animation-duration:1s;-webkit-animation-duration:var(--animate-duration);animation-duration:var(--animate-duration);-webkit-animation-fill-mode:both;animation-fill-mode:both}.animate__animated.animate__infinite{-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite}.animate__animated.animate__repeat-1{-webkit-animation-iteration-count:1;animation-iteration-count:1;-webkit-animation-iteration-count:var(--animate-repeat);animation-iteration-count:var(--animate-repeat)}.animate__animated.animate__repeat-2{-webkit-animation-iteration-count:2;animation-iteration-count:2;-webkit-animation-iteration-count:calc(var(--animate-repeat)*2);animation-iteration-count:calc(var(--animate-repeat)*2)}.animate__animated.animate__repeat-3{-webkit-animation-iteration-count:3;animation-iteration-count:3;-webkit-animation-iteration-count:calc(var(--animate-repeat)*3);animation-iteration-count:calc(var(--animate-repeat)*3)}.animate__animated.animate__delay-1s{-webkit-animation-delay:1s;animation-delay:1s;-webkit-animation-delay:var(--animate-delay);animation-delay:var(--animate-delay)}.animate__animated.animate__delay-2s{-webkit-animation-delay:2s;animation-delay:2s;-webkit-animation-delay:calc(var(--animate-delay)*2);animation-delay:calc(var(--animate-delay)*2)}.animate__animated.animate__delay-3s{-webkit-animation-delay:3s;animation-delay:3s;-webkit-animation-delay:calc(var(--animate-delay)*3);animation-delay:calc(var(--animate-delay)*3)}.animate__animated.animate__delay-4s{-webkit-animation-delay:4s;animation-delay:4s;-webkit-animation-delay:calc(var(--animate-delay)*4);animation-delay:calc(var(--animate-delay)*4)}.animate__animated.animate__delay-5s{-webkit-animation-delay:5s;animation-delay:5s;-webkit-animation-delay:calc(var(--animate-delay)*5);animation-delay:calc(var(--animate-delay)*5)}.animate__animated.animate__faster{-webkit-animation-duration:.5s;animation-duration:.5s;-webkit-animation-duration:calc(var(--animate-duration)/2);animation-duration:calc(var(--animate-duration)/2)}.animate__animated.animate__fast{-webkit-animation-duration:.8s;animation-duration:.8s;-webkit-animation-duration:calc(var(--animate-duration)*0.8);animation-duration:calc(var(--animate-duration)*0.8)}.animate__animated.animate__slow{-webkit-animation-duration:2s;animation-duration:2s;-webkit-animation-duration:calc(var(--animate-duration)*2);animation-duration:calc(var(--animate-duration)*2)}.animate__animated.animate__slower{-webkit-animation-duration:3s;animation-duration:3s;-webkit-animation-duration:calc(var(--animate-duration)*3);animation-duration:calc(var(--animate-duration)*3)}@media (prefers-reduced-motion:reduce),print{.animate__animated{-webkit-animation-duration:1ms!important;animation-duration:1ms!important;-webkit-transition-duration:1ms!important;transition-duration:1ms!important;-webkit-animation-iteration-count:1!important;animation-iteration-count:1!important}.animate__animated[class*=Out]{opacity:0}}@-webkit-keyframes bounce{0%,20%,53%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1);-webkit-transform:translateZ(0);transform:translateZ(0)}40%,43%{-webkit-animation-timing-function:cubic-bezier(.755,.05,.855,.06);animation-timing-function:cubic-bezier(.755,.05,.855,.06);-webkit-transform:translate3d(0,-30px,0) scaleY(1.1);transform:translate3d(0,-30px,0) scaleY(1.1)}70%{-webkit-animation-timing-function:cubic-bezier(.755,.05,.855,.06);animation-timing-function:cubic-bezier(.755,.05,.855,.06);-webkit-transform:translate3d(0,-15px,0) scaleY(1.05);transform:translate3d(0,-15px,0) scaleY(1.05)}80%{-webkit-transition-timing-function:cubic-bezier(.215,.61,.355,1);transition-timing-function:cubic-bezier(.215,.61,.355,1);-webkit-transform:translateZ(0) scaleY(.95);transform:translateZ(0) scaleY(.95)}90%{-webkit-transform:translate3d(0,-4px,0) scaleY(1.02);transform:translate3d(0,-4px,0) scaleY(1.02)}}@keyframes bounce{0%,20%,53%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1);-webkit-transform:translateZ(0);transform:translateZ(0)}40%,43%{-webkit-animation-timing-function:cubic-bezier(.755,.05,.855,.06);animation-timing-function:cubic-bezier(.755,.05,.855,.06);-webkit-transform:translate3d(0,-30px,0) scaleY(1.1);transform:translate3d(0,-30px,0) scaleY(1.1)}70%{-webkit-animation-timing-function:cubic-bezier(.755,.05,.855,.06);animation-timing-function:cubic-bezier(.755,.05,.855,.06);-webkit-transform:translate3d(0,-15px,0) scaleY(1.05);transform:translate3d(0,-15px,0) scaleY(1.05)}80%{-webkit-transition-timing-function:cubic-bezier(.215,.61,.355,1);transition-timing-function:cubic-bezier(.215,.61,.355,1);-webkit-transform:translateZ(0) scaleY(.95);transform:translateZ(0) scaleY(.95)}90%{-webkit-transform:translate3d(0,-4px,0) scaleY(1.02);transform:translate3d(0,-4px,0) scaleY(1.02)}}.animate__bounce{-webkit-animation-name:bounce;animation-name:bounce;-webkit-transform-origin:center bottom;transform-origin:center bottom}@-webkit-keyframes flash{0%,50%,to{opacity:1}25%,75%{opacity:0}}@keyframes flash{0%,50%,to{opacity:1}25%,75%{opacity:0}}.animate__flash{-webkit-animation-name:flash;animation-name:flash}@-webkit-keyframes pulse{0%{-webkit-transform:scaleX(1);transform:scaleX(1)}50%{-webkit-transform:scale3d(1.05,1.05,1.05);transform:scale3d(1.05,1.05,1.05)}to{-webkit-transform:scaleX(1);transform:scaleX(1)}}@keyframes pulse{0%{-webkit-transform:scaleX(1);transform:scaleX(1)}50%{-webkit-transform:scale3d(1.05,1.05,1.05);transform:scale3d(1.05,1.05,1.05)}to{-webkit-transform:scaleX(1);transform:scaleX(1)}}.animate__pulse{-webkit-animation-name:pulse;animation-name:pulse;-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}@-webkit-keyframes rubberBand{0%{-webkit-transform:scaleX(1);transform:scaleX(1)}30%{-webkit-transform:scale3d(1.25,.75,1);transform:scale3d(1.25,.75,1)}40%{-webkit-transform:scale3d(.75,1.25,1);transform:scale3d(.75,1.25,1)}50%{-webkit-transform:scale3d(1.15,.85,1);transform:scale3d(1.15,.85,1)}65%{-webkit-transform:scale3d(.95,1.05,1);transform:scale3d(.95,1.05,1)}75%{-webkit-transform:scale3d(1.05,.95,1);transform:scale3d(1.05,.95,1)}to{-webkit-transform:scaleX(1);transform:scaleX(1)}}@keyframes rubberBand{0%{-webkit-transform:scaleX(1);transform:scaleX(1)}30%{-webkit-transform:scale3d(1.25,.75,1);transform:scale3d(1.25,.75,1)}40%{-webkit-transform:scale3d(.75,1.25,1);transform:scale3d(.75,1.25,1)}50%{-webkit-transform:scale3d(1.15,.85,1);transform:scale3d(1.15,.85,1)}65%{-webkit-transform:scale3d(.95,1.05,1);transform:scale3d(.95,1.05,1)}75%{-webkit-transform:scale3d(1.05,.95,1);transform:scale3d(1.05,.95,1)}to{-webkit-transform:scaleX(1);transform:scaleX(1)}}.animate__rubberBand{-webkit-animation-name:rubberBand;animation-name:rubberBand}@-webkit-keyframes shakeX{0%,to{-webkit-transform:translateZ(0);transform:translateZ(0)}10%,30%,50%,70%,90%{-webkit-transform:translate3d(-10px,0,0);transform:translate3d(-10px,0,0)}20%,40%,60%,80%{-webkit-transform:translate3d(10px,0,0);transform:translate3d(10px,0,0)}}@keyframes shakeX{0%,to{-webkit-transform:translateZ(0);transform:translateZ(0)}10%,30%,50%,70%,90%{-webkit-transform:translate3d(-10px,0,0);transform:translate3d(-10px,0,0)}20%,40%,60%,80%{-webkit-transform:translate3d(10px,0,0);transform:translate3d(10px,0,0)}}.animate__shakeX{-webkit-animation-name:shakeX;animation-name:shakeX}@-webkit-keyframes shakeY{0%,to{-webkit-transform:translateZ(0);transform:translateZ(0)}10%,30%,50%,70%,90%{-webkit-transform:translate3d(0,-10px,0);transform:translate3d(0,-10px,0)}20%,40%,60%,80%{-webkit-transform:translate3d(0,10px,0);transform:translate3d(0,10px,0)}}@keyframes shakeY{0%,to{-webkit-transform:translateZ(0);transform:translateZ(0)}10%,30%,50%,70%,90%{-webkit-transform:translate3d(0,-10px,0);transform:translate3d(0,-10px,0)}20%,40%,60%,80%{-webkit-transform:translate3d(0,10px,0);transform:translate3d(0,10px,0)}}.animate__shakeY{-webkit-animation-name:shakeY;animation-name:shakeY}@-webkit-keyframes headShake{0%{-webkit-transform:translateX(0);transform:translateX(0)}6.5%{-webkit-transform:translateX(-6px) rotateY(-9deg);transform:translateX(-6px) rotateY(-9deg)}18.5%{-webkit-transform:translateX(5px) rotateY(7deg);transform:translateX(5px) rotateY(7deg)}31.5%{-webkit-transform:translateX(-3px) rotateY(-5deg);transform:translateX(-3px) rotateY(-5deg)}43.5%{-webkit-transform:translateX(2px) rotateY(3deg);transform:translateX(2px) rotateY(3deg)}50%{-webkit-transform:translateX(0);transform:translateX(0)}}@keyframes headShake{0%{-webkit-transform:translateX(0);transform:translateX(0)}6.5%{-webkit-transform:translateX(-6px) rotateY(-9deg);transform:translateX(-6px) rotateY(-9deg)}18.5%{-webkit-transform:translateX(5px) rotateY(7deg);transform:translateX(5px) rotateY(7deg)}31.5%{-webkit-transform:translateX(-3px) rotateY(-5deg);transform:translateX(-3px) rotateY(-5deg)}43.5%{-webkit-transform:translateX(2px) rotateY(3deg);transform:translateX(2px) rotateY(3deg)}50%{-webkit-transform:translateX(0);transform:translateX(0)}}.animate__headShake{-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out;-webkit-animation-name:headShake;animation-name:headShake}@-webkit-keyframes swing{20%{-webkit-transform:rotate(15deg);transform:rotate(15deg)}40%{-webkit-transform:rotate(-10deg);transform:rotate(-10deg)}60%{-webkit-transform:rotate(5deg);transform:rotate(5deg)}80%{-webkit-transform:rotate(-5deg);transform:rotate(-5deg)}to{-webkit-transform:rotate(0deg);transform:rotate(0deg)}}@keyframes swing{20%{-webkit-transform:rotate(15deg);transform:rotate(15deg)}40%{-webkit-transform:rotate(-10deg);transform:rotate(-10deg)}60%{-webkit-transform:rotate(5deg);transform:rotate(5deg)}80%{-webkit-transform:rotate(-5deg);transform:rotate(-5deg)}to{-webkit-transform:rotate(0deg);transform:rotate(0deg)}}.animate__swing{-webkit-transform-origin:top center;transform-origin:top center;-webkit-animation-name:swing;animation-name:swing}@-webkit-keyframes tada{0%{-webkit-transform:scaleX(1);transform:scaleX(1)}10%,20%{-webkit-transform:scale3d(.9,.9,.9) rotate(-3deg);transform:scale3d(.9,.9,.9) rotate(-3deg)}30%,50%,70%,90%{-webkit-transform:scale3d(1.1,1.1,1.1) rotate(3deg);transform:scale3d(1.1,1.1,1.1) rotate(3deg)}40%,60%,80%{-webkit-transform:scale3d(1.1,1.1,1.1) rotate(-3deg);transform:scale3d(1.1,1.1,1.1) rotate(-3deg)}to{-webkit-transform:scaleX(1);transform:scaleX(1)}}@keyframes tada{0%{-webkit-transform:scaleX(1);transform:scaleX(1)}10%,20%{-webkit-transform:scale3d(.9,.9,.9) rotate(-3deg);transform:scale3d(.9,.9,.9) rotate(-3deg)}30%,50%,70%,90%{-webkit-transform:scale3d(1.1,1.1,1.1) rotate(3deg);transform:scale3d(1.1,1.1,1.1) rotate(3deg)}40%,60%,80%{-webkit-transform:scale3d(1.1,1.1,1.1) rotate(-3deg);transform:scale3d(1.1,1.1,1.1) rotate(-3deg)}to{-webkit-transform:scaleX(1);transform:scaleX(1)}}.animate__tada{-webkit-animation-name:tada;animation-name:tada}@-webkit-keyframes wobble{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}15%{-webkit-transform:translate3d(-25%,0,0) rotate(-5deg);transform:translate3d(-25%,0,0) rotate(-5deg)}30%{-webkit-transform:translate3d(20%,0,0) rotate(3deg);transform:translate3d(20%,0,0) rotate(3deg)}45%{-webkit-transform:translate3d(-15%,0,0) rotate(-3deg);transform:translate3d(-15%,0,0) rotate(-3deg)}60%{-webkit-transform:translate3d(10%,0,0) rotate(2deg);transform:translate3d(10%,0,0) rotate(2deg)}75%{-webkit-transform:translate3d(-5%,0,0) rotate(-1deg);transform:translate3d(-5%,0,0) rotate(-1deg)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes wobble{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}15%{-webkit-transform:translate3d(-25%,0,0) rotate(-5deg);transform:translate3d(-25%,0,0) rotate(-5deg)}30%{-webkit-transform:translate3d(20%,0,0) rotate(3deg);transform:translate3d(20%,0,0) rotate(3deg)}45%{-webkit-transform:translate3d(-15%,0,0) rotate(-3deg);transform:translate3d(-15%,0,0) rotate(-3deg)}60%{-webkit-transform:translate3d(10%,0,0) rotate(2deg);transform:translate3d(10%,0,0) rotate(2deg)}75%{-webkit-transform:translate3d(-5%,0,0) rotate(-1deg);transform:translate3d(-5%,0,0) rotate(-1deg)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__wobble{-webkit-animation-name:wobble;animation-name:wobble}@-webkit-keyframes jello{0%,11.1%,to{-webkit-transform:translateZ(0);transform:translateZ(0)}22.2%{-webkit-transform:skewX(-12.5deg) skewY(-12.5deg);transform:skewX(-12.5deg) skewY(-12.5deg)}33.3%{-webkit-transform:skewX(6.25deg) skewY(6.25deg);transform:skewX(6.25deg) skewY(6.25deg)}44.4%{-webkit-transform:skewX(-3.125deg) skewY(-3.125deg);transform:skewX(-3.125deg) skewY(-3.125deg)}55.5%{-webkit-transform:skewX(1.5625deg) skewY(1.5625deg);transform:skewX(1.5625deg) skewY(1.5625deg)}66.6%{-webkit-transform:skewX(-.78125deg) skewY(-.78125deg);transform:skewX(-.78125deg) skewY(-.78125deg)}77.7%{-webkit-transform:skewX(.390625deg) skewY(.390625deg);transform:skewX(.390625deg) skewY(.390625deg)}88.8%{-webkit-transform:skewX(-.1953125deg) skewY(-.1953125deg);transform:skewX(-.1953125deg) skewY(-.1953125deg)}}@keyframes jello{0%,11.1%,to{-webkit-transform:translateZ(0);transform:translateZ(0)}22.2%{-webkit-transform:skewX(-12.5deg) skewY(-12.5deg);transform:skewX(-12.5deg) skewY(-12.5deg)}33.3%{-webkit-transform:skewX(6.25deg) skewY(6.25deg);transform:skewX(6.25deg) skewY(6.25deg)}44.4%{-webkit-transform:skewX(-3.125deg) skewY(-3.125deg);transform:skewX(-3.125deg) skewY(-3.125deg)}55.5%{-webkit-transform:skewX(1.5625deg) skewY(1.5625deg);transform:skewX(1.5625deg) skewY(1.5625deg)}66.6%{-webkit-transform:skewX(-.78125deg) skewY(-.78125deg);transform:skewX(-.78125deg) skewY(-.78125deg)}77.7%{-webkit-transform:skewX(.390625deg) skewY(.390625deg);transform:skewX(.390625deg) skewY(.390625deg)}88.8%{-webkit-transform:skewX(-.1953125deg) skewY(-.1953125deg);transform:skewX(-.1953125deg) skewY(-.1953125deg)}}.animate__jello{-webkit-animation-name:jello;animation-name:jello;-webkit-transform-origin:center;transform-origin:center}@-webkit-keyframes heartBeat{0%{-webkit-transform:scale(1);transform:scale(1)}14%{-webkit-transform:scale(1.3);transform:scale(1.3)}28%{-webkit-transform:scale(1);transform:scale(1)}42%{-webkit-transform:scale(1.3);transform:scale(1.3)}70%{-webkit-transform:scale(1);transform:scale(1)}}@keyframes heartBeat{0%{-webkit-transform:scale(1);transform:scale(1)}14%{-webkit-transform:scale(1.3);transform:scale(1.3)}28%{-webkit-transform:scale(1);transform:scale(1)}42%{-webkit-transform:scale(1.3);transform:scale(1.3)}70%{-webkit-transform:scale(1);transform:scale(1)}}.animate__heartBeat{-webkit-animation-name:heartBeat;animation-name:heartBeat;-webkit-animation-duration:1.3s;animation-duration:1.3s;-webkit-animation-duration:calc(var(--animate-duration)*1.3);animation-duration:calc(var(--animate-duration)*1.3);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}@-webkit-keyframes backInDown{0%{-webkit-transform:translateY(-1200px) scale(.7);transform:translateY(-1200px) scale(.7);opacity:.7}80%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes backInDown{0%{-webkit-transform:translateY(-1200px) scale(.7);transform:translateY(-1200px) scale(.7);opacity:.7}80%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}.animate__backInDown{-webkit-animation-name:backInDown;animation-name:backInDown}@-webkit-keyframes backInLeft{0%{-webkit-transform:translateX(-2000px) scale(.7);transform:translateX(-2000px) scale(.7);opacity:.7}80%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes backInLeft{0%{-webkit-transform:translateX(-2000px) scale(.7);transform:translateX(-2000px) scale(.7);opacity:.7}80%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}.animate__backInLeft{-webkit-animation-name:backInLeft;animation-name:backInLeft}@-webkit-keyframes backInRight{0%{-webkit-transform:translateX(2000px) scale(.7);transform:translateX(2000px) scale(.7);opacity:.7}80%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes backInRight{0%{-webkit-transform:translateX(2000px) scale(.7);transform:translateX(2000px) scale(.7);opacity:.7}80%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}.animate__backInRight{-webkit-animation-name:backInRight;animation-name:backInRight}@-webkit-keyframes backInUp{0%{-webkit-transform:translateY(1200px) scale(.7);transform:translateY(1200px) scale(.7);opacity:.7}80%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@keyframes backInUp{0%{-webkit-transform:translateY(1200px) scale(.7);transform:translateY(1200px) scale(.7);opacity:.7}80%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:scale(1);transform:scale(1);opacity:1}}.animate__backInUp{-webkit-animation-name:backInUp;animation-name:backInUp}@-webkit-keyframes backOutDown{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:translateY(700px) scale(.7);transform:translateY(700px) scale(.7);opacity:.7}}@keyframes backOutDown{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:translateY(700px) scale(.7);transform:translateY(700px) scale(.7);opacity:.7}}.animate__backOutDown{-webkit-animation-name:backOutDown;animation-name:backOutDown}@-webkit-keyframes backOutLeft{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:translateX(-2000px) scale(.7);transform:translateX(-2000px) scale(.7);opacity:.7}}@keyframes backOutLeft{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:translateX(-2000px) scale(.7);transform:translateX(-2000px) scale(.7);opacity:.7}}.animate__backOutLeft{-webkit-animation-name:backOutLeft;animation-name:backOutLeft}@-webkit-keyframes backOutRight{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:translateX(2000px) scale(.7);transform:translateX(2000px) scale(.7);opacity:.7}}@keyframes backOutRight{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateX(0) scale(.7);transform:translateX(0) scale(.7);opacity:.7}to{-webkit-transform:translateX(2000px) scale(.7);transform:translateX(2000px) scale(.7);opacity:.7}}.animate__backOutRight{-webkit-animation-name:backOutRight;animation-name:backOutRight}@-webkit-keyframes backOutUp{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:translateY(-700px) scale(.7);transform:translateY(-700px) scale(.7);opacity:.7}}@keyframes backOutUp{0%{-webkit-transform:scale(1);transform:scale(1);opacity:1}20%{-webkit-transform:translateY(0) scale(.7);transform:translateY(0) scale(.7);opacity:.7}to{-webkit-transform:translateY(-700px) scale(.7);transform:translateY(-700px) scale(.7);opacity:.7}}.animate__backOutUp{-webkit-animation-name:backOutUp;animation-name:backOutUp}@-webkit-keyframes bounceIn{0%,20%,40%,60%,80%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}}@keyframes bounceIn{0%,20%,40%,60%,80%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}}.animate__bounceIn{-webkit-animation-duration:.75s;animation-duration:.75s;-webkit-animation-duration:calc(var(--animate-duration)*0.75);animation-duration:calc(var(--animate-duration)*0.75);-webkit-animation-name:bounceIn;animation-name:bounceIn}@-webkit-keyframes bounceInDown{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(0,-3000px,0) scaleY(3);transform:translate3d(0,-3000px,0) scaleY(3)}60%{opacity:1;-webkit-transform:translate3d(0,25px,0) scaleY(.9);transform:translate3d(0,25px,0) scaleY(.9)}75%{-webkit-transform:translate3d(0,-10px,0) scaleY(.95);transform:translate3d(0,-10px,0) scaleY(.95)}90%{-webkit-transform:translate3d(0,5px,0) scaleY(.985);transform:translate3d(0,5px,0) scaleY(.985)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes bounceInDown{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(0,-3000px,0) scaleY(3);transform:translate3d(0,-3000px,0) scaleY(3)}60%{opacity:1;-webkit-transform:translate3d(0,25px,0) scaleY(.9);transform:translate3d(0,25px,0) scaleY(.9)}75%{-webkit-transform:translate3d(0,-10px,0) scaleY(.95);transform:translate3d(0,-10px,0) scaleY(.95)}90%{-webkit-transform:translate3d(0,5px,0) scaleY(.985);transform:translate3d(0,5px,0) scaleY(.985)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__bounceInDown{-webkit-animation-name:bounceInDown;animation-name:bounceInDown}@-webkit-keyframes bounceInLeft{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(-3000px,0,0) scaleX(3);transform:translate3d(-3000px,0,0) scaleX(3)}60%{opacity:1;-webkit-transform:translate3d(25px,0,0) scaleX(1);transform:translate3d(25px,0,0) scaleX(1)}75%{-webkit-transform:translate3d(-10px,0,0) scaleX(.98);transform:translate3d(-10px,0,0) scaleX(.98)}90%{-webkit-transform:translate3d(5px,0,0) scaleX(.995);transform:translate3d(5px,0,0) scaleX(.995)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes bounceInLeft{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(-3000px,0,0) scaleX(3);transform:translate3d(-3000px,0,0) scaleX(3)}60%{opacity:1;-webkit-transform:translate3d(25px,0,0) scaleX(1);transform:translate3d(25px,0,0) scaleX(1)}75%{-webkit-transform:translate3d(-10px,0,0) scaleX(.98);transform:translate3d(-10px,0,0) scaleX(.98)}90%{-webkit-transform:translate3d(5px,0,0) scaleX(.995);transform:translate3d(5px,0,0) scaleX(.995)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__bounceInLeft{-webkit-animation-name:bounceInLeft;animation-name:bounceInLeft}@-webkit-keyframes bounceInRight{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(3000px,0,0) scaleX(3);transform:translate3d(3000px,0,0) scaleX(3)}60%{opacity:1;-webkit-transform:translate3d(-25px,0,0) scaleX(1);transform:translate3d(-25px,0,0) scaleX(1)}75%{-webkit-transform:translate3d(10px,0,0) scaleX(.98);transform:translate3d(10px,0,0) scaleX(.98)}90%{-webkit-transform:translate3d(-5px,0,0) scaleX(.995);transform:translate3d(-5px,0,0) scaleX(.995)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes bounceInRight{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(3000px,0,0) scaleX(3);transform:translate3d(3000px,0,0) scaleX(3)}60%{opacity:1;-webkit-transform:translate3d(-25px,0,0) scaleX(1);transform:translate3d(-25px,0,0) scaleX(1)}75%{-webkit-transform:translate3d(10px,0,0) scaleX(.98);transform:translate3d(10px,0,0) scaleX(.98)}90%{-webkit-transform:translate3d(-5px,0,0) scaleX(.995);transform:translate3d(-5px,0,0) scaleX(.995)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__bounceInRight{-webkit-animation-name:bounceInRight;animation-name:bounceInRight}@-webkit-keyframes bounceInUp{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(0,3000px,0) scaleY(5);transform:translate3d(0,3000px,0) scaleY(5)}60%{opacity:1;-webkit-transform:translate3d(0,-20px,0) scaleY(.9);transform:translate3d(0,-20px,0) scaleY(.9)}75%{-webkit-transform:translate3d(0,10px,0) scaleY(.95);transform:translate3d(0,10px,0) scaleY(.95)}90%{-webkit-transform:translate3d(0,-5px,0) scaleY(.985);transform:translate3d(0,-5px,0) scaleY(.985)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes bounceInUp{0%,60%,75%,90%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:translate3d(0,3000px,0) scaleY(5);transform:translate3d(0,3000px,0) scaleY(5)}60%{opacity:1;-webkit-transform:translate3d(0,-20px,0) scaleY(.9);transform:translate3d(0,-20px,0) scaleY(.9)}75%{-webkit-transform:translate3d(0,10px,0) scaleY(.95);transform:translate3d(0,10px,0) scaleY(.95)}90%{-webkit-transform:translate3d(0,-5px,0) scaleY(.985);transform:translate3d(0,-5px,0) scaleY(.985)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__bounceInUp{-webkit-animation-name:bounceInUp;animation-name:bounceInUp}@-webkit-keyframes bounceOut{20%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}50%,55%{opacity:1;-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}to{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}}@keyframes bounceOut{20%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}50%,55%{opacity:1;-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}to{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}}.animate__bounceOut{-webkit-animation-duration:.75s;animation-duration:.75s;-webkit-animation-duration:calc(var(--animate-duration)*0.75);animation-duration:calc(var(--animate-duration)*0.75);-webkit-animation-name:bounceOut;animation-name:bounceOut}@-webkit-keyframes bounceOutDown{20%{-webkit-transform:translate3d(0,10px,0) scaleY(.985);transform:translate3d(0,10px,0) scaleY(.985)}40%,45%{opacity:1;-webkit-transform:translate3d(0,-20px,0) scaleY(.9);transform:translate3d(0,-20px,0) scaleY(.9)}to{opacity:0;-webkit-transform:translate3d(0,2000px,0) scaleY(3);transform:translate3d(0,2000px,0) scaleY(3)}}@keyframes bounceOutDown{20%{-webkit-transform:translate3d(0,10px,0) scaleY(.985);transform:translate3d(0,10px,0) scaleY(.985)}40%,45%{opacity:1;-webkit-transform:translate3d(0,-20px,0) scaleY(.9);transform:translate3d(0,-20px,0) scaleY(.9)}to{opacity:0;-webkit-transform:translate3d(0,2000px,0) scaleY(3);transform:translate3d(0,2000px,0) scaleY(3)}}.animate__bounceOutDown{-webkit-animation-name:bounceOutDown;animation-name:bounceOutDown}@-webkit-keyframes bounceOutLeft{20%{opacity:1;-webkit-transform:translate3d(20px,0,0) scaleX(.9);transform:translate3d(20px,0,0) scaleX(.9)}to{opacity:0;-webkit-transform:translate3d(-2000px,0,0) scaleX(2);transform:translate3d(-2000px,0,0) scaleX(2)}}@keyframes bounceOutLeft{20%{opacity:1;-webkit-transform:translate3d(20px,0,0) scaleX(.9);transform:translate3d(20px,0,0) scaleX(.9)}to{opacity:0;-webkit-transform:translate3d(-2000px,0,0) scaleX(2);transform:translate3d(-2000px,0,0) scaleX(2)}}.animate__bounceOutLeft{-webkit-animation-name:bounceOutLeft;animation-name:bounceOutLeft}@-webkit-keyframes bounceOutRight{20%{opacity:1;-webkit-transform:translate3d(-20px,0,0) scaleX(.9);transform:translate3d(-20px,0,0) scaleX(.9)}to{opacity:0;-webkit-transform:translate3d(2000px,0,0) scaleX(2);transform:translate3d(2000px,0,0) scaleX(2)}}@keyframes bounceOutRight{20%{opacity:1;-webkit-transform:translate3d(-20px,0,0) scaleX(.9);transform:translate3d(-20px,0,0) scaleX(.9)}to{opacity:0;-webkit-transform:translate3d(2000px,0,0) scaleX(2);transform:translate3d(2000px,0,0) scaleX(2)}}.animate__bounceOutRight{-webkit-animation-name:bounceOutRight;animation-name:bounceOutRight}@-webkit-keyframes bounceOutUp{20%{-webkit-transform:translate3d(0,-10px,0) scaleY(.985);transform:translate3d(0,-10px,0) scaleY(.985)}40%,45%{opacity:1;-webkit-transform:translate3d(0,20px,0) scaleY(.9);transform:translate3d(0,20px,0) scaleY(.9)}to{opacity:0;-webkit-transform:translate3d(0,-2000px,0) scaleY(3);transform:translate3d(0,-2000px,0) scaleY(3)}}@keyframes bounceOutUp{20%{-webkit-transform:translate3d(0,-10px,0) scaleY(.985);transform:translate3d(0,-10px,0) scaleY(.985)}40%,45%{opacity:1;-webkit-transform:translate3d(0,20px,0) scaleY(.9);transform:translate3d(0,20px,0) scaleY(.9)}to{opacity:0;-webkit-transform:translate3d(0,-2000px,0) scaleY(3);transform:translate3d(0,-2000px,0) scaleY(3)}}.animate__bounceOutUp{-webkit-animation-name:bounceOutUp;animation-name:bounceOutUp}@-webkit-keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.animate__fadeIn{-webkit-animation-name:fadeIn;animation-name:fadeIn}@-webkit-keyframes fadeInDown{0%{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInDown{0%{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInDown{-webkit-animation-name:fadeInDown;animation-name:fadeInDown}@-webkit-keyframes fadeInDownBig{0%{opacity:0;-webkit-transform:translate3d(0,-2000px,0);transform:translate3d(0,-2000px,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInDownBig{0%{opacity:0;-webkit-transform:translate3d(0,-2000px,0);transform:translate3d(0,-2000px,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInDownBig{-webkit-animation-name:fadeInDownBig;animation-name:fadeInDownBig}@-webkit-keyframes fadeInLeft{0%{opacity:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInLeft{0%{opacity:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInLeft{-webkit-animation-name:fadeInLeft;animation-name:fadeInLeft}@-webkit-keyframes fadeInLeftBig{0%{opacity:0;-webkit-transform:translate3d(-2000px,0,0);transform:translate3d(-2000px,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInLeftBig{0%{opacity:0;-webkit-transform:translate3d(-2000px,0,0);transform:translate3d(-2000px,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInLeftBig{-webkit-animation-name:fadeInLeftBig;animation-name:fadeInLeftBig}@-webkit-keyframes fadeInRight{0%{opacity:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInRight{0%{opacity:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInRight{-webkit-animation-name:fadeInRight;animation-name:fadeInRight}@-webkit-keyframes fadeInRightBig{0%{opacity:0;-webkit-transform:translate3d(2000px,0,0);transform:translate3d(2000px,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInRightBig{0%{opacity:0;-webkit-transform:translate3d(2000px,0,0);transform:translate3d(2000px,0,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInRightBig{-webkit-animation-name:fadeInRightBig;animation-name:fadeInRightBig}@-webkit-keyframes fadeInUp{0%{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInUp{0%{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInUp{-webkit-animation-name:fadeInUp;animation-name:fadeInUp}@-webkit-keyframes fadeInUpBig{0%{opacity:0;-webkit-transform:translate3d(0,2000px,0);transform:translate3d(0,2000px,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInUpBig{0%{opacity:0;-webkit-transform:translate3d(0,2000px,0);transform:translate3d(0,2000px,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInUpBig{-webkit-animation-name:fadeInUpBig;animation-name:fadeInUpBig}@-webkit-keyframes fadeInTopLeft{0%{opacity:0;-webkit-transform:translate3d(-100%,-100%,0);transform:translate3d(-100%,-100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInTopLeft{0%{opacity:0;-webkit-transform:translate3d(-100%,-100%,0);transform:translate3d(-100%,-100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInTopLeft{-webkit-animation-name:fadeInTopLeft;animation-name:fadeInTopLeft}@-webkit-keyframes fadeInTopRight{0%{opacity:0;-webkit-transform:translate3d(100%,-100%,0);transform:translate3d(100%,-100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInTopRight{0%{opacity:0;-webkit-transform:translate3d(100%,-100%,0);transform:translate3d(100%,-100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInTopRight{-webkit-animation-name:fadeInTopRight;animation-name:fadeInTopRight}@-webkit-keyframes fadeInBottomLeft{0%{opacity:0;-webkit-transform:translate3d(-100%,100%,0);transform:translate3d(-100%,100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInBottomLeft{0%{opacity:0;-webkit-transform:translate3d(-100%,100%,0);transform:translate3d(-100%,100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInBottomLeft{-webkit-animation-name:fadeInBottomLeft;animation-name:fadeInBottomLeft}@-webkit-keyframes fadeInBottomRight{0%{opacity:0;-webkit-transform:translate3d(100%,100%,0);transform:translate3d(100%,100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes fadeInBottomRight{0%{opacity:0;-webkit-transform:translate3d(100%,100%,0);transform:translate3d(100%,100%,0)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__fadeInBottomRight{-webkit-animation-name:fadeInBottomRight;animation-name:fadeInBottomRight}@-webkit-keyframes fadeOut{0%{opacity:1}to{opacity:0}}@keyframes fadeOut{0%{opacity:1}to{opacity:0}}.animate__fadeOut{-webkit-animation-name:fadeOut;animation-name:fadeOut}@-webkit-keyframes fadeOutDown{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}}@keyframes fadeOutDown{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}}.animate__fadeOutDown{-webkit-animation-name:fadeOutDown;animation-name:fadeOutDown}@-webkit-keyframes fadeOutDownBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,2000px,0);transform:translate3d(0,2000px,0)}}@keyframes fadeOutDownBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,2000px,0);transform:translate3d(0,2000px,0)}}.animate__fadeOutDownBig{-webkit-animation-name:fadeOutDownBig;animation-name:fadeOutDownBig}@-webkit-keyframes fadeOutLeft{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}@keyframes fadeOutLeft{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}.animate__fadeOutLeft{-webkit-animation-name:fadeOutLeft;animation-name:fadeOutLeft}@-webkit-keyframes fadeOutLeftBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(-2000px,0,0);transform:translate3d(-2000px,0,0)}}@keyframes fadeOutLeftBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(-2000px,0,0);transform:translate3d(-2000px,0,0)}}.animate__fadeOutLeftBig{-webkit-animation-name:fadeOutLeftBig;animation-name:fadeOutLeftBig}@-webkit-keyframes fadeOutRight{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}}@keyframes fadeOutRight{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}}.animate__fadeOutRight{-webkit-animation-name:fadeOutRight;animation-name:fadeOutRight}@-webkit-keyframes fadeOutRightBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(2000px,0,0);transform:translate3d(2000px,0,0)}}@keyframes fadeOutRightBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(2000px,0,0);transform:translate3d(2000px,0,0)}}.animate__fadeOutRightBig{-webkit-animation-name:fadeOutRightBig;animation-name:fadeOutRightBig}@-webkit-keyframes fadeOutUp{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}}@keyframes fadeOutUp{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}}.animate__fadeOutUp{-webkit-animation-name:fadeOutUp;animation-name:fadeOutUp}@-webkit-keyframes fadeOutUpBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,-2000px,0);transform:translate3d(0,-2000px,0)}}@keyframes fadeOutUpBig{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(0,-2000px,0);transform:translate3d(0,-2000px,0)}}.animate__fadeOutUpBig{-webkit-animation-name:fadeOutUpBig;animation-name:fadeOutUpBig}@-webkit-keyframes fadeOutTopLeft{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(-100%,-100%,0);transform:translate3d(-100%,-100%,0)}}@keyframes fadeOutTopLeft{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(-100%,-100%,0);transform:translate3d(-100%,-100%,0)}}.animate__fadeOutTopLeft{-webkit-animation-name:fadeOutTopLeft;animation-name:fadeOutTopLeft}@-webkit-keyframes fadeOutTopRight{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(100%,-100%,0);transform:translate3d(100%,-100%,0)}}@keyframes fadeOutTopRight{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(100%,-100%,0);transform:translate3d(100%,-100%,0)}}.animate__fadeOutTopRight{-webkit-animation-name:fadeOutTopRight;animation-name:fadeOutTopRight}@-webkit-keyframes fadeOutBottomRight{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(100%,100%,0);transform:translate3d(100%,100%,0)}}@keyframes fadeOutBottomRight{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(100%,100%,0);transform:translate3d(100%,100%,0)}}.animate__fadeOutBottomRight{-webkit-animation-name:fadeOutBottomRight;animation-name:fadeOutBottomRight}@-webkit-keyframes fadeOutBottomLeft{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(-100%,100%,0);transform:translate3d(-100%,100%,0)}}@keyframes fadeOutBottomLeft{0%{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}to{opacity:0;-webkit-transform:translate3d(-100%,100%,0);transform:translate3d(-100%,100%,0)}}.animate__fadeOutBottomLeft{-webkit-animation-name:fadeOutBottomLeft;animation-name:fadeOutBottomLeft}@-webkit-keyframes flip{0%{-webkit-transform:perspective(400px) scaleX(1) translateZ(0) rotateY(-1turn);transform:perspective(400px) scaleX(1) translateZ(0) rotateY(-1turn);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}40%{-webkit-transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-190deg);transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-190deg);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}50%{-webkit-transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-170deg);transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-170deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}80%{-webkit-transform:perspective(400px) scale3d(.95,.95,.95) translateZ(0) rotateY(0deg);transform:perspective(400px) scale3d(.95,.95,.95) translateZ(0) rotateY(0deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}to{-webkit-transform:perspective(400px) scaleX(1) translateZ(0) rotateY(0deg);transform:perspective(400px) scaleX(1) translateZ(0) rotateY(0deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}}@keyframes flip{0%{-webkit-transform:perspective(400px) scaleX(1) translateZ(0) rotateY(-1turn);transform:perspective(400px) scaleX(1) translateZ(0) rotateY(-1turn);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}40%{-webkit-transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-190deg);transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-190deg);-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}50%{-webkit-transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-170deg);transform:perspective(400px) scaleX(1) translateZ(150px) rotateY(-170deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}80%{-webkit-transform:perspective(400px) scale3d(.95,.95,.95) translateZ(0) rotateY(0deg);transform:perspective(400px) scale3d(.95,.95,.95) translateZ(0) rotateY(0deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}to{-webkit-transform:perspective(400px) scaleX(1) translateZ(0) rotateY(0deg);transform:perspective(400px) scaleX(1) translateZ(0) rotateY(0deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}}.animate__animated.animate__flip{-webkit-backface-visibility:visible;backface-visibility:visible;-webkit-animation-name:flip;animation-name:flip}@-webkit-keyframes flipInX{0%{-webkit-transform:perspective(400px) rotateX(90deg);transform:perspective(400px) rotateX(90deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in;opacity:0}40%{-webkit-transform:perspective(400px) rotateX(-20deg);transform:perspective(400px) rotateX(-20deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}60%{-webkit-transform:perspective(400px) rotateX(10deg);transform:perspective(400px) rotateX(10deg);opacity:1}80%{-webkit-transform:perspective(400px) rotateX(-5deg);transform:perspective(400px) rotateX(-5deg)}to{-webkit-transform:perspective(400px);transform:perspective(400px)}}@keyframes flipInX{0%{-webkit-transform:perspective(400px) rotateX(90deg);transform:perspective(400px) rotateX(90deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in;opacity:0}40%{-webkit-transform:perspective(400px) rotateX(-20deg);transform:perspective(400px) rotateX(-20deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}60%{-webkit-transform:perspective(400px) rotateX(10deg);transform:perspective(400px) rotateX(10deg);opacity:1}80%{-webkit-transform:perspective(400px) rotateX(-5deg);transform:perspective(400px) rotateX(-5deg)}to{-webkit-transform:perspective(400px);transform:perspective(400px)}}.animate__flipInX{-webkit-backface-visibility:visible!important;backface-visibility:visible!important;-webkit-animation-name:flipInX;animation-name:flipInX}@-webkit-keyframes flipInY{0%{-webkit-transform:perspective(400px) rotateY(90deg);transform:perspective(400px) rotateY(90deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in;opacity:0}40%{-webkit-transform:perspective(400px) rotateY(-20deg);transform:perspective(400px) rotateY(-20deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}60%{-webkit-transform:perspective(400px) rotateY(10deg);transform:perspective(400px) rotateY(10deg);opacity:1}80%{-webkit-transform:perspective(400px) rotateY(-5deg);transform:perspective(400px) rotateY(-5deg)}to{-webkit-transform:perspective(400px);transform:perspective(400px)}}@keyframes flipInY{0%{-webkit-transform:perspective(400px) rotateY(90deg);transform:perspective(400px) rotateY(90deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in;opacity:0}40%{-webkit-transform:perspective(400px) rotateY(-20deg);transform:perspective(400px) rotateY(-20deg);-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}60%{-webkit-transform:perspective(400px) rotateY(10deg);transform:perspective(400px) rotateY(10deg);opacity:1}80%{-webkit-transform:perspective(400px) rotateY(-5deg);transform:perspective(400px) rotateY(-5deg)}to{-webkit-transform:perspective(400px);transform:perspective(400px)}}.animate__flipInY{-webkit-backface-visibility:visible!important;backface-visibility:visible!important;-webkit-animation-name:flipInY;animation-name:flipInY}@-webkit-keyframes flipOutX{0%{-webkit-transform:perspective(400px);transform:perspective(400px)}30%{-webkit-transform:perspective(400px) rotateX(-20deg);transform:perspective(400px) rotateX(-20deg);opacity:1}to{-webkit-transform:perspective(400px) rotateX(90deg);transform:perspective(400px) rotateX(90deg);opacity:0}}@keyframes flipOutX{0%{-webkit-transform:perspective(400px);transform:perspective(400px)}30%{-webkit-transform:perspective(400px) rotateX(-20deg);transform:perspective(400px) rotateX(-20deg);opacity:1}to{-webkit-transform:perspective(400px) rotateX(90deg);transform:perspective(400px) rotateX(90deg);opacity:0}}.animate__flipOutX{-webkit-animation-duration:.75s;animation-duration:.75s;-webkit-animation-duration:calc(var(--animate-duration)*0.75);animation-duration:calc(var(--animate-duration)*0.75);-webkit-animation-name:flipOutX;animation-name:flipOutX;-webkit-backface-visibility:visible!important;backface-visibility:visible!important}@-webkit-keyframes flipOutY{0%{-webkit-transform:perspective(400px);transform:perspective(400px)}30%{-webkit-transform:perspective(400px) rotateY(-15deg);transform:perspective(400px) rotateY(-15deg);opacity:1}to{-webkit-transform:perspective(400px) rotateY(90deg);transform:perspective(400px) rotateY(90deg);opacity:0}}@keyframes flipOutY{0%{-webkit-transform:perspective(400px);transform:perspective(400px)}30%{-webkit-transform:perspective(400px) rotateY(-15deg);transform:perspective(400px) rotateY(-15deg);opacity:1}to{-webkit-transform:perspective(400px) rotateY(90deg);transform:perspective(400px) rotateY(90deg);opacity:0}}.animate__flipOutY{-webkit-animation-duration:.75s;animation-duration:.75s;-webkit-animation-duration:calc(var(--animate-duration)*0.75);animation-duration:calc(var(--animate-duration)*0.75);-webkit-backface-visibility:visible!important;backface-visibility:visible!important;-webkit-animation-name:flipOutY;animation-name:flipOutY}@-webkit-keyframes lightSpeedInRight{0%{-webkit-transform:translate3d(100%,0,0) skewX(-30deg);transform:translate3d(100%,0,0) skewX(-30deg);opacity:0}60%{-webkit-transform:skewX(20deg);transform:skewX(20deg);opacity:1}80%{-webkit-transform:skewX(-5deg);transform:skewX(-5deg)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes lightSpeedInRight{0%{-webkit-transform:translate3d(100%,0,0) skewX(-30deg);transform:translate3d(100%,0,0) skewX(-30deg);opacity:0}60%{-webkit-transform:skewX(20deg);transform:skewX(20deg);opacity:1}80%{-webkit-transform:skewX(-5deg);transform:skewX(-5deg)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__lightSpeedInRight{-webkit-animation-name:lightSpeedInRight;animation-name:lightSpeedInRight;-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}@-webkit-keyframes lightSpeedInLeft{0%{-webkit-transform:translate3d(-100%,0,0) skewX(30deg);transform:translate3d(-100%,0,0) skewX(30deg);opacity:0}60%{-webkit-transform:skewX(-20deg);transform:skewX(-20deg);opacity:1}80%{-webkit-transform:skewX(5deg);transform:skewX(5deg)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes lightSpeedInLeft{0%{-webkit-transform:translate3d(-100%,0,0) skewX(30deg);transform:translate3d(-100%,0,0) skewX(30deg);opacity:0}60%{-webkit-transform:skewX(-20deg);transform:skewX(-20deg);opacity:1}80%{-webkit-transform:skewX(5deg);transform:skewX(5deg)}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__lightSpeedInLeft{-webkit-animation-name:lightSpeedInLeft;animation-name:lightSpeedInLeft;-webkit-animation-timing-function:ease-out;animation-timing-function:ease-out}@-webkit-keyframes lightSpeedOutRight{0%{opacity:1}to{-webkit-transform:translate3d(100%,0,0) skewX(30deg);transform:translate3d(100%,0,0) skewX(30deg);opacity:0}}@keyframes lightSpeedOutRight{0%{opacity:1}to{-webkit-transform:translate3d(100%,0,0) skewX(30deg);transform:translate3d(100%,0,0) skewX(30deg);opacity:0}}.animate__lightSpeedOutRight{-webkit-animation-name:lightSpeedOutRight;animation-name:lightSpeedOutRight;-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}@-webkit-keyframes lightSpeedOutLeft{0%{opacity:1}to{-webkit-transform:translate3d(-100%,0,0) skewX(-30deg);transform:translate3d(-100%,0,0) skewX(-30deg);opacity:0}}@keyframes lightSpeedOutLeft{0%{opacity:1}to{-webkit-transform:translate3d(-100%,0,0) skewX(-30deg);transform:translate3d(-100%,0,0) skewX(-30deg);opacity:0}}.animate__lightSpeedOutLeft{-webkit-animation-name:lightSpeedOutLeft;animation-name:lightSpeedOutLeft;-webkit-animation-timing-function:ease-in;animation-timing-function:ease-in}@-webkit-keyframes rotateIn{0%{-webkit-transform:rotate(-200deg);transform:rotate(-200deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}@keyframes rotateIn{0%{-webkit-transform:rotate(-200deg);transform:rotate(-200deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}.animate__rotateIn{-webkit-animation-name:rotateIn;animation-name:rotateIn;-webkit-transform-origin:center;transform-origin:center}@-webkit-keyframes rotateInDownLeft{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}@keyframes rotateInDownLeft{0%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}.animate__rotateInDownLeft{-webkit-animation-name:rotateInDownLeft;animation-name:rotateInDownLeft;-webkit-transform-origin:left bottom;transform-origin:left bottom}@-webkit-keyframes rotateInDownRight{0%{-webkit-transform:rotate(45deg);transform:rotate(45deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}@keyframes rotateInDownRight{0%{-webkit-transform:rotate(45deg);transform:rotate(45deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}.animate__rotateInDownRight{-webkit-animation-name:rotateInDownRight;animation-name:rotateInDownRight;-webkit-transform-origin:right bottom;transform-origin:right bottom}@-webkit-keyframes rotateInUpLeft{0%{-webkit-transform:rotate(45deg);transform:rotate(45deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}@keyframes rotateInUpLeft{0%{-webkit-transform:rotate(45deg);transform:rotate(45deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}.animate__rotateInUpLeft{-webkit-animation-name:rotateInUpLeft;animation-name:rotateInUpLeft;-webkit-transform-origin:left bottom;transform-origin:left bottom}@-webkit-keyframes rotateInUpRight{0%{-webkit-transform:rotate(-90deg);transform:rotate(-90deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}@keyframes rotateInUpRight{0%{-webkit-transform:rotate(-90deg);transform:rotate(-90deg);opacity:0}to{-webkit-transform:translateZ(0);transform:translateZ(0);opacity:1}}.animate__rotateInUpRight{-webkit-animation-name:rotateInUpRight;animation-name:rotateInUpRight;-webkit-transform-origin:right bottom;transform-origin:right bottom}@-webkit-keyframes rotateOut{0%{opacity:1}to{-webkit-transform:rotate(200deg);transform:rotate(200deg);opacity:0}}@keyframes rotateOut{0%{opacity:1}to{-webkit-transform:rotate(200deg);transform:rotate(200deg);opacity:0}}.animate__rotateOut{-webkit-animation-name:rotateOut;animation-name:rotateOut;-webkit-transform-origin:center;transform-origin:center}@-webkit-keyframes rotateOutDownLeft{0%{opacity:1}to{-webkit-transform:rotate(45deg);transform:rotate(45deg);opacity:0}}@keyframes rotateOutDownLeft{0%{opacity:1}to{-webkit-transform:rotate(45deg);transform:rotate(45deg);opacity:0}}.animate__rotateOutDownLeft{-webkit-animation-name:rotateOutDownLeft;animation-name:rotateOutDownLeft;-webkit-transform-origin:left bottom;transform-origin:left bottom}@-webkit-keyframes rotateOutDownRight{0%{opacity:1}to{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);opacity:0}}@keyframes rotateOutDownRight{0%{opacity:1}to{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);opacity:0}}.animate__rotateOutDownRight{-webkit-animation-name:rotateOutDownRight;animation-name:rotateOutDownRight;-webkit-transform-origin:right bottom;transform-origin:right bottom}@-webkit-keyframes rotateOutUpLeft{0%{opacity:1}to{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);opacity:0}}@keyframes rotateOutUpLeft{0%{opacity:1}to{-webkit-transform:rotate(-45deg);transform:rotate(-45deg);opacity:0}}.animate__rotateOutUpLeft{-webkit-animation-name:rotateOutUpLeft;animation-name:rotateOutUpLeft;-webkit-transform-origin:left bottom;transform-origin:left bottom}@-webkit-keyframes rotateOutUpRight{0%{opacity:1}to{-webkit-transform:rotate(90deg);transform:rotate(90deg);opacity:0}}@keyframes rotateOutUpRight{0%{opacity:1}to{-webkit-transform:rotate(90deg);transform:rotate(90deg);opacity:0}}.animate__rotateOutUpRight{-webkit-animation-name:rotateOutUpRight;animation-name:rotateOutUpRight;-webkit-transform-origin:right bottom;transform-origin:right bottom}@-webkit-keyframes hinge{0%{-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}20%,60%{-webkit-transform:rotate(80deg);transform:rotate(80deg);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}40%,80%{-webkit-transform:rotate(60deg);transform:rotate(60deg);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out;opacity:1}to{-webkit-transform:translate3d(0,700px,0);transform:translate3d(0,700px,0);opacity:0}}@keyframes hinge{0%{-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}20%,60%{-webkit-transform:rotate(80deg);transform:rotate(80deg);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out}40%,80%{-webkit-transform:rotate(60deg);transform:rotate(60deg);-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out;opacity:1}to{-webkit-transform:translate3d(0,700px,0);transform:translate3d(0,700px,0);opacity:0}}.animate__hinge{-webkit-animation-duration:2s;animation-duration:2s;-webkit-animation-duration:calc(var(--animate-duration)*2);animation-duration:calc(var(--animate-duration)*2);-webkit-animation-name:hinge;animation-name:hinge;-webkit-transform-origin:top left;transform-origin:top left}@-webkit-keyframes jackInTheBox{0%{opacity:0;-webkit-transform:scale(.1) rotate(30deg);transform:scale(.1) rotate(30deg);-webkit-transform-origin:center bottom;transform-origin:center bottom}50%{-webkit-transform:rotate(-10deg);transform:rotate(-10deg)}70%{-webkit-transform:rotate(3deg);transform:rotate(3deg)}to{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}@keyframes jackInTheBox{0%{opacity:0;-webkit-transform:scale(.1) rotate(30deg);transform:scale(.1) rotate(30deg);-webkit-transform-origin:center bottom;transform-origin:center bottom}50%{-webkit-transform:rotate(-10deg);transform:rotate(-10deg)}70%{-webkit-transform:rotate(3deg);transform:rotate(3deg)}to{opacity:1;-webkit-transform:scale(1);transform:scale(1)}}.animate__jackInTheBox{-webkit-animation-name:jackInTheBox;animation-name:jackInTheBox}@-webkit-keyframes rollIn{0%{opacity:0;-webkit-transform:translate3d(-100%,0,0) rotate(-120deg);transform:translate3d(-100%,0,0) rotate(-120deg)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes rollIn{0%{opacity:0;-webkit-transform:translate3d(-100%,0,0) rotate(-120deg);transform:translate3d(-100%,0,0) rotate(-120deg)}to{opacity:1;-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__rollIn{-webkit-animation-name:rollIn;animation-name:rollIn}@-webkit-keyframes rollOut{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(100%,0,0) rotate(120deg);transform:translate3d(100%,0,0) rotate(120deg)}}@keyframes rollOut{0%{opacity:1}to{opacity:0;-webkit-transform:translate3d(100%,0,0) rotate(120deg);transform:translate3d(100%,0,0) rotate(120deg)}}.animate__rollOut{-webkit-animation-name:rollOut;animation-name:rollOut}@-webkit-keyframes zoomIn{0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes zoomIn{0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}50%{opacity:1}}.animate__zoomIn{-webkit-animation-name:zoomIn;animation-name:zoomIn}@-webkit-keyframes zoomInDown{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,-1000px,0);transform:scale3d(.1,.1,.1) translate3d(0,-1000px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,60px,0);transform:scale3d(.475,.475,.475) translate3d(0,60px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}@keyframes zoomInDown{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,-1000px,0);transform:scale3d(.1,.1,.1) translate3d(0,-1000px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,60px,0);transform:scale3d(.475,.475,.475) translate3d(0,60px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.animate__zoomInDown{-webkit-animation-name:zoomInDown;animation-name:zoomInDown}@-webkit-keyframes zoomInLeft{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(-1000px,0,0);transform:scale3d(.1,.1,.1) translate3d(-1000px,0,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(10px,0,0);transform:scale3d(.475,.475,.475) translate3d(10px,0,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}@keyframes zoomInLeft{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(-1000px,0,0);transform:scale3d(.1,.1,.1) translate3d(-1000px,0,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(10px,0,0);transform:scale3d(.475,.475,.475) translate3d(10px,0,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.animate__zoomInLeft{-webkit-animation-name:zoomInLeft;animation-name:zoomInLeft}@-webkit-keyframes zoomInRight{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(1000px,0,0);transform:scale3d(.1,.1,.1) translate3d(1000px,0,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(-10px,0,0);transform:scale3d(.475,.475,.475) translate3d(-10px,0,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}@keyframes zoomInRight{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(1000px,0,0);transform:scale3d(.1,.1,.1) translate3d(1000px,0,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(-10px,0,0);transform:scale3d(.475,.475,.475) translate3d(-10px,0,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.animate__zoomInRight{-webkit-animation-name:zoomInRight;animation-name:zoomInRight}@-webkit-keyframes zoomInUp{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,1000px,0);transform:scale3d(.1,.1,.1) translate3d(0,1000px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}@keyframes zoomInUp{0%{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,1000px,0);transform:scale3d(.1,.1,.1) translate3d(0,1000px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}60%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.animate__zoomInUp{-webkit-animation-name:zoomInUp;animation-name:zoomInUp}@-webkit-keyframes zoomOut{0%{opacity:1}50%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}to{opacity:0}}@keyframes zoomOut{0%{opacity:1}50%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}to{opacity:0}}.animate__zoomOut{-webkit-animation-name:zoomOut;animation-name:zoomOut}@-webkit-keyframes zoomOutDown{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}to{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,2000px,0);transform:scale3d(.1,.1,.1) translate3d(0,2000px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}@keyframes zoomOutDown{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);transform:scale3d(.475,.475,.475) translate3d(0,-60px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}to{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,2000px,0);transform:scale3d(.1,.1,.1) translate3d(0,2000px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.animate__zoomOutDown{-webkit-animation-name:zoomOutDown;animation-name:zoomOutDown;-webkit-transform-origin:center bottom;transform-origin:center bottom}@-webkit-keyframes zoomOutLeft{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(42px,0,0);transform:scale3d(.475,.475,.475) translate3d(42px,0,0)}to{opacity:0;-webkit-transform:scale(.1) translate3d(-2000px,0,0);transform:scale(.1) translate3d(-2000px,0,0)}}@keyframes zoomOutLeft{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(42px,0,0);transform:scale3d(.475,.475,.475) translate3d(42px,0,0)}to{opacity:0;-webkit-transform:scale(.1) translate3d(-2000px,0,0);transform:scale(.1) translate3d(-2000px,0,0)}}.animate__zoomOutLeft{-webkit-animation-name:zoomOutLeft;animation-name:zoomOutLeft;-webkit-transform-origin:left center;transform-origin:left center}@-webkit-keyframes zoomOutRight{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(-42px,0,0);transform:scale3d(.475,.475,.475) translate3d(-42px,0,0)}to{opacity:0;-webkit-transform:scale(.1) translate3d(2000px,0,0);transform:scale(.1) translate3d(2000px,0,0)}}@keyframes zoomOutRight{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(-42px,0,0);transform:scale3d(.475,.475,.475) translate3d(-42px,0,0)}to{opacity:0;-webkit-transform:scale(.1) translate3d(2000px,0,0);transform:scale(.1) translate3d(2000px,0,0)}}.animate__zoomOutRight{-webkit-animation-name:zoomOutRight;animation-name:zoomOutRight;-webkit-transform-origin:right center;transform-origin:right center}@-webkit-keyframes zoomOutUp{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,60px,0);transform:scale3d(.475,.475,.475) translate3d(0,60px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}to{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,-2000px,0);transform:scale3d(.1,.1,.1) translate3d(0,-2000px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}@keyframes zoomOutUp{40%{opacity:1;-webkit-transform:scale3d(.475,.475,.475) translate3d(0,60px,0);transform:scale3d(.475,.475,.475) translate3d(0,60px,0);-webkit-animation-timing-function:cubic-bezier(.55,.055,.675,.19);animation-timing-function:cubic-bezier(.55,.055,.675,.19)}to{opacity:0;-webkit-transform:scale3d(.1,.1,.1) translate3d(0,-2000px,0);transform:scale3d(.1,.1,.1) translate3d(0,-2000px,0);-webkit-animation-timing-function:cubic-bezier(.175,.885,.32,1);animation-timing-function:cubic-bezier(.175,.885,.32,1)}}.animate__zoomOutUp{-webkit-animation-name:zoomOutUp;animation-name:zoomOutUp;-webkit-transform-origin:center bottom;transform-origin:center bottom}@-webkit-keyframes slideInDown{0%{-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes slideInDown{0%{-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__slideInDown{-webkit-animation-name:slideInDown;animation-name:slideInDown}@-webkit-keyframes slideInLeft{0%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes slideInLeft{0%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__slideInLeft{-webkit-animation-name:slideInLeft;animation-name:slideInLeft}@-webkit-keyframes slideInRight{0%{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes slideInRight{0%{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__slideInRight{-webkit-animation-name:slideInRight;animation-name:slideInRight}@-webkit-keyframes slideInUp{0%{-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}@keyframes slideInUp{0%{-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0);visibility:visible}to{-webkit-transform:translateZ(0);transform:translateZ(0)}}.animate__slideInUp{-webkit-animation-name:slideInUp;animation-name:slideInUp}@-webkit-keyframes slideOutDown{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}}@keyframes slideOutDown{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(0,100%,0);transform:translate3d(0,100%,0)}}.animate__slideOutDown{-webkit-animation-name:slideOutDown;animation-name:slideOutDown}@-webkit-keyframes slideOutLeft{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}@keyframes slideOutLeft{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}.animate__slideOutLeft{-webkit-animation-name:slideOutLeft;animation-name:slideOutLeft}@-webkit-keyframes slideOutRight{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}}@keyframes slideOutRight{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}}.animate__slideOutRight{-webkit-animation-name:slideOutRight;animation-name:slideOutRight}@-webkit-keyframes slideOutUp{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}}@keyframes slideOutUp{0%{-webkit-transform:translateZ(0);transform:translateZ(0)}to{visibility:hidden;-webkit-transform:translate3d(0,-100%,0);transform:translate3d(0,-100%,0)}}.animate__slideOutUp{-webkit-animation-name:slideOutUp;animation-name:slideOutUp}
xyhp915/logseq-assets-plus
28
A Logseq plugin to enhance assets features 🚀
TypeScript
xyhp915
Charlie
logseq
libs/uFuzzy.iife.min.js
JavaScript
/*! https://github.com/leeoniya/uFuzzy (v1.0.10) */ window.uFuzzy=function(){"use strict";const e=new Intl.Collator("en").compare,t=1/0,l=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n="eexxaacctt",r=(e,t,l)=>e.replace("A-Z",t).replace("a-z",l),i={unicode:!1,alpha:null,interSplit:"[^A-Za-z\\d']+",intraSplit:"[a-z][A-Z]",intraBound:"[A-Za-z]\\d|\\d[A-Za-z]|[a-z][A-Z]",interLft:0,interRgt:0,interChars:".",interIns:t,intraChars:"[a-z\\d']",intraIns:0,intraContr:"'[a-z]{1,2}\\b",intraMode:0,intraSlice:[1,t],intraSub:0,intraTrn:0,intraDel:0,intraFilt:()=>!0,sort:(t,l)=>{let{idx:n,chars:r,terms:i,interLft2:s,interLft1:a,start:g,intraIns:h,interIns:f}=t;return n.map(((e,t)=>t)).sort(((t,u)=>r[u]-r[t]||h[t]-h[u]||i[u]+s[u]+.5*a[u]-(i[t]+s[t]+.5*a[t])||f[t]-f[u]||g[t]-g[u]||e(l[n[t]],l[n[u]])))}},s=(e,l)=>0==l?"":1==l?e+"??":l==t?e+"*?":e+`{0,${l}}?`,a="(?:\\b|_)";function g(e){e=Object.assign({},i,e);let{unicode:t,interLft:g,interRgt:h,intraMode:u,intraSlice:c,intraIns:o,intraSub:p,intraTrn:x,intraDel:m,intraContr:d,intraSplit:R,interSplit:b,intraBound:L,intraChars:S}=e,A=e.letters??e.alpha;if(null!=A){let e=A.toLocaleUpperCase(),t=A.toLocaleLowerCase();b=r(b,e,t),R=r(R,e,t),L=r(L,e,t),S=r(S,e,t),d=r(d,e,t)}let E=t?"u":"";const I='".+?"',C=RegExp(I,"gi"+E),z=RegExp(`(?:\\s+|^)-(?:${S}+|${I})`,"gi"+E);let{intraRules:k}=e;null==k&&(k=e=>{let t=i.intraSlice,l=0,n=0,r=0,s=0,a=e.length;return a>4?(t=c,l=o,n=p,r=x,s=m):3>a||(r=Math.min(x,1),4==a&&(l=Math.min(o,1))),{intraSlice:t,intraIns:l,intraSub:n,intraTrn:r,intraDel:s}});let y=!!R,j=RegExp(R,"g"+E),$=RegExp(b,"g"+E),w=RegExp("^"+b+"|"+b+"$","g"+E),Z=RegExp(d,"gi"+E);const M=e=>{let t=[];e=(e=e.replace(C,(e=>(t.push(e),n)))).replace(w,"").toLocaleLowerCase(),y&&(e=e.replace(j,(e=>e[0]+" "+e[1])));let l=0;return e.split($).filter((e=>""!=e)).map((e=>e===n?t[l++]:e))},D=(t,n=0,r=!1)=>{let i=M(t);if(0==i.length)return[];let f,c=Array(i.length).fill("");if(i=i.map(((e,t)=>e.replace(Z,(e=>(c[t]=e,""))))),1==u)f=i.map(((e,t)=>{let{intraSlice:n,intraIns:r,intraSub:i,intraTrn:a,intraDel:g}=k(e);if(r+i+a+g==0)return e+c[t];if('"'===e[0])return l(e.slice(1,-1));let[h,f]=n,u=e.slice(0,h),o=e.slice(f),p=e.slice(h,f);1==r&&1==u.length&&u!=p[0]&&(u+="(?!"+u+")");let x=p.length,m=[e];if(i)for(let e=0;x>e;e++)m.push(u+p.slice(0,e)+S+p.slice(e+1)+o);if(a)for(let e=0;x-1>e;e++)p[e]!=p[e+1]&&m.push(u+p.slice(0,e)+p[e+1]+p[e]+p.slice(e+2)+o);if(g)for(let e=0;x>e;e++)m.push(u+p.slice(0,e+1)+"?"+p.slice(e+1)+o);if(r){let e=s(S,1);for(let t=0;x>t;t++)m.push(u+p.slice(0,t)+e+p.slice(t)+o)}return"(?:"+m.join("|")+")"+c[t]}));else{let e=s(S,o);2==n&&o>0&&(e=")("+e+")("),f=i.map(((t,n)=>'"'===t[0]?l(t.slice(1,-1)):t.split("").map(((e,t,l)=>(1==o&&0==t&&l.length>1&&e!=l[t+1]&&(e+="(?!"+e+")"),e))).join(e)+c[n]))}let p=2==g?a:"",x=2==h?a:"",m=x+s(e.interChars,e.interIns)+p;return n>0?r?f=p+"("+f.join(")"+x+"|"+p+"(")+")"+x:(f="("+f.join(")("+m+")(")+")",f="(.??"+p+")"+f+"("+x+".*)"):(f=f.join(m),f=p+f+x),[RegExp(f,"i"+E),i,c]},T=(e,t,l)=>{let[n]=D(t);if(null==n)return null;let r=[];if(null!=l)for(let t=0;l.length>t;t++){let i=l[t];n.test(e[i])&&r.push(i)}else for(let t=0;e.length>t;t++)n.test(e[t])&&r.push(t);return r};let F=!!L,O=RegExp(b,E),B=RegExp(L,E);const U=(t,l,n)=>{let[r,i,s]=D(n,1),[a]=D(n,2),f=i.length,u=t.length,c=Array(u).fill(0),o={idx:Array(u),start:c.slice(),chars:c.slice(),terms:c.slice(),interIns:c.slice(),intraIns:c.slice(),interLft2:c.slice(),interRgt2:c.slice(),interLft1:c.slice(),interRgt1:c.slice(),ranges:Array(u)},p=1==g||1==h,x=0;for(let n=0;t.length>n;n++){let u=l[t[n]],c=u.match(r),m=c.index+c[1].length,d=m,R=!1,b=0,L=0,S=0,A=0,I=0,C=0,z=0,k=0,y=[];for(let t=0,l=2;f>t;t++,l+=2){let n=c[l].toLocaleLowerCase(),r=i[t],a='"'==r[0]?r.slice(1,-1):r+s[t],o=a.length,x=n.length,j=n==a;if(!j&&c[l+1].length>=o){let e=c[l+1].toLocaleLowerCase().indexOf(a);e>-1&&(y.push(d,x,e,o),d+=v(c,l,e,o),n=a,x=o,j=!0,0==t&&(m=d))}if(p||j){let e=d-1,r=d+x,i=!1,s=!1;if(-1==e||O.test(u[e]))j&&b++,i=!0;else{if(2==g){R=!0;break}if(F&&B.test(u[e]+u[e+1]))j&&L++,i=!0;else if(1==g){let e=c[l+1],r=d+x;if(e.length>=o){let s,g=0,h=!1,f=RegExp(a,"ig"+E);for(;s=f.exec(e);){g=s.index;let e=r+g,t=e-1;if(-1==t||O.test(u[t])){b++,h=!0;break}if(B.test(u[t]+u[e])){L++,h=!0;break}}h&&(i=!0,y.push(d,x,g,o),d+=v(c,l,g,o),n=a,x=o,j=!0,0==t&&(m=d))}if(!i){R=!0;break}}}if(r==u.length||O.test(u[r]))j&&S++,s=!0;else{if(2==h){R=!0;break}if(F&&B.test(u[r-1]+u[r]))j&&A++,s=!0;else if(1==h){R=!0;break}}j&&(I+=o,i&&s&&C++)}if(x>o&&(k+=x-o),t>0&&(z+=c[l-1].length),!e.intraFilt(a,n,d)){R=!0;break}f-1>t&&(d+=x+c[l+1].length)}if(!R){o.idx[x]=t[n],o.interLft2[x]=b,o.interLft1[x]=L,o.interRgt2[x]=S,o.interRgt1[x]=A,o.chars[x]=I,o.terms[x]=C,o.interIns[x]=z,o.intraIns[x]=k,o.start[x]=m;let e=u.match(a),l=e.index+e[1].length,r=y.length,i=r>0?0:1/0,s=r-4;for(let t=2;e.length>t;)if(i>s||y[i]!=l)l+=e[t].length,t++;else{let n=y[i+1],r=y[i+2],s=y[i+3],a=t,g="";for(let t=0;n>t;a++)g+=e[a],t+=e[a].length;e.splice(t,a-t,g),l+=v(e,t,r,s),i+=4}l=e.index+e[1].length;let g=o.ranges[x]=[],h=l,f=l;for(let t=2;e.length>t;t++){let n=e[t].length;l+=n,t%2==0?f=l:n>0&&(g.push(h,f),h=f=l)}f>h&&g.push(h,f),x++}}if(t.length>x)for(let e in o)o[e]=o[e].slice(0,x);return o},v=(e,t,l,n)=>{let r=e[t]+e[t+1].slice(0,l);return e[t-1]+=r,e[t]=e[t+1].slice(l,l+n),e[t+1]=e[t+1].slice(l+n),r.length};return{search:(...t)=>((t,n,r,i=1e3,s)=>{r=r?!0===r?5:r:0;let a=null,g=null,h=[];n=n.replace(z,(e=>{let t=e.trim().slice(1);return'"'===t[0]&&(t=l(t.slice(1,-1))),h.push(t),""}));let u,c=M(n);if(h.length>0){if(u=RegExp(h.join("|"),"i"+E),0==c.length){let e=[];for(let l=0;t.length>l;l++)u.test(t[l])||e.push(l);return[e,null,null]}}else if(0==c.length)return[null,null,null];if(r>0){let e=M(n);if(e.length>1){let l=e.slice().sort(((e,t)=>t.length-e.length));for(let e=0;l.length>e;e++){if(0==s?.length)return[[],null,null];s=T(t,l[e],s)}if(e.length>r)return[s,null,null];a=f(e).map((e=>e.join(" "))),g=[];let n=new Set;for(let e=0;a.length>e;e++)if(s.length>n.size){let l=s.filter((e=>!n.has(e))),r=T(t,a[e],l);for(let e=0;r.length>e;e++)n.add(r[e]);g.push(r)}else g.push([])}}null==a&&(a=[n],g=[s?.length>0?s:T(t,n)]);let o=null,p=null;if(h.length>0&&(g=g.map((e=>e.filter((e=>!u.test(t[e])))))),i>=g.reduce(((e,t)=>e+t.length),0)){o={},p=[];for(let l=0;g.length>l;l++){let n=g[l];if(null==n||0==n.length)continue;let r=a[l],i=U(n,t,r),s=e.sort(i,t,r);if(l>0)for(let e=0;s.length>e;e++)s[e]+=p.length;for(let e in i)o[e]=(o[e]??[]).concat(i[e]);p=p.concat(s)}}return[[].concat(...g),o,p]})(...t),split:M,filter:T,info:U,sort:e.sort}}const h=(()=>{let e={A:"ÁÀÃÂÄĄ",a:"áàãâäą",E:"ÉÈÊËĖ",e:"éèêëę",I:"ÍÌÎÏĮ",i:"íìîïį",O:"ÓÒÔÕÖ",o:"óòôõö",U:"ÚÙÛÜŪŲ",u:"úùûüūų",C:"ÇČ",c:"çč",N:"Ñ",n:"ñ",S:"Š",s:"š"},t=new Map,l="";for(let n in e)e[n].split("").forEach((e=>{l+=e,t.set(e,n)}));let n=RegExp(`[${l}]`,"g"),r=e=>t.get(e);return e=>{if("string"==typeof e)return e.replace(n,r);let t=Array(e.length);for(let l=0;e.length>l;l++)t[l]=e[l].replace(n,r);return t}})();function f(e){let t,l,n=(e=e.slice()).length,r=[e.slice()],i=Array(n).fill(0),s=1;for(;n>s;)s>i[s]?(t=s%2&&i[s],l=e[s],e[s]=e[t],e[t]=l,++i[s],s=1,r.push(e.slice())):(i[s]=0,++s);return r}const u=(e,t)=>t?`<mark>${e}</mark>`:e,c=(e,t)=>e+t;return g.latinize=h,g.permute=e=>f([...Array(e.length).keys()]).sort(((e,t)=>{for(let l=0;e.length>l;l++)if(e[l]!=t[l])return e[l]-t[l];return 0})).map((t=>t.map((t=>e[t])))),g.highlight=function(e,t,l=u,n="",r=c){n=r(n,l(e.substring(0,t[0]),!1))??n;for(let i=0;t.length>i;i+=2)n=r(n,l(e.substring(t[i],t[i+1]),!0))??n,t.length-3>i&&(n=r(n,l(e.substring(t[i+1],t[i+2]),!1))??n);return r(n,l(e.substring(t[t.length-1]),!1))??n},g}();
xyhp915/logseq-assets-plus
28
A Logseq plugin to enhance assets features 🚀
TypeScript
xyhp915
Charlie
logseq
src/index.css
CSS
:root, html { --ls-primary-background-color: #ffffff; --ls-secondary-background-color: #f7f7f7; --ls-tertiary-background-color: #eaeaea; --ls-quaternary-background-color: #dcdcdc; --ls-active-primary-color: rgb(0, 105, 182); --ls-active-secondary-color: #00477c; --ls-border-color: #ccc; --ls-secondary-border-color: #e2e2e2; --ls-tertiary-border-color: rgba(200, 200, 200, 0.3); --ls-primary-text-color: #433f38; --ls-secondary-text-color: #161e2e; /*--ls-block-highlight-color: --ls-quaternary-background-color;*/ } html[data-theme='dark'] { --ls-primary-background-color: #002b36; --ls-secondary-background-color: #023643; --ls-tertiary-background-color: #08404f; --ls-quaternary-background-color: #094b5a; --ls-active-primary-color: #8ec2c2; --ls-active-secondary-color: #d0e8e8; --ls-border-color: #0e5263; --ls-secondary-border-color: #126277; --ls-tertiary-border-color: rgba(0, 2, 0, 0.1); --ls-primary-text-color: #a4b5b6; --ls-secondary-text-color: #dfdfdf; } body { padding: 0; margin: 0; box-sizing: border-box; font-family: sans-serif; color: var(--ls-primary-text-color); width: 100vw; height: 100vh; overflow-x: hidden; position: relative; } body.as-full:after { content: " "; position: absolute; width: 100%; height: 100%; background-color: rgba(241, 241, 241, 0.5); opacity: .6; } html[data-theme='dark'] body.as-full:after { background-image: linear-gradient(to bottom, var(--ls-primary-background-color), var(--ls-quaternary-background-color)); } ul { list-style: none; margin: 0; padding: 0; } marker { background-color: #eeb41e; } .search-input-container { min-width: 480px; max-width: 560px; min-height: 240px; border-radius: 8px; overflow: hidden; border: 1px solid var(--ls-border-color); box-shadow: 0 0 8px var(--ls-border-color); background-color: var(--ls-primary-background-color); display: flex; flex-direction: column; position: absolute; top: 0; left: 0; visibility: hidden; transition: opacity .3s; opacity: 0; z-index: 10; } html[data-theme=dark] .search-input-container { box-shadow: none; } body.as-full .search-input-container { width: 80vw; max-width: 620px; } .search-input-container.animate__defaultIn { visibility: visible; transition: opacity .3s; opacity: 1; } .search-input-head { display: flex; align-items: center; padding-bottom: 10px; margin: 12px 15px 0; position: relative; } .search-input-head:focus-within { } .search-input-head .icon-wrap { position: absolute; top: 2px; left: 4px; opacity: .4; } .search-input-head:focus-within .icon-wrap { opacity: .9; } .search-input-head .input-wrap { display: flex; width: 100%; } .search-input-head .input-wrap input { padding: 8px 8px 8px 36px; flex: 1; border: none; font-size: 16px; outline: none; background: transparent; color: var(--ls-primary-text-color); } .search-input-list-wrap { max-height: calc(60vh); overflow-y: auto; } .search-input-list-wrap .loading, .search-input-list-wrap .nothing { display: flex; justify-content: center; align-items: center; padding-top: 40px; } .search-input-list-wrap .nothing { color: lightgray; font-size: 14px; } .search-input-list { list-style: none; margin: 0; padding: 9px 0 10px; } .search-input-list .list-item { display: flex; cursor: pointer; user-select: none; white-space: break-spaces; word-break: break-all; transition: background-color .3s; position: relative; overflow: hidden; } .search-input-list .list-item:after { content: " "; position: absolute; bottom: 0; left: 15px; right: 15px; /*border-bottom: 1px solid var(--ls-border-color);*/ height: 0; overflow: hidden; } html[data-theme='dark'] .search-input-list .list-item:after { display: none; } .search-input-list .list-item:last-child:after { border-bottom: none; } .search-input-list .list-item.active { background-color: var(--ls-tertiary-background-color); } .search-input-list .list-item:active { opacity: .7; } .search-input-list .list-item .l { width: 40px; height: 40px; background-color: aliceblue; border-radius: 100%; overflow: hidden; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 10px; opacity: .8; margin: 12px 15px; } .search-input-list .list-item .r { display: flex; flex-direction: column; flex: 1; font-size: 15px; position: relative; overflow: hidden; top: 15px; } .search-input-list .list-item .r strong { width: 95%; font-weight: 500; opacity: .85; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; line-height: 16px; } .search-input-list .list-item.active .r strong, .search-input-list .list-item:hover .r strong { opacity: 1; } .search-input-list .list-item .r p { margin: 0; padding: 4px 0; font-size: 12px; color: #b9b9b9; } .search-input-list .list-item .r .ctrls { position: absolute; right: 10px; top: 4px; padding: 10px; opacity: .6; visibility: hidden; } .search-input-list .list-item .r .ctrls:hover { opacity: 1; } .search-input-list .list-item:hover .ctrls { visibility: visible; } .search-input-tabs { -webkit-font-smoothing: antialiased; display: flex; border-bottom: 2px solid var(--ls-border-color); padding-left: 20px; padding-right: 15px; position: relative; } .search-input-tabs li { user-select: none; padding: 10px 15px; display: flex; justify-content: center; align-items: center; margin-right: 4px; margin-bottom: -2px; font-size: 15px; border-bottom: 2px solid transparent; color: var(--ls-primary-text-color); opacity: .4; } .search-input-tabs li.settings-dropdown { position: absolute; top: -1px; right: -2px; z-index: 1; opacity: 1 !important; } .search-input-tabs li.settings-dropdown > span { cursor: pointer; user-select: none; opacity: .5; } .search-input-tabs li.settings-dropdown > span:active { opacity: .9; } .settings-dropdown-content { position: absolute; top: 32px; right: 10px; width: 168px; border-radius: 8px; overflow: hidden; border: 1px solid var(--ls-border-color); box-shadow: 0 0 8px var(--ls-border-color); background-color: var(--ls-primary-background-color); padding: 6px; } html[data-theme=dark] .settings-dropdown-content { box-shadow: none; } .settings-dropdown-content > .item { padding: 6px 0; display: flex; align-items: center; border-radius: 6px; } .settings-dropdown-content > .item.as-link:hover { cursor: pointer; background-color: var(--ls-tertiary-background-color); } .settings-dropdown-content > .item > span { position: relative; top: 1px; padding-left: 8px; opacity: .6; } .settings-dropdown-content > .item > strong { font-weight: 400; font-size: 16px; padding: 0 6px; } .search-input-tabs li.active { color: var(--ls-primary-text-color); opacity: 1; border-bottom-color: var(--ls-primary-text-color); } html[data-theme=dark] .search-input-tabs li.active { border-bottom-color: var(--ls-secondary-border-color); } .search-input-tabs li > strong { font-weight: 400; } .search-input-tabs li > svg { margin-right: 5px; } .search-input-tabs li > code { font-size: 11px; line-height: 1; background-color: var(--ls-secondary-background-color); color: var(--ls-primary-text-color); border-radius: 6px; margin-left: 6px; padding: 3px; font-weight: 600; } .search-input-tabs li:hover { color: var(--ls-primary-text-color); opacity: .8; } .search-input-tabs li.active > strong { font-weight: 600; }
xyhp915/logseq-assets-plus
28
A Logseq plugin to enhance assets features 🚀
TypeScript
xyhp915
Charlie
logseq
src/index.tsx
TypeScript (TSX)
import './index.css' import 'react-virtualized/styles.css' import '@logseq/libs' import { render } from 'preact' import { useEffect, useRef, useState } from 'preact/hooks' import cx from 'classnames' import { ArrowsClockwise, Books, Faders, FileAudio, Folder, Images, ListMagnifyingGlass, Prohibit } from '@phosphor-icons/react' import { AutoSizer, List } from 'react-virtualized' import { MoonLoader } from 'react-spinners' import { LSPluginBaseInfo } from '@logseq/libs/dist/LSPlugin' import normalizePath from 'normalize-path' import { setup as l10nSetup, t } from 'logseq-l10n' //https://github.com/sethyuan/logseq-l10n import ja from './translations/ja.json' import zhCN from './translations/zh-CN.json' import zhHant from './translations/zh-Hant.json' import ko from './translations/ko.json' const imageFormats = ['png', 'jpg', 'jpeg', 'webp', 'gif'] const bookFormats = ['pdf'] const documentFormats = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'md', 'txt', 'html', 'htm', 'csv'] const videoFormats = ['mp4', 'avi', 'mov', 'wmv', 'flv', '3gp', 'mpeg', 'mpg', 'ts', 'm4v'] const audioFormats = ['mp3', 'wav', 'ogg', 'flac', 'wma'] const tabTypes = { 'documents': [...bookFormats, ...documentFormats], 'audios': audioFormats, 'images': imageFormats } const makeMdAssetLink = ({ name, path, normalizePath, extname }) => { if (!name || !path) return path = normalizePath.split('/assets/')?.[1] if (!path) return const isSupportedRichExt = [...imageFormats, ...bookFormats, ...audioFormats, ...videoFormats] .includes(extname?.toLowerCase()) return `${isSupportedRichExt ? '!' : ''}[${name}](assets/${path})` } // TODO: use react-virtualized function ResultList({ data, inputValue, activeItemIdx, onSelect }) { if (!data?.length) return ( <div className={'nothing'}> <Prohibit size={16}/> <p>{t('No results')}</p> </div>) const rowRenderer = ({ index, key, style }) => { const it = data[index] let name = it.name // highlight matched text if (it.ranges?.length && inputValue?.length) { const ranges = it.ranges.map((range, n) => { if (n === 0) return name.substring(0, range) const ret = name.substring(it.ranges[n - 1], range) return n % 2 === 0 ? ret : `<marker>${ret}</marker>` }) const lastIdx = it.ranges[it.ranges.length - 1] if (lastIdx < name.length) { ranges.push(name.substring(lastIdx)) } name = ranges.join('') } return ( <div key={key} style={style} title={t('Insert this asset at the cursor position. If that position doesn\'t exist, open this file on the OS.')} data-index={index} className={cx('list-item', index === activeItemIdx && 'active')} onClick={(e) => { e.stopPropagation() onSelect(it) }} > <div className="l">{it.extname?.toUpperCase()}</div> <div className="r"> <strong title={it.originalName} dangerouslySetInnerHTML={{ __html: name }}></strong> <p> {it.size} • {t('Modified')} {it.formatModifiedTime} </p> <span className="ctrls" title={t('Open the folder with the OS')}> <a onClick={(e) => { logseq.App.showItemInFolder(it.path) e.stopPropagation() }}> <Folder size={18} weight={'duotone'}/> </a> </span> </div> </div> ) } // TODO: dynamic size for responsive const listContainerSize = { width: 620, height: 500 } return ( <List className={'search-input-list'} autoWidth={true} rowCount={data.length} rowHeight={60} rowRenderer={rowRenderer} {...listContainerSize} ></List> ) } // normalize item data function normalizeDataItem(it) { if (!it.path) return // TODO: with relative full path it.normalizePath = normalizePath(it.path) it.name = it.normalizePath && it.normalizePath.substring(it.normalizePath.lastIndexOf('/') + 1) if (it.name?.startsWith('.')) { return } if (typeof it.name === 'string') { it.originalName = it.name it.name = it.name.length > 32 ? it.name.replace(/[0-9_.]{5,}(\.|$)/g, '$1') : it.name const extDotLastIdx = it.name.lastIndexOf('.') if (extDotLastIdx !== -1) { it.extname = it.name.substring(extDotLastIdx + 1) } } if (typeof it.size === 'number') { it.size = (it.size / 1024).toFixed(2) if (it.size > 999) { it.size = (it.size / 1024).toFixed(2) it.size += 'MB' } else { it.size += 'KB' } } if (typeof it.modifiedTime === 'number') { it.formatModifiedTime = (new Date(it.modifiedTime)).toLocaleString() } return it } function App() { const elRef = useRef<HTMLDivElement>(null) const [visible, setVisible] = useState(false) const [inputValue, setInputValue] = useState('') const [preparing, setPreparing] = useState(false) const [data, setData] = useState([]) const [_dataDirty, setDataDirty] = useState(false) const [currentListData, setCurrentListData] = useState([]) const [activeItemIdx, setActiveItemIdx] = useState(0) const tabs = ['all', 'documents', 'images', 'audios'] const [activeTab, setActiveTab] = useState(tabs[0]) const [activeSettings, setActiveSettings] = useState(false) const hasInputValue = !!inputValue?.trim() const isAllTab = activeTab === 'all' const isDocumentsTab = activeTab === 'documents' const isImagesTab = activeTab === 'images' const isAudiosTab = activeTab === 'audios' // const [asFullFeatures, setAsFullFeatures] = useState(false) // is full features pane const isAsFullFeatures = () => document.body.classList.contains('as-full') const resetActiveIdx = () => setActiveItemIdx(0) const upActiveIdx = () => { setCurrentListData((currentListData) => { setActiveItemIdx((activeItemIdx) => { if (!currentListData?.length) return 0 let toIdx = activeItemIdx - 1 if (toIdx < 0) toIdx = currentListData?.length - 1 return toIdx }) return currentListData }) } const downActiveIdx = () => { setCurrentListData((currentListData) => { setActiveItemIdx((activeItemIdx) => { if (!currentListData?.length) return 0 let toIdx = activeItemIdx + 1 if (toIdx >= currentListData?.length) toIdx = 0 return toIdx }) return currentListData }) } const closeUI = (opts: any = {}) => { logseq.hideMainUI(opts) setVisible(false) setActiveTab('all') resetActiveIdx() setInputValue('') document.body.classList.remove('as-full') } // select item const onSelect = async ( activeItem: any, options?: { isMetaKey?: boolean, isCtrlKey?: boolean } ) => { if (!activeItem) return const asFullFeatures = isAsFullFeatures() const { isMetaKey, isCtrlKey } = options || {} const builtInSupport = [...bookFormats] if (asFullFeatures) { if (!isCtrlKey && builtInSupport.includes(activeItem.extname?.toLowerCase())) { try { // @ts-ignore await logseq.Assets.builtInOpen(activeItem.path) return closeUI() } catch (error) { // Note: compatible with old version } } return logseq.App.openPath(activeItem.path) } closeUI() setInputValue('') logseq.Editor.insertAtEditingCursor( makeMdAssetLink(activeItem) ) } // load all assets data const doPrepareData = async () => { if (preparing) return setPreparing(true) const data = await logseq.Assets.listFilesOfCurrentGraph() data?.sort((a, b) => (b.modifiedTime || 0) - (a.modifiedTime || 0)) setData(data?.map(normalizeDataItem).filter(it => !!it)) setPreparing(false) } useEffect(() => { const el = elRef.current if (!el) return const handleClick = (e: MouseEvent) => { // check popup existed if (activeSettings) { setActiveSettings(false) return } const target = e.target as HTMLElement if (target && el.contains(target)) return closeUI() } const handleKeyup = (e: KeyboardEvent) => { if (e.key === 'Escape') { if (inputValue !== '') { return setInputValue('') } closeUI({ restoreEditingCursor: true }) return } if (e.ctrlKey && e.key === 'Tab') { const isShift = e.shiftKey const activeTabIdx = tabs.findIndex((v) => v === activeTab) let toIdx = activeTabIdx + (isShift ? -1 : 1) // move tab if (toIdx >= tabs.length) toIdx = 0 if (toIdx < 0) toIdx = (tabs.length - 1) setActiveTab(tabs[toIdx]) return } if (e.key === 'Enter') { const activeItem = currentListData?.[activeItemIdx] onSelect(activeItem, { isMetaKey: e.metaKey, isCtrlKey: e.ctrlKey }) return } } document.addEventListener('keyup', handleKeyup, false) document.addEventListener('click', handleClick, false) return () => { document.removeEventListener('keyup', handleKeyup) document.removeEventListener('click', handleClick) } }, [inputValue, activeTab, activeSettings]) useEffect(() => { logseq.on('ui:visible:changed', ({ visible }) => { if (visible) { setVisible(true) setDataDirty((dirty) => { if (dirty) { doPrepareData().catch(null) return false } }) } }) // TODO: teardown logseq.App.onCurrentGraphChanged(() => { setDataDirty(true) closeUI() }) setVisible(true) doPrepareData().catch(console.error) // global keydown for move active item const handleKeydown = (e: KeyboardEvent) => { const key = e.code const isCtrlKey = e.ctrlKey const isArrowUp = key === 'ArrowUp' || (isCtrlKey && key === 'KeyP') const isArrowDown = key === 'ArrowDown' || (isCtrlKey && key === 'KeyN') if (isArrowDown || isArrowUp) { isArrowDown ? downActiveIdx() : upActiveIdx() } } document.addEventListener('keydown', handleKeydown, false) return () => { document.removeEventListener('keydown', handleKeydown) } }, []) // search useEffect(() => { resetActiveIdx() const typedData = data.filter(it => { const activeTypes = tabTypes[activeTab] if (activeTypes && !activeTypes.includes(it.extname?.toLowerCase())) { return } return true }) if (!hasInputValue) { setCurrentListData(typedData) return } // Unicode / universal (50%-75% slower) const fuzzy = new window.uFuzzy({ unicode: true, interSplit: '[^\\p{L}\\d\']+', intraSplit: '\\p{Ll}\\p{Lu}', intraBound: '\\p{L}\\d|\\d\\p{L}|\\p{Ll}\\p{Lu}', intraChars: '[\\p{L}\\d\']', intraContr: '\'\\p{L}{1,2}\\b', }) const result = fuzzy.search(typedData.map(it => it.name), inputValue) if (!result?.[1]) return const { idx, ranges } = result[1] setCurrentListData(idx?.map((idx, n) => { const r = typedData[idx] r.ranges = ranges[n] return r })) }, [data, inputValue, activeTab]) // focus active item in view useEffect(() => { const el = elRef.current const listWrapEl = el?.querySelector('.search-input-list-wrap') const listWrapInnerEl = el?.querySelector('.search-input-list-wrap > .ReactVirtualized__List') if (!el) return if (activeItemIdx === 0) { listWrapInnerEl?.scrollTo(0, 0) return } const activeItem = el.querySelector(`[data-index="${activeItemIdx}"]`) if (!activeItem) return const activeItemRect = activeItem.getBoundingClientRect() const elRect = listWrapEl.getBoundingClientRect() const { height: itemHeight } = activeItemRect const { height: elHeight } = elRect const { top: itemTop } = activeItemRect const { top: elTop } = elRect const itemBottom = itemTop + itemHeight const elBottom = elTop + elHeight const isInView = itemTop >= elTop && itemBottom <= elBottom if (!isInView) { // using scroll into view activeItem.scrollIntoView({ block: 'center', }) } }, [activeItemIdx]) return ( <div className={'search-input-container animate__animated' + (visible ? ' animate__defaultIn' : '')} ref={elRef} > <div className="search-input-head"> <span className={'icon-wrap'}> <ListMagnifyingGlass size={28} weight={'duotone'}/> </span> <span className={'input-wrap'} title={t('Search by keyword or extension')}> <input placeholder={t('Search local assets for current graph')} value={inputValue} onKeyDown={(e) => { const key = e.code const isCtrlKey = e.ctrlKey const isArrowUp = key === 'ArrowUp' || (isCtrlKey && key === 'KeyP') const isArrowDown = key === 'ArrowDown' || (isCtrlKey && key === 'KeyN') const isTab = key === 'Tab' if (isTab && !isCtrlKey) { e.preventDefault() const activeTabIdx = tabs.findIndex((v) => v === activeTab) let toIdx = activeTabIdx + 1 // move tab if (toIdx >= tabs.length) toIdx = 0 if (toIdx < 0) toIdx = (tabs.length - 1) setActiveTab(tabs[toIdx]) return } if (isArrowDown || isArrowUp) { isArrowDown ? downActiveIdx() : upActiveIdx() e.stopPropagation() e.preventDefault() } }} onKeyUp={(e) => { const isEnter = e.key === 'Enter' const isCtrlKey = e.ctrlKey if (isEnter) { e.preventDefault() e.stopPropagation() const activeItem = currentListData?.[activeItemIdx] onSelect(activeItem, { isCtrlKey }) return } }} onChange={e => { setInputValue(e.target.value) }} /> </span> </div> {/* tabs */} <ul className="search-input-tabs"> <li className={isAllTab && 'active'} onClick={() => setActiveTab('all')}> <strong>{t('All')}</strong> <code>{(hasInputValue && isAllTab) ? currentListData?.length : (data?.length || 0)}</code> </li> <li className={isDocumentsTab && 'active'} onClick={() => setActiveTab('documents')}> <Books size={18} weight={'duotone'}/> <strong>{t('Documents')}</strong> {isDocumentsTab && (<code>{currentListData?.length}</code>)} </li> <li className={activeTab === 'images' && 'active'} onClick={() => setActiveTab('images')}> <Images size={18} weight={'duotone'}/> <strong>{t('Images')}</strong> {isImagesTab && (<code>{currentListData?.length}</code>)} </li> <li className={activeTab === 'audios' && 'active'} onClick={() => setActiveTab('audios')}> <FileAudio size={18} weight={'duotone'}/> <strong>{t('Audios')}</strong> {isAudiosTab && (<code>{currentListData?.length}</code>)} </li> {/* settings */} <li className={'settings-dropdown'}> <span onClick={() => { setActiveSettings(!activeSettings) }}> <Faders size={18} weight={'bold'}/> </span> {activeSettings && ( <div className="settings-dropdown-content"> <div className="item as-link" onClick={doPrepareData}> <span><ArrowsClockwise size={17} weight={'bold'}/></span> <strong>{t('Reload assets')}</strong> </div> </div> )} </li> </ul> {/* results */} <div className={'search-input-list-wrap'}> {preparing ? <p className={'loading'}> <MoonLoader size={18}/> </p> : (<ResultList data={currentListData} inputValue={inputValue} activeItemIdx={activeItemIdx} onSelect={onSelect}/>)} </div> </div> ) } let mounted = false function mount() { if (mounted) return render(<App/>, document.getElementById('app')) mounted = true } async function showPicker() { const container = document.querySelector('.search-input-container') as HTMLDivElement const { left, top, rect, } = (await logseq.Editor.getEditingCursorPosition() || { left: 0, top: 0, rect: null }) const cls = document.body.classList cls.remove('as-full') if (!rect) {cls.add('as-full')} Object.assign(container.style, rect ? { top: top + rect.top + 'px', left: left + rect.left + 4 + 'px', transform: 'unset' } : { left: '50%', top: '15%', transform: 'translate3d(-50%, 0, 0)' }) logseq.showMainUI() // focus input setTimeout(() => { container.querySelector('input')?.select() }, 100) } function main(_baseInfo: LSPluginBaseInfo) { (async () => { await l10nSetup({ builtinTranslations: { ja, 'zh-CN': zhCN, 'zh-Hant': zhHant, ko } }) // logseq-l10n })() const open: any = () => { mount() return setTimeout(showPicker, 0) } logseq.Editor.registerSlashCommand('Insert a local asset file', open) logseq.App.registerCommandPalette({ key: 'logseq-assets-plus', label: t('Assets Plus: open picker'), keybinding: { binding: 'mod+shift+o' } }, open) // themes const loadThemeVars = async () => { const props = [ '--ls-primary-background-color', '--ls-secondary-background-color', '--ls-tertiary-background-color', '--ls-quaternary-background-color', '--ls-active-primary-color', '--ls-active-secondary-color', '--ls-border-color', '--ls-secondary-border-color', '--ls-tertiary-border-color', '--ls-primary-text-color', '--ls-secondary-text-color', '--ls-block-highlight-color' ] // @ts-ignore const vals = await logseq.UI.resolveThemeCssPropsVals(props) if (!vals) return const style = document.body.style Object.entries(vals).forEach(([k, v]) => { style.setProperty(k, v as string) }) } const setThemeMode = (mode: string) => { document.documentElement.dataset.theme = mode } logseq.App.onThemeChanged(() => { setTimeout(loadThemeVars, 100) }) logseq.App.onThemeModeChanged((t) => { setTimeout(loadThemeVars, 100) setThemeMode(t.mode) }) logseq.on('ui:visible:changed', ({ visible }) => { if (visible) loadThemeVars().catch(console.error) }) setTimeout(() => { logseq.App.getUserConfigs().then(t => { setThemeMode(t.preferredThemeMode) }) }, 100) } logseq.ready(main).catch(console.error)
xyhp915/logseq-assets-plus
28
A Logseq plugin to enhance assets features 🚀
TypeScript
xyhp915
Charlie
logseq
src/uFuzzy.d.ts
TypeScript
declare class uFuzzy { constructor(opts?: uFuzzy.Options); /** search API composed of filter/info/sort, with a info/ranking threshold (1e3) and fast outOfOrder impl */ search( haystack: string[], needle: string, /** limit how many terms will be permuted, default = 0; 5 will result in up to 5! (120) search iterations. be careful with this! */ outOfOrder?: number, /** default = 1e3 */ infoThresh?: number, preFiltered?: uFuzzy.HaystackIdxs | null ): uFuzzy.SearchResult; /** initial haystack filter, can accept idxs from previous prefix/typeahead match as optimization */ filter( haystack: string[], needle: string, idxs?: uFuzzy.HaystackIdxs ): uFuzzy.HaystackIdxs | null; /** collects stats about pre-filtered matches, does additional filtering based on term boundary settings, finds highlight ranges */ info( idxs: uFuzzy.HaystackIdxs, haystack: string[], needle: string ): uFuzzy.Info; /** performs final result sorting via Array.sort(), relying on Info */ sort( info: uFuzzy.Info, haystack: string[], needle: string ): uFuzzy.InfoIdxOrder; /** utility for splitting needle into terms following defined interSplit/intraSplit opts. useful for out-of-order permutes */ split(needle: string): uFuzzy.Terms; /** util for creating out-of-order permutations of a needle terms array */ static permute(arr: unknown[]): unknown[][]; /** util for replacing common diacritics/accents */ static latinize<T extends string[] | string>(strings: T): T; /** util for highlighting matched substr parts of a result */ static highlight<TAccum = string, TMarkedPart = string>( match: string, ranges: number[], mark?: (part: string, matched: boolean) => TMarkedPart, accum?: TAccum, append?: (accum: TAccum, part: TMarkedPart) => TAccum | undefined ): TAccum; } export = uFuzzy; declare namespace uFuzzy { /** needle's terms */ export type Terms = string[]; /** subset of idxs of a haystack array */ export type HaystackIdxs = number[]; /** sorted order in which info facets should be iterated */ export type InfoIdxOrder = number[]; export type AbortedResult = [null, null, null]; export type FilteredResult = [uFuzzy.HaystackIdxs, null, null]; export type RankedResult = [ uFuzzy.HaystackIdxs, uFuzzy.Info, uFuzzy.InfoIdxOrder ]; export type SearchResult = FilteredResult | RankedResult | AbortedResult; /** partial RegExp */ type PartialRegExp = string; /** what should be considered acceptable term bounds */ export const enum BoundMode { /** will match 'man' substr anywhere. e.g. tasmania */ Any = 0, /** will match 'man' at whitespace, punct, case-change, and alpha-num boundaries. e.g. mantis, SuperMan, fooManBar, 0007man */ Loose = 1, /** will match 'man' at whitespace, punct boundaries only. e.g. mega man, walk_man, man-made, foo.man.bar */ Strict = 2, } export const enum IntraMode { /** allows any number of extra char insertions within a term, but all term chars must be present for a match */ MultiInsert = 0, /** allows for a single-char substitution, transposition, insertion, or deletion within terms (excluding first and last chars) */ SingleError = 1, } export type IntraSliceIdxs = [from: number, to: number]; export interface Options { // whether regexps use a /u unicode flag unicode?: boolean; // false /** @deprecated renamed to opts.alpha */ letters?: PartialRegExp | null; // a-z // regexp character class [] of chars which should be treated as letters (case insensitive) alpha?: PartialRegExp | null; // a-z /** term segmentation & punct/whitespace merging */ interSplit?: PartialRegExp; // '[^A-Za-z0-9]+' intraSplit?: PartialRegExp | null; // '[a-z][A-Z]' /** intra bounds that will be used to increase lft1/rgt1 info counters */ intraBound?: PartialRegExp | null; // '[A-Za-z][0-9]|[0-9][A-Za-z]|[a-z][A-Z]' /** inter-term modes, during .info() can discard matches when bounds conditions are not met */ interLft?: BoundMode; // 0 interRgt?: BoundMode; // 0 /** allowance between terms */ interChars?: PartialRegExp; // '.' interIns?: number; // Infinity /** allowance between chars within terms */ intraChars?: PartialRegExp; // '[a-z\\d]' intraIns?: number; // 0 /** contractions detection */ intraContr?: PartialRegExp; // "'[a-z]{1,2}\\b" /** error tolerance mode within terms. will clamp intraIns to 1 when set to SingleError */ intraMode?: IntraMode; // 0 /** which part of each term should tolerate errors (when intraMode: 1) */ intraSlice?: IntraSliceIdxs; // [1, Infinity] /** max substitutions (when intraMode: 1) */ intraSub?: 0 | 1; // 0 /** max transpositions (when intraMode: 1) */ intraTrn?: 0 | 1; // 0 /** max omissions/deletions (when intraMode: 1) */ intraDel?: 0 | 1; // 0 /** can dynamically adjust error tolerance rules per term in needle (when intraMode: 1) */ intraRules?: (term: string) => { intraSlice?: IntraSliceIdxs; intraIns: 0 | 1; intraSub: 0 | 1; intraTrn: 0 | 1; intraDel: 0 | 1; }; /** post-filters matches during .info() based on cmp of term in needle vs partial match */ intraFilt?: (term: string, match: string, index: number) => boolean; // should this also accept WIP info? sort?: (info: Info, haystack: string[], needle: string) => InfoIdxOrder; } export interface Info { /** matched idxs from haystack */ idx: HaystackIdxs; /** match offsets */ start: number[]; /** number of left BoundMode.Strict term boundaries found */ interLft2: number[]; /** number of right BoundMode.Strict term boundaries found */ interRgt2: number[]; /** number of left BoundMode.Loose term boundaries found */ interLft1: number[]; /** number of right BoundMode.Loose term boundaries found */ interRgt1: number[]; /** total number of extra chars matched within all terms. higher = matched terms have more fuzz in them */ intraIns: number[]; /** total number of chars found in between matched terms. higher = terms are more sparse, have more fuzz in between them */ interIns: number[]; /** total number of matched contiguous chars (substrs but not necessarily full terms) */ chars: number[]; /** number of exactly-matched terms (intra = 0) where both lft and rgt landed on a BoundMode.Loose or BoundMode.Strict boundary */ terms: number[]; /** offset ranges within match for highlighting: [startIdx0, endIdx0, startIdx1, endIdx1,...] */ ranges: number[][]; } } export as namespace uFuzzy;
xyhp915/logseq-assets-plus
28
A Logseq plugin to enhance assets features 🚀
TypeScript
xyhp915
Charlie
logseq
index.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Logseq fenced code Plus</title> <script src="./src/main.ts" type="module"></script> </head> <body> <div id="app">Workspace+</div> </body> </html>
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
playground/index.css
CSS
body { @apply p-2; --lx-gray-01: #eee; --lx-gray-02: #ddd; --lx-gray-03: #ccc; --lx-gray-06: #aaa; --lx-accent-10: #0096ff; } .wp-tile-layout-root { @apply h-[calc(100vh-30px)] bg-amber-100; } .wp-tile-layout.flex { @apply !flex; } .wp-tile-layout-view { @apply w-full; }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
playground/index.html
HTML
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="./index.tsx" type="module"></script> <title>Document</title> </head> <body> <div id="app"></div> </body> </html>
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
playground/index.tsx
TypeScript (TSX)
import '../src/main.css' import './index.css' import ReactDOM from 'react-dom' import { getCardViewCtorFromRegistry, TileLayoutRoot } from '../src/Layout' function Playground() { return ( <div className={'relative'}> <TileLayoutRoot onRequireCardView={async (tile) => { const cardID = ['HiCard', 'YoutubeCard', 'ImageCard'][Math.floor(Math.random() * 3)] const CardViewCtor = getCardViewCtorFromRegistry(cardID) if (!CardViewCtor) { throw new Error(`${cardID} not registered!`) } return new CardViewCtor(tile) }}/> </div> ) } // mount the Playground component ReactDOM.render( <Playground/>, document.getElementById('app'))
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
postcss.config.js
JavaScript
module.exports = { plugins: { 'tailwindcss/nesting': {}, tailwindcss: {}, }, }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/App.tsx
TypeScript (TSX)
import React, { useEffect } from 'react' import { tickEffect } from './Workspace' export function App() { useEffect(() => { console.info('Hi from workspace+ APP!') }, []) return ( <div className={'app-inner'}> <pre className={'p-2'}> {JSON.stringify(logseq.baseInfo, null, 2)} </pre> <button onClick={() => logseq.hideMainUI()}> {tickEffect()} </button> {/*{devHMRWatcher.Provider()}*/} </div> ) }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/Layout.spec.tsx
TypeScript (TSX)
import { test, expect } from 'vitest' import { parseTileDataWithTkey, resizeTileLeft, resizeTileRight } from './Layout' import { produce } from 'immer' test('tile layout apis 1', async () => { const draftData: any = { direction: 'row', children: [ { span: 24, children: [16, { span: 22 }, 7, -1] }, 10, { span: 23, children: [12, 12, 8, { span: 12, direction: 'row', children: [32, 32] }, -1] }, { children: [23, 12, -1] } ] } expect(parseTileDataWithTkey('0-0-1', draftData)).toEqual([{ span: 22 }, draftData.children[0].children, draftData.children[0], 1, '0-0-1']) expect(parseTileDataWithTkey('0-1', draftData)).toEqual([10, draftData.children, draftData, 1, '0-1']) expect(parseTileDataWithTkey('0-2-1', draftData)).toEqual([12, draftData.children[2].children, draftData.children[2], 1, '0-2-1']) // resizeTileLeft const resizedLeftState: any = produce(draftData, draft => { resizeTileLeft('0-0-1', draft) resizeTileLeft('0-1', draft) resizeTileLeft('0-2-0', draft) resizeTileLeft('0-3-2', draft) resizeTileLeft('0-2-3-0', draft) }) expect(resizedLeftState.children[0].children[0].span).toBe(15) expect(resizedLeftState.children[0].children[1].span).toBe(23) expect(resizedLeftState.children[1]).toEqual(10) expect(resizedLeftState.children[2].children[0].span).toBe(11) expect(resizedLeftState.children[2].children[1].span).toBe(13) expect(resizedLeftState.children[3].children[1]).toEqual({ span: 11 }) expect(resizedLeftState.children[3].children[2]).toEqual({ span: -1 }) expect(resizedLeftState.children[2].children[2].span).toBe(7) expect(resizedLeftState.children[2].children[3].span).toBe(13) // resizeTileRight const resizedRightState: any = produce(draftData, draft => { resizeTileRight('0-0-1', draft) resizeTileRight('0-1', draft) resizeTileRight('0-3-2', draft) resizeTileRight('0-2-3-0', draft) }) expect(resizedRightState.children[0].children[1]).toEqual({ span: 23 }) expect(resizedRightState.children[0].children[2]).toEqual({ span: 6 }) expect(resizedRightState.children[1]).toBe(10) expect(resizedRightState.children[3].children[2]).toEqual({ span: -1 }) expect(resizedRightState.children[3].children[1]).toEqual({ span: 13 }) expect(resizedRightState.children[2].children[3].span).toEqual(13) expect(resizedRightState.children[2].children[4].span).toEqual(-1) }) test('tile layout apis 2', async () => { })
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/Layout.tsx
TypeScript (TSX)
import './layout.css' import { useImmer } from 'use-immer' import { FC, FunctionComponent, useEffect, useRef, useState } from 'react' import uniqid from 'uniqid' import { CardID, ICardView, ICardViewConstructor } from './cards/shared' import { HiCard } from './cards/Hi' import { original } from 'immer' import { YoutubeCard } from './cards/Youtube' import { EditorCard } from './cards/Editor' import { EmptyPlaceholder } from './cards/EmptyPlaceholder' import { ImageCard } from './cards/Image' import { LSUI, SHUI } from './utils' import { CalendarCard } from './cards/Calendar' export type Span = number export type ViewsRecord = Record<CardID, ICardView | FC<any>> export type TileLayoutAttrs = { group: string, depth: number, index: number, id?: string, tkey?: string, direction?: 'row' | 'col', span?: Span, children?: Array<Span | Partial<TileLayoutAttrs>>, parent?: TileLayoutAttrs views?: ViewsRecord } export const gridN = 64 export function TileLayout(attrs: TileLayoutAttrs) { const span = attrs?.span const group = attrs?.group const direction = attrs?.direction ?? 'col' const id = attrs?.id || uniqid() const tkey = attrs?.tkey ?? 0 const parent = attrs?.parent const childrenLen = attrs?.children?.length const spanClass = parent?.direction ? `${parent?.direction}-span-${span}` : '' const gridClass = !childrenLen ? 'flex' : `grid-${direction}s-${gridN}` const view = attrs.views?.[id] || attrs.views?.[tkey] const View = typeof view === 'function' ? view : view?.render const doc = top.document const elRef = useRef(null) let childrenSpanAcc = 0 return ( <div className={`wp-tile-layout ${gridClass} ${spanClass} as-${direction}`} data-group={group} data-key={tkey} id={id} ref={elRef} tabIndex={0} onKeyUp={(e) => { if (e.key === 'Enter') { if (doc.activeElement === elRef.current) { (view as ICardView)?.onEnter(e.target) } } }} > {/* card view */} {!childrenLen && (View ? (<div className={'wp-tile-layout-view'}> <View tid={id} tkey={tkey}/> </div>) : (<div className={'wp-tile-layout-view-placeholder'}> <EmptyPlaceholder tileLayout={attrs} cardsViewRegistry={cardsViewRegistry}/> </div>))} {!childrenLen && ( <div className={'wp-tile-layout-toolbar absolute flex justify-between bg-secondary shadow w-full top-0 left-0 p-2 items-center'}> <b className={'wp-tile-label-text'}> {tkey} ({span}, {id}) </b> <div className={'flex items-center gap-2'}> {View && <button data-action={'remove-view'} className={'px-2 flex items-center'}> <SHUI.TablerIcon name={'trash'}/> </button>} <button data-action={'set-view'} className={'px-2 flex items-center'}> <SHUI.TablerIcon name={'circle-plus'}/> </button> <button data-action={'split-v'} className={'flex items-center mr-1'}> <SHUI.TablerIcon name={'circle-half'}/> </button> <button data-action={'split-h'} className={'flex items-center mr-1'}> <SHUI.TablerIcon name={'circle-half-vertical'}/> </button> <button data-action={'remove'} className={'mr-1 flex items-center text-red-700'}> <SHUI.TablerIcon name={'x'}/> </button> </div> </div> )} {attrs.children?.map((child, index) => { let props: TileLayoutAttrs = { depth: attrs.depth + 1, tkey: `${tkey}-${index}`, index, group } if (typeof child === 'number') { props.span = child } else { props = { ...child, ...props } } if (isFlexibleSpan(props.span)) { props.span = gridN - childrenSpanAcc } props.children = (child as TileLayoutAttrs).children props.parent = { ...attrs, direction } props.views = attrs.views childrenSpanAcc += props.span return ( <TileLayout {...props} /> ) } )} </div> ) } export function parseTileDataWithTkey(tkey: string, draftData: any) { // remove root index const indexes = tkey.split('-').map(Number)?.slice(1) const ret = indexes.reduce(([value, refChildren, refParent], idx) => { return value.children ? [value.children[idx], value.children, value, idx] : [value, refChildren, refParent, idx] }, [draftData, false, false, 0]) ret.push(tkey) return ret } const FlexSpan = -1 const isNumber = (s: any) => typeof s === 'number' const isObject = (obj: any) => { return typeof obj === 'object' && obj !== null && !Array.isArray(obj)} const isFlexibleSpan = (s: any) => (!s || s === FlexSpan || s.span === FlexSpan || (isObject(s) && s.span == undefined)) const isRootTkey = (s: string) => s === '0' || !s const parseParentTkey = (s: string) => s?.replace(/-\d+$/, '') const parsePrevSiblingTkey = (s: string) => s?.replace(/-(\d+)$/, (s, p1) => `-${p1 - 1}`) const parseNextSiblingTkey = (s: string) => s?.replace(/-(\d+)$/, (s, p1) => `-${p1 + 1}`) export type RawTileData = number | ({ span: number, children?: Array<RawTileData> } & Partial<TileLayoutAttrs>) export type RawTileDataProxy = { span: number, children?: Array<RawTileData> } & Partial<TileLayoutAttrs> export type IndexedTileData = { idx: number, value: RawTileData, refChildren?: Array<RawTileData>, refParent?: RawTileData } function resizeTilePrevSibling( { idx, refChildren, }: IndexedTileData, draftData: any, step = 1 ) { // do not resize the only child if (refChildren?.length === 1) return draftData const valueRef = refChildren[idx] as RawTileDataProxy const valueLeft = refChildren[idx - 1] if (valueLeft && isNumber(valueLeft)) refChildren[idx - 1] = { span: valueLeft as number } const valueLeftRef = valueLeft && refChildren[idx - 1] as RawTileDataProxy const valueRight = refChildren[idx + 1] if (valueRight && isNumber(valueRight)) refChildren[idx + 1] = { span: valueRight as number } const valueRightRef = valueRight && refChildren[idx + 1] as RawTileDataProxy if (valueLeft) { valueLeftRef.span -= step if (!isFlexibleSpan(valueRef)) valueRef.span += step } else { if (!isFlexibleSpan(valueRef)) valueRef.span -= step if (!isFlexibleSpan(valueRight)) valueRightRef.span += step } return draftData } export function resizeTileLeft(tkey: string, draftData: any, step: number = 1) { const [value, refChildren, refParent, idx] = parseTileDataWithTkey(tkey, draftData) const isInRows = refParent?.direction === 'row' if (isInRows) { const parentTkey = parseParentTkey(tkey) if (!parentTkey || isRootTkey(parentTkey)) return const [_, parentRefChildren] = parseTileDataWithTkey(parentTkey, draftData) if (parentRefChildren?.length === 1) return return resizeTileLeft(parentTkey, draftData, step) } if (isNumber(value)) refChildren[idx] = { span: value } return resizeTilePrevSibling( { idx, value, refChildren, refParent }, draftData, step) } function resizeTileNextSibling( { idx, refChildren }: IndexedTileData, draftData: any, step = 1 ) { // do not resize the only child if (refChildren?.length === 1) return draftData const valueRef = refChildren[idx] as RawTileDataProxy const valueLeft = refChildren[idx - 1] if (valueLeft && isNumber(valueLeft)) refChildren[idx - 1] = { span: valueLeft as number } const valueLeftRef = valueLeft && refChildren[idx - 1] as RawTileDataProxy const valueRight = refChildren[idx + 1] if (valueRight && isNumber(valueRight)) refChildren[idx + 1] = { span: valueRight as number } const valueRightRef = valueRight && refChildren[idx + 1] as RawTileDataProxy if (valueRight) { if (!isFlexibleSpan(valueRef)) valueRef.span += step if (!isFlexibleSpan(valueRight)) valueRightRef.span -= step } else { if (!isFlexibleSpan(valueRef)) valueRef.span -= step if (valueLeft) valueLeftRef.span += step } return draftData } export function resizeTileRight(tkey: string, draftData: any, step: number = 1) { const [value, refChildren, refParent, idx] = parseTileDataWithTkey(tkey, draftData) const isInRows = refParent?.direction === 'row' if (isInRows) { const parentTkey = parseParentTkey(tkey) if (!parentTkey || isRootTkey(parentTkey)) return const [_, parentRefChildren] = parseTileDataWithTkey(parentTkey, draftData) if (parentRefChildren?.length === 1) return return resizeTileRight(parentTkey, draftData, step) } if (isNumber(value)) refChildren[idx] = { span: value } return resizeTileNextSibling( { idx, value, refChildren, refParent }, draftData, step) } export function resizeTileUp(tkey: string, draftData: any, step: number = 1) { const [value, refChildren, refParent, idx] = parseTileDataWithTkey(tkey, draftData) const isInCols = refParent?.direction !== 'row' if (isInCols) { const parentTkey = parseParentTkey(tkey) if (isRootTkey(parentTkey)) return const [_, parentRefChildren] = parseTileDataWithTkey(parentTkey, draftData) if (parentRefChildren?.length === 1) return return resizeTileUp(parentTkey, draftData, step) } if (isNumber(value)) refChildren[idx] = { span: value } return resizeTilePrevSibling( { idx, value, refChildren, refParent }, draftData, step) } export function resizeTileDown(tkey: string, draftData: any) { const [value, refChildren, refParent, idx] = parseTileDataWithTkey(tkey, draftData) const isInCols = refParent?.direction !== 'row' if (isInCols) { const parentTkey = parseParentTkey(tkey) if (!parentTkey || isRootTkey(parentTkey)) return const [_, parentRefChildren] = parseTileDataWithTkey(parentTkey, draftData) if (parentRefChildren?.length === 1) return return resizeTileDown(parentTkey, draftData) } if (isNumber(value)) refChildren[idx] = { span: value } return resizeTileNextSibling( { idx, value, refChildren }, draftData) } export function splitVertical(tkey: string, draftData: any, callback?: Function) { const [value, refChildren, _refParent, idx] = parseTileDataWithTkey(tkey, draftData) if (isNumber(value)) refChildren[idx] = { span: value, id: uniqid() } const valueRef = !refChildren ? value : refChildren[idx] const spanId = valueRef.id const newSpanId = uniqid() if (!_refParent || _refParent?.direction === 'row') { if (!_refParent) valueRef.direction = 'col' valueRef.id = uniqid() valueRef.children = [{ span: gridN / 2, id: spanId }, { span: gridN / 2, id: newSpanId }] } else { const spanVal = isFlexibleSpan(valueRef.span) ? ( refChildren?.length ? (gridN - (refChildren.reduce((a, v) => { v = isNumber(v) ? v : v.span return a + (isFlexibleSpan(v) ? 0 : v) }), 0)) : gridN ) : valueRef.span const span1 = Math.floor(spanVal / 2) const span2 = spanVal - span1 valueRef.span = span1 refChildren[idx + 1] = { span: span2, id: newSpanId } } callback?.(newSpanId) return draftData } export function splitHorizontal(tkey: string, draftData: any, callback?: Function) { const [value, refChildren, _refParent, idx] = parseTileDataWithTkey(tkey, draftData) if (isNumber(value)) refChildren[idx] = { span: value, id: uniqid() } const valueRef = !refChildren ? value : refChildren[idx] const spanId = valueRef.id const newSpanId = uniqid() if (_refParent?.direction !== 'row') { valueRef.direction = 'row' valueRef.id = uniqid() valueRef.children = [{ span: gridN / 2, id: spanId }, { span: gridN / 2, id: newSpanId }] } else { const spanVal = isFlexibleSpan(valueRef.span) ? ( refChildren?.length ? (gridN - (refChildren.reduce((a, v) => { v = isNumber(v) ? v : v.span return a + (isFlexibleSpan(v) ? 0 : v) }), 0)) : gridN ) : valueRef.span const span1 = Math.floor(spanVal / 2) const span2 = spanVal - span1 valueRef.span = span1 refChildren[idx + 1] = { span: span2, id: newSpanId } } callback?.(newSpanId) return draftData } export function removeTile(tkey: string, draftData: any, callback?: (v: any) => void, back?: boolean) { const [value, refChildren, _refParent, idx] = parseTileDataWithTkey(tkey, draftData) const prevSiblingRef = refChildren[idx - 1] const nextSiblingRef = refChildren[idx + 1] if (prevSiblingRef && !isNumber(prevSiblingRef)) { if (value.span === FlexSpan) { prevSiblingRef.span = FlexSpan } else { prevSiblingRef.span += value.span } } else if (nextSiblingRef && !isNumber(nextSiblingRef) && nextSiblingRef.span !== FlexSpan) { nextSiblingRef.span += value.span } if (!refChildren) { return draftData } if (!back) { callback?.apply(null, [original(value)]) } refChildren.splice(idx, 1) if (!back && refChildren.length === 0) { removeTile(parseParentTkey(tkey), draftData, callback) } else if (refChildren.length === 1) { // back const childTkey = parsePrevSiblingTkey(tkey) const [childValue] = parseTileDataWithTkey(childTkey, draftData) // TODO: deep nested children if (childValue.children?.length < 2) { const [parentValue] = parseTileDataWithTkey(parseParentTkey(tkey), draftData) parentValue.id = refChildren[0].id removeTile(childTkey, draftData, callback, true) } } return draftData } function inflateTileData(root: Partial<TileLayoutAttrs>) { const { children } = root if (root?.id == undefined) root.id = uniqid() if (!children) return root return { ...root, children: children.map((child: any) => { if (isNumber(child)) { child = { span: child } } return inflateTileData(child as Partial<TileLayoutAttrs>) }) } } function MovementObserver( props: { group: string, views: ViewsRecord, layoutData: Partial<TileLayoutAttrs>, setLayoutData: Function, ops: { doRemove: Function, doSplitV: Function, doSplitH: Function } } ) { const { views, layoutData, setLayoutData, ops } = props const lastFocusTidRef = useRef(null) const [isKeyLeading, setIsKeyLeading] = useState<any>(false) const doc = top.document const doFocus = (tid: string, delay = 0) => { const fn = () => { const tile: HTMLElement = doc.getElementById(tid) if (!tile) return const view = props.views?.[tid] as ICardView // trigger prev view blur if (lastFocusTidRef.current && lastFocusTidRef.current !== tid) { const prevView = props.views?.[lastFocusTidRef.current] as ICardView prevView?.onBlur?.(tile) } tile.focus() view?.onFocus?.(tile) lastFocusTidRef.current = tid } if (delay > 0) { setTimeout(fn, delay) } else { fn() } } const doMove = ( tkey: string, arrowDirection: string, opts: { isResizeFlag: boolean, isFocusFlag: boolean } = { isResizeFlag: false, isFocusFlag: true } ) => { const { isFocusFlag, isResizeFlag } = opts const getPrevClosestTile = (tkey: string, direction: string = 'col') => { const [value, refChildren, _refParent, idx] = parseTileDataWithTkey(tkey, props.layoutData) // root if (isRootTkey(tkey)) return const isStopDirection = (_refParent?.direction || 'col') === direction const prevSiblingRef = refChildren[idx - 1] if (!isStopDirection || !prevSiblingRef) { return getPrevClosestTile(parseParentTkey(tkey), direction) } if (prevSiblingRef) { const pickValidTile = (tile: any) => { if (!tile.children?.length) { return tile } // TODO: root original index return pickValidTile(tile.children[0]) } return pickValidTile(prevSiblingRef) } } const getNextClosestTile = (tkey: string, direction: string = 'col') => { const [value, refChildren, _refParent, idx] = parseTileDataWithTkey(tkey, props.layoutData) // root if (!tkey || tkey === '0') return const isStopDirection = (_refParent?.direction || 'col') === direction const nextSiblingRef = refChildren[idx + 1] if (!isStopDirection || !nextSiblingRef) { return getNextClosestTile(parseParentTkey(tkey), direction) } if (nextSiblingRef) { const pickValidTile = (tile: any) => { if (!tile.children?.length) { return tile } // TODO: root original index return pickValidTile(tile.children[0]) } return pickValidTile(nextSiblingRef) } } let tile = null switch (arrowDirection) { case 'ArrowLeft': if (isResizeFlag) { return setLayoutData(draft => { return resizeTileLeft(tkey, draft) }) } if (isFocusFlag) { tile = getPrevClosestTile(tkey, 'col') } break case 'ArrowRight': if (isResizeFlag) { return setLayoutData(draft => { return resizeTileRight(tkey, draft) }) } if (isFocusFlag) { tile = getNextClosestTile(tkey, 'col') } break case 'ArrowUp': if (isResizeFlag) { return setLayoutData(draft => { return resizeTileUp(tkey, draft) }) } if (isFocusFlag) { tile = getPrevClosestTile(tkey, 'row') } break case 'ArrowDown': if (isResizeFlag) { return setLayoutData(draft => { return resizeTileDown(tkey, draft) }) } if (isFocusFlag) { tile = getNextClosestTile(tkey, 'row') } break default: } tile && doFocus(tile.id) } // leading key handler & restore focus useEffect(() => { const gLeadingHandler = (e: KeyboardEvent) => { let tileContainer = doc.activeElement?.closest('.wp-tile-layout') if (!tileContainer) { // TODO: infer the latest tile container if (lastFocusTidRef.current) { tileContainer = doc.getElementById(lastFocusTidRef.current) } else { const selectedBlock = doc.querySelector('.ls-block.selected') if (selectedBlock) { tileContainer = selectedBlock.closest('.wp-tile-layout') } } } if (!tileContainer) return if (isKeyLeading) { const moveOpts = { isResizeFlag: e.ctrlKey, isFocusFlag: !e.ctrlKey } const tkey = tileContainer.getAttribute('data-key') clearTimeout(isKeyLeading) setIsKeyLeading(false) switch (e.key) { case 'h': return doMove(tkey, 'ArrowLeft', moveOpts) case 'j': return doMove(tkey, 'ArrowDown', moveOpts) case 'k': return doMove(tkey, 'ArrowUp', moveOpts) case 'l': return doMove(tkey, 'ArrowRight', moveOpts) case '=': return ops.doSplitV(tkey, (tid: string) => doFocus(tid, 64)) case '-': return ops.doSplitH(tkey, (tid: string) => doFocus(tid, 64)) case 'd': return ops.doRemove(tkey) } } if (e.ctrlKey && e.code === 'KeyX') { const leadingTimer = setTimeout(() => {setIsKeyLeading(false)}, 2000) setIsKeyLeading(leadingTimer) } } doc.addEventListener('keydown', gLeadingHandler) return () => { doc.removeEventListener('keydown', gLeadingHandler) } }, [isKeyLeading]) // tile movement handler useEffect(() => { const groupContainer = doc.getElementById(`lsp-wp-${props.group}`) const moveHandler = (e: KeyboardEvent) => { const tileContainer = doc.activeElement?.closest('.wp-tile-layout') if (!tileContainer) { const isDirectionKey = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key) if (isDirectionKey && lastFocusTidRef.current) { doFocus(lastFocusTidRef.current) } return } const tkey = tileContainer.getAttribute('data-key') const isResizeFlag = e.ctrlKey || e.metaKey const isFocusFlag = e.altKey const arrowDirection = e.key doMove(tkey, arrowDirection, { isResizeFlag, isFocusFlag }) } groupContainer?.addEventListener('keydown', moveHandler) return () => { groupContainer?.removeEventListener('keydown', moveHandler) } }, [views, layoutData, setLayoutData]) return <></> } // cards view registry const cardsViewRegistry = new Map<CardID, ICardViewConstructor>() cardsViewRegistry.set(HiCard.name, HiCard) cardsViewRegistry.set(YoutubeCard.name, YoutubeCard) cardsViewRegistry.set(EditorCard.name, EditorCard) cardsViewRegistry.set(ImageCard.name, ImageCard) cardsViewRegistry.set(CalendarCard.name, CalendarCard) export const getCardViewCtorFromRegistry = (id: CardID) => cardsViewRegistry.get(id) export const removeCardViewFromRegistry = (id: CardID) => cardsViewRegistry.delete(id) export function createCardViewFromJSONMeta(meta: any) { const { id, tileLayout, ...opts } = meta const Ctor = getCardViewCtorFromRegistry(id) if (!Ctor) return return new Ctor(tileLayout, opts) } function createADemoView(tkey: string) { return () => { return ( <div className={'p-4 bg-green-600 text-white rounded-xl flex-1 w-full h-full flex items-center justify-center'}> <button>Hi, Card View in #{tkey}!</button> </div> ) } } let _setLastLayoutUpdate = null export function persistLayoutAndViewState() { _setLastLayoutUpdate?.(Date.now()) } let _setViews = null export function applyCardViewInTile( tid: string, view: string | ICardViewConstructor, opts?: any ) { const ViewCtor = typeof view === 'string' ? getCardViewCtorFromRegistry(view) : view if (!ViewCtor) return _setViews((v: ViewsRecord) => { return { ...v, [tid]: new ViewCtor({ id: tid }, opts) } }) } export function TileLayoutRoot(props: { onRequireCardView: (t: Partial<TileLayoutAttrs>, e?: any) => void }) { const group = 'lsp-ws-1' const [layoutData, setLayoutData] = useImmer<Partial<TileLayoutAttrs>>(inflateTileData({})) const [lastLayoutUpdate, setLastLayoutUpdate1] = useState(Date.now()) const [views, setViews] = useState<ViewsRecord>({ 'test-id': () => <button>Hi, Card View!</button> }) const [mounted, setMounted] = useState(false) useEffect(() => { setMounted(true) _setLastLayoutUpdate = setLastLayoutUpdate1 _setViews = setViews return () => { _setLastLayoutUpdate = null _setViews = null } }, []) // persist the layout & views useEffect(() => { if (mounted) { localStorage.setItem(group, JSON.stringify({ layoutData, views, lastLayoutUpdate })) } else { // restore the layout and views const data = localStorage.getItem(group) if (data) { const { layoutData, views } = JSON.parse(data) setLayoutData(layoutData) if (views) { Object.entries(views).forEach(([id, viewMeta]) => { if (viewMeta) { views[id] = createCardViewFromJSONMeta(viewMeta) } else { delete views[id] } }) setViews(views) } } } }, [mounted, layoutData, views, lastLayoutUpdate]) // ops const doRemove = (tkey: string) => { setLayoutData(draft => { return removeTile(tkey, draft, (t) => { if (t?.id && views[t.id]) { console.log('===>> remove:', t) setViews((v) => { delete v[t.id] return v }) } }) }) } const doSplitV = (tkey: string, callback?: Function) => { setLayoutData(draft => { return splitVertical(tkey, draft, callback) }) } const doSplitH = (tkey: string, callback?: Function) => { setLayoutData(draft => { return splitHorizontal(tkey, draft, callback) }) } return ( <> {mounted && <MovementObserver group={group} views={views} layoutData={layoutData} setLayoutData={setLayoutData} ops={{ doRemove, doSplitV, doSplitH }} />} <div className={'wp-tile-layout-root'} id={`lsp-wp-${group}`} onClick={(e) => { const target = (e.target as HTMLElement).closest('button') if (!target) return const action = target.getAttribute('data-action') const tkey = target.closest('.wp-tile-layout')?.getAttribute('data-key') const tid = target.closest('.wp-tile-layout')?.id switch (action) { case 'left': return setLayoutData(draft => { return resizeTileLeft(tkey, draft) }) case 'right': return setLayoutData(draft => { return resizeTileRight(tkey, draft) }) case 'up': return setLayoutData(draft => { return resizeTileUp(tkey, draft) }) case 'down': return setLayoutData(draft => { return resizeTileDown(tkey, draft) }) case 'split-v': return doSplitV(tkey) case 'split-h': return doSplitH(tkey) case 'remove': return doRemove(tkey) case 'set-view': return props.onRequireCardView({ id: tid }, e) case 'remove-view': return setViews((v) => { delete v[tid] return { ...v } }) default: } }} > <TileLayout group={group} depth={0} index={0} views={views} {...layoutData}/> </div> </> ) }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/Workspace.tsx
TypeScript (TSX)
import './workspace.css' import React from 'react' import { applyCardViewInTile, getCardViewCtorFromRegistry, TileLayoutRoot } from './Layout' import { LSUI, SHUI, toClj, toJs } from './utils' export function initTestCustomRoute() { // @ts-ignore logseq.Experiments.registerRouteRenderer( 'x-route', { path: '/x-route', render: () => { return ( <TileLayoutRoot onRequireCardView={async (t, e) => { const cardTypes = ['HiCard', 'ImageCard', 'EditorCard', 'YoutubeCard', 'CalendarCard'] SHUI.popupShow(e.target, (_p1) => { return ( <div className={'p-3 w-60 flex gap-2 flex-wrap'}> {cardTypes.map(it => { return ( <LSUI.Button size={'sm'} onClick={(e) => { const CardCtor = getCardViewCtorFromRegistry(it) const opts = {} if (it === 'EditorCard') { SHUI.popupShow(e, () => { const demoPages = ['Charlie', 'Test', 'Contents'] return ( <> {demoPages.map(p => { return (<LSUI.DropdownMenuItem onClick={() => { applyCardViewInTile(t.id, CardCtor, { name: p.toLowerCase() }) SHUI.popupHideAll() }}> [[{p}]]</LSUI.DropdownMenuItem>) })} </> ) }, toClj({[`as-dropdown?`]: true})) return } applyCardViewInTile(t.id, CardCtor, opts) SHUI.popupHide() }} > {it} </LSUI.Button> ) })} </div> ) }) }}/> ) } }) } export function initWorkspace() { initTestCustomRoute() } export const tickEffect = () => { return Date.now() }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/cards/Calendar.tsx
TypeScript (TSX)
import { TileLayoutAttrs } from '../Layout' import { ICardView } from './shared' import React from 'react' import { LSUI } from '../utils' export class CalendarCard implements ICardView { static name = 'CalendarCard' private _id: string = 'CalendarCard' private _title: string = 'Calendar Card' private readonly _tileLayout: Partial<TileLayoutAttrs> constructor(tileLayout: Partial<TileLayoutAttrs>) { this._tileLayout = tileLayout this.render = this.render.bind(this) } render(props: any): React.ReactElement { return ( <div className={'flex h-full items-center justify-center w-full'}> <LSUI.Calendar /> </div> ) } get id(): string { return this._id } get title(): string { return this._title } get tileLayout(): Partial<TileLayoutAttrs> { return this._tileLayout } toJSON(): {} { return { id: this.id, title: this.title, tileLayout: this.tileLayout } } }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/cards/Editor.tsx
TypeScript (TSX)
import { ICardView } from './shared' import { LSUI } from '../utils' import React, { useEffect, useState } from 'react' import { applyCardViewInTile, TileLayoutAttrs } from '../Layout' // @ts-ignore const Components = window.logseq?.Experiments?.Components const hostSDKBaseAPIs = window.logseq?.Experiments?.ensureHostScope().logseq.api const doc = top.document const isUUIDStr = (s: string) => { if (typeof s !== 'string') return return /^[a-z,0-9-]{36}$/.test(s) } export class EditorCard implements ICardView { static name = 'EditorCard' private _id: string = 'EditorCard' private _title: string = 'Editor Card' private _lastEditBlockId: string private readonly _tileLayout: Partial<TileLayoutAttrs> private readonly _opts: any = {} constructor(tileLayout: Partial<TileLayoutAttrs>, opts: any = {}) { this.render = this.render.bind(this) this._tileLayout = tileLayout this._opts = opts } render(props: any) { const { name } = this._opts const isBlock = isUUIDStr(name) const [ready, setReady] = useState(!isBlock) useEffect(() => { if (ready) return const rt = setTimeout(() => { setReady(true) }, 32) return () => { clearTimeout(rt) } }, []) return ( <div className={'w-full px-2'}> {ready ? <Components.Editor page={name} includeUnlinkedRefs={false} includeLinkedRefs={false} onRedirectToPage={(name: string) => { if (!name || name === this._opts.name) return applyCardViewInTile(this._tileLayout.id, EditorCard.name, { name }) }} onEscapeEditing={(blockId: string, isEsc: boolean) => { this.lastEditBlockId = blockId // TODO: handle escape editing if (isEsc) { const layoutEl = doc.getElementById(this._tileLayout.id) layoutEl?.focus() } }}/> : (<h2 className={'py-10 flex items-center w-full'}>Loading...</h2>) } </div> ) } // hooks onFocus(e: any) { // @ts-ignore hostSDKBaseAPIs.clear_selected_blocks() if (this._lastEditBlockId) { setTimeout(() => { hostSDKBaseAPIs.edit_block(this._lastEditBlockId) }, 32) } } onBlur(e: any) { // @ts-ignore hostSDKBaseAPIs.clear_selected_blocks() } onEnter(e: any) { const hasSelectedBlocks = doc.querySelector('.ls-block.selected') if (hasSelectedBlocks) return this.onFocus(e) } static async onEmptyPlaceholderDrop(e: any) { const dt = e.dataTransfer as DataTransfer const blockId = dt?.getData('block-uuid') if (blockId) { return { name: blockId } } } set lastEditBlockId(value: string) { this._lastEditBlockId = value console.log('===>>> pl: set lastEditBlockId..', this._tileLayout.id, ' :: ', value) } get id(): string { return this._id } get title(): string { return this._title } get tileLayout(): any { return this._tileLayout } toJSON() { return { id: this.id, title: this.title, tileLayout: this._tileLayout, ...this._opts } } }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/cards/EmptyPlaceholder.tsx
TypeScript (TSX)
import React from 'react' import { CardID, ICardViewConstructor } from './shared' import { applyCardViewInTile, TileLayoutAttrs } from '../Layout' export function EmptyPlaceholder( props: { tileLayout: Partial<TileLayoutAttrs>, cardsViewRegistry: Map<CardID, ICardViewConstructor> } ) { const { tileLayout, cardsViewRegistry } = props return ( <div className={'flex flex-1 items-center justify-center'} onDragOver={(e) => { e.preventDefault() }} onDrop={async (e) => { e.preventDefault() console.debug('===>>> drop:', e) for (const [_, ctor] of cardsViewRegistry) { if (ctor.onEmptyPlaceholderDrop) { const ret = await ctor.onEmptyPlaceholderDrop(e) if (ret) { // require card view applyCardViewInTile(tileLayout.id, ctor, ret) break } } } }} > <h1 className={'text-lg text-gray-500 opacity-40'}>Empty Card</h1> </div> ) }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/cards/Hi.tsx
TypeScript (TSX)
import { ICardView } from './shared' import React from 'react' import { TileLayoutAttrs } from '../Layout' export class HiCard implements ICardView { static name = 'HiCard' private _id: string = 'HiCard' private _title: string = 'A card to say Hi for beginners!' private readonly _tileLayout: Partial<TileLayoutAttrs> constructor(tileLayout: Partial<TileLayoutAttrs>) { this._tileLayout = tileLayout this.render = this.render.bind(this) } render(props: any): React.ReactElement { return ( <div className={'flex h-full items-center justify-center w-full'}> <h1 className={'text-3xl text-pink-500'}>Hi 🃏 for you, in <button className={'bg-green-600 text-white'} onClick={() => alert(JSON.stringify(this))} > ${this._tileLayout.id}</button> ! </h1> </div> ) } // hooks onFocus(e: any) { console.info('===>> focus:', this.tileLayout.id, '<<==>>', e) } static async onBeforeAddView(tileData: Partial<TileLayoutAttrs>) { // TODO: Add a new card to the layout } get tileLayout(): Partial<TileLayoutAttrs> { return this._tileLayout } get id(): string { return this._id } get title(): string { return this._title } toJSON() { return { id: this.id, title: this.title, tileLayout: this.tileLayout } } }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/cards/Image.tsx
TypeScript (TSX)
import { persistLayoutAndViewState, TileLayoutAttrs } from '../Layout' import { ICardView } from './shared' import { useEffect, useState } from 'react' export class ImageCard implements ICardView { static name = 'ImageCard' private _id: string = 'ImageCard' private _title: string = 'A card to show images!' private readonly _tileLayout: Partial<TileLayoutAttrs> private readonly _opts: any = {} constructor(tileLayout: Partial<TileLayoutAttrs>, opts: any = {}) { this._tileLayout = tileLayout this._opts = opts this.render = this.render.bind(this) } render(props: any) { const { url } = this._opts const [url1, setUrl1] = useState(url) useEffect(() => { if (!url1) { const s = 'https://source.unsplash.com/random/800x600' fetch(s).finally(() => setUrl1(s)) return } this._opts.url = url1 persistLayoutAndViewState() }, [url1]) return ( <div className={'flex h-full items-center justify-center w-full'}> {url1 ? <img src={url1} draggable={true} alt={'random image'} className={'w-full h-full object-cover'}/> : <h1>Loading...</h1>} </div> ) } get id(): string { return this._id } get title(): string { return this._title } get tileLayout(): Partial<TileLayoutAttrs> { return this._tileLayout } toJSON(): {} { return { id: this.id, title: this.title, tileLayout: this.tileLayout, ...this._opts } } static async onEmptyPlaceholderDrop(e: any) { let items = e.dataTransfer?.items if (!items?.length) return const uris = await Promise.all(Array.from(items).map((it: DataTransferItem) => { return new Promise<string | undefined>((resolve) => { if (it.kind === 'string' && it.type === 'text/uri-list') { return it.getAsString(s => resolve(s)) } else { resolve(undefined) } }) })) const validUrl = uris?.find((u) => (!!u && u.startsWith('http'))) if (validUrl) { // as opts return { url: validUrl } } } }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/cards/Youtube.tsx
TypeScript (TSX)
import { CardID, ICardView } from './shared' import * as console from 'console' import { persistLayoutAndViewState, TileLayoutAttrs } from '../Layout' import { useEffect, useState } from 'react' export class YoutubeCard implements ICardView { static name = 'YoutubeCard' private _id: string = 'YoutubeCard' private _title: string = 'Youtube Card' private readonly _tileLayout: any private readonly _opts: any = {} constructor(tileLayout: any, opts: any = {}) { this._tileLayout = tileLayout this._opts = opts this.render = this.render.bind(this) } render(props: any) { const { title, url } = this._opts const [url1, setUrl1] = useState(url) useEffect(() => { if (url1) { this._opts.url = url1 } }, [url1]) return ( <div className={'flex h-full items-center justify-center w-full flex-col'}> {!url1 && <h1 className={'text-3xl text-pink-500'}>Youtube Card</h1>} {typeof url1 === 'string' ? ( <iframe width="100%" height="100%" style={{ margin: 0 }} src={`https://www.youtube.com/embed/${url1.split('v=')[1]}`} title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerPolicy="strict-origin-when-cross-origin" allowFullScreen></iframe> ) : ( <div className={'flex items-center gap-2'}> <input type="text" defaultValue={url1} placeholder={'Enter youtube video url'} className={'p-2 border border-gray-300 rounded w-96'} /> <button onClick={(e) => { const url1 = (e.target as any).previousElementSibling.value setUrl1(url1) persistLayoutAndViewState() }} > Load </button> </div> )} </div> ) } // hooks onFocus(e: any) { console.info('===>> focus:', this.tileLayout.id, '<<==>>', e) } get tileLayout(): Partial<TileLayoutAttrs> { return this._tileLayout } get id(): CardID { return this._id } get title(): string { return this._title } toJSON() { return { id: this.id, title: this.title, tileLayout: this.tileLayout, ...this._opts } } }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/cards/shared.ts
TypeScript
import { ReactElement } from 'react' import { TileLayoutAttrs } from '../Layout' export type CardID = string export interface ICardViewConstructor { new(tile: Partial<TileLayoutAttrs>, opts?: any): ICardView onBeforeAddView?(tile: Partial<TileLayoutAttrs>): Promise<any> onEmptyPlaceholderDrop?(e: any): Promise<boolean | {}> } export interface ICardView { readonly id: CardID; readonly title: string; readonly tileLayout: Partial<TileLayoutAttrs>; readonly description?: string; render(props: any): ReactElement | null | undefined; // hooks onFocus?(e: any): void; onEnter?(e: any): void; onBlur?(e: any): void; // for serialization to persist the card toJSON(): {}; }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/layout.css
CSS
.wp-tile-layout-root { @apply relative w-full h-[calc(100vh-48px)]; background-color: var(--lx-gray-03); } .wp-tile-layout { @apply h-full relative grid; @apply relative overflow-auto outline-none; border-width: 1px; border-color: var(--lx-gray-06); background-color: var(--lx-gray-01); &:focus, &:focus-within { /*background-color: var(--lx-gray-02);*/ } } .wp-tile-layout-view-placeholder { @apply h-full w-full flex; } .wp-tile-layout.as-col { > div.wp-tile-layout { @apply border-r-2; &:last-child { @apply border-r-0; } } } .wp-tile-layout.as-row { > div.wp-tile-layout { @apply border-b-2; &:last-child { @apply border-b-0; } } }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/main.css
CSS
@tailwind base; @tailwind components; @tailwind utilities;
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/main.ts
TypeScript
import './main.css' import '@logseq/libs' import { App } from './App' import React from 'react' import ReactDOM from 'react-dom' import { initWorkspace } from './Workspace' function main() { console.info('Hello from workspace+ plugin!') logseq.App.registerCommandShortcut( 'mod+1' , () => { logseq.App.pushState('x-route') }) const cssLink = document.head.getElementsByTagName('link')?.[0] const cssHref = cssLink?.getAttribute('href') logseq.provideStyle(` @import url('${logseq.resolveResourceFullUrl(`dist/${cssHref}`)}'); `) logseq.provideModel({ toggleMainUI() { logseq.App.pushState('x-route') } }) logseq.setMainUIInlineStyle({ width: '600px', height: '400px', position: 'fixed', top: '100px', left: '50%', transform: 'translateX(-50%)', backgroundColor: 'white', border: '2px solid red', }) logseq.App.registerUIItem('toolbar', { key: 'open-workspace-x', template: ` <a class="button" data-on-click="toggleMainUI"> <i class="ti ti-table"></i> </a> `, }) // mount the App component ReactDOM.render( React.createElement(App), document.getElementById('app')) // init custom routes initWorkspace() } // bootstrap logseq.ready(main).catch(console.error) // hmr for development in logseq const callbacks = [initWorkspace] // @ts-ignore if (module.hot) { // @ts-ignore module.hot.accept(function (_a, _b) { console.info('== plugin: hot accept') // reinstall changes callbacks.forEach(cb => cb()) // module or one of its dependencies was just updated const pid = logseq.baseInfo?.id if (!pid) return const host = logseq.Experiments.ensureHostScope() host.LSPluginCore.ensurePlugin(pid).reload() host.frontend.core.delay_remount(200) }) }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/react-dom.js
JavaScript
module.exports = logseq.Experiments.ReactDOM
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/react.js
JavaScript
module.exports = logseq.Experiments.React
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/utils.ts
TypeScript
import { FunctionComponent, PropsWithChildren } from 'react' import { snakeCase } from 'snake-case' export function toClj(s) { if (!s) return s try { s = logseq.Experiments.ensureHostScope().logseq.sdk.utils.jsx_to_clj(s) return s } catch (e) { console.error(e) } } export function toJs(o) { if (!o) return o return logseq.Experiments.ensureHostScope().logseq.sdk.utils.to_js(o) } export const LSUI: { [k: string]: FunctionComponent<PropsWithChildren<any>> } = new Proxy({}, { get: (target, prop) => { return logseq.Experiments.ensureHostScope().LSUI[prop] } }) export const SHUI: { [k: string]: any } = new Proxy({}, { get: (target, prop: string) => { const ctx = logseq.Experiments.ensureHostScope().logseq.shui.ui if (prop === 'TablerIcon') { return (props: any) => ctx.tabler_icon(props.name, toClj(props)) } else if (prop.startsWith('popup') || prop.startsWith('toast')) { return ctx[`${snakeCase(prop)}_BANG_`] } return ctx[prop] } })
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
src/workspace.css
CSS
body[data-page="x-route"] { .cp__sidebar-main-content { @apply !max-w-none; > .pb-24 { @apply !pb-0 !mb-0; } } #main-content-container { @apply !p-0; } } .wp-tile-label-text { @apply text-xs right-10 top-3; } .wp-tile-layout-view { @apply h-full w-full overflow-auto; &:focus-within { } } .wp-tile-layout { &.flex { @apply !flex pt-[40px]; } } .wp-tile-layout-toolbar { button { @apply opacity-80 hover:opacity-100 active:opacity-70; } } .wp-tile-layout { .wp-tile-layout-toolbar { transition: background-color 0.2s; transition-delay: 32ms; } &:focus { .wp-tile-layout-toolbar { background-color: var(--lx-gray-06); } } } .wp-tile-layout-view { &:focus, &:focus-within { & ~ .wp-tile-layout-toolbar { background-color: var(--lx-gray-06); } } .page { @apply px-2; } }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
tailwind.config.js
JavaScript
/** @type {import('tailwindcss').Config} */ export default { content: [ './index.html', './src/**/*.{js,ts,jsx,tsx}', './playground/**/*.{js,ts,jsx,tsx}', ], safelist: [ { pattern: /grid-/ }, { pattern: /(col|row)-/ }, ], theme: { extend: { gridTemplateColumns: { '64': 'repeat(64, minmax(0, 1fr))', }, gridTemplateRows: { '64': 'repeat(64, minmax(0, 1fr))', }, gridRow: Array.from({ length: 64 - 12 }).reduce((r, _, i) => { const k = 12 + i + 1 r[`span-${k}`] = `span ${k} / span ${k}` return r }, {}), gridColumn: Array.from({ length: 64 - 12 }).reduce((r, _, i) => { const k = 12 + i + 1 r[`span-${k}`] = `span ${k} / span ${k}` return r }, {}), }, }, plugins: [], }
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
vite.config.ts
TypeScript
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], // build: { // rollupOptions: { // external: ['react', 'react-dom'], // output: { // globals: { // react: 'logseq.Experiments.React', // 'react-dom': 'logseq.Experiments.ReactDOM', // }, // } // } // } })
xyhp915/logseq-workspace-plus
0
A Logseq plugin to enhance workspace features!
TypeScript
xyhp915
Charlie
logseq
index.html
HTML
<!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>logseq-zotero-plugin</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/App.css
CSS
@reference "tailwindcss"; @layer components { html { @apply w-screen h-screen bg-black/20 flex items-center justify-center; } #root { @apply p-4 w-[90vw] sm:max-w-[1280px] bg-white rounded-xl overflow-y-auto dark:bg-black; } .badge { background: transparent !important; white-space: nowrap !important; } .table-container { max-height: 66vh; overflow-y: auto; min-height: 380px; .hover-visible { @apply invisible; } tr { &:hover { @apply bg-gray-100! dark:bg-gray-800!; .hover-visible { @apply visible!; } } } } .dropdown-content { } }
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/App.tsx
TypeScript (TSX)
import './App.css' import { setZoteroUserSettings, useAppState, useCacheZEntitiesEffects, useCollections, useFilteredTopItems, usePaginatedTopItems, useTopItems, useTopItemsGroupedByCollection, validateZoteroCredentials, type ZoteroItemEntity, } from './store.ts' import { type PropsWithChildren, useEffect, useMemo, useRef, useState } from 'react' import cn from 'classnames' import { type Immutable, type ImmutableArray, type State, useHookstate } from '@hookstate/core' import useTableSort from './hooks/useTableSort' import { LucideDownload, LucideExternalLink, LucideFilter, LucideList, LucideLoader, LucideLoader2, LucideMinus, LucideRotateCcw, LucideSearch, LucideSettings2, LucideUpload, LucideX, } from 'lucide-react' import { openItemInLogseq, pushItemToLogseq, startFullPushToLogseq } from './handlers.ts' import { closeMainDialog, delay, getItemTitle, shortenFilename } from './common.ts' function GroupedItemsTabsContainer() { const { groupedItems, groupedCollections } = useTopItemsGroupedByCollection() const [currentCollectionKey, setCurrentCollectionKey] = useState<string | null>(null) return ( <div> <ul className={'flex gap-2 flex-row'}> {Object.keys(groupedItems).map(collKey => { const collection = groupedCollections[collKey] return ( <li key={collKey} className={'flex-1'}> <button className={cn('btn w-full', currentCollectionKey === collKey && 'btn-active')} onClick={() => setCurrentCollectionKey(collKey)} > <strong> {collection?.name || collKey} ({groupedItems[collKey].length}) </strong> </button> </li> ) })} </ul> <div className={'p-2 py-6'}> {currentCollectionKey && groupedItems[currentCollectionKey] && ( <div> <TopEntityItemsTableContainer items={groupedItems[currentCollectionKey]}/> </div> )} </div> </div> ) } function CollectionsLabels(props: { itemCollectionKeys: string[] }) { const { itemCollectionKeys } = props const collectionsState = useCollections() const itemCollections = collectionsState.items?.filter(coll => itemCollectionKeys.includes(coll.key)) return ( <div className={'flex gap-2 flex-wrap'}> {itemCollections?.map(coll => { return ( <code key={coll.key} className={'badge badge-soft badge-xs'}> {coll.name} </code> ) })} </div> ) } function PushItemButton({ item }: { item: Immutable<ZoteroItemEntity> }) { const pushingState = useHookstate(false) return ( <button className={'btn btn-xs btn-ghost px-1'} disabled={pushingState.get()} onClick={async () => { try { pushingState.set(true) await pushItemToLogseq(item) await logseq.UI.showMsg( `Item "${item.title}" pushed to Logseq page.`, 'success', ) await delay() } catch (e) { await logseq.UI.showMsg( `Error pushing item "${item.title}" to Logseq: ${e}`, 'error', ) console.error(e) } finally { pushingState.set(false) } }} > {pushingState.get() ? ( <LucideLoader size={12} className={'animate-spin'}/>) : <LucideUpload size={14}/>} </button> ) } function TopEntityItemsTableContainer( props: { items: ImmutableArray<ZoteroItemEntity>, onCheckedItemsChange?: (checkedItemsState: State<any>, checkedItemsCount: number) => void }, ) { const checkedItemsState = useHookstate<{ [key: string]: boolean }>({}) const checkedInputRef = useRef<HTMLInputElement>(null) const checkedChangedState = useHookstate(0) const { sortedItems, sortKey, sortDir, toggleSort } = useTableSort( props.items, null, 'asc', ) useEffect(() => { const allKeysChecked = props.items?.every(it => checkedItemsState[it.key].get()) const someKeysChecked = props.items?.some(it => checkedItemsState[it.key].get()) if (checkedInputRef.current) { checkedInputRef.current.indeterminate = !allKeysChecked && someKeysChecked checkedInputRef.current.checked = allKeysChecked || false } if (props.onCheckedItemsChange) { const checkedItemsCount = Object.values(checkedItemsState.get() || {}).filter(v => v).length props.onCheckedItemsChange(checkedItemsState, checkedItemsCount) } }, [checkedChangedState.get()]) const renderSortIndicator = (key: string) => { if (sortKey !== key) return null return sortDir === 'asc' ? ' ▲' : ' ▼' } return ( <table className="table table-xs border collapse"> <thead className={'bg-base-200'}> <tr> <th className={'w-[16px] pr-0'}> <label className={'relative top-1'}> <input type="checkbox" ref={checkedInputRef} defaultChecked={false} onChange={e => { const checked = e.target.checked const newCheckedState: { [key: string]: boolean } = {} props.items?.forEach(it => { newCheckedState[it.key] = checked }) checkedItemsState.set(newCheckedState) checkedChangedState.set(p => p + 1) }} /> </label> </th> <th className={'pl-0 cursor-pointer'} onClick={() => toggleSort('title')}>Title{renderSortIndicator( 'title')}</th> <th className={'cursor-pointer'} onClick={() => toggleSort('itemType')}>Type{renderSortIndicator( 'itemType')}</th> <th className={'cursor-pointer'} onClick={() => toggleSort('collections')}>Collections{renderSortIndicator( 'collections')}</th> <th className={'cursor-pointer'} onClick={() => toggleSort('attachments')}> Attachments {renderSortIndicator('attachments')} </th> <th className={'cursor-pointer'} onClick={() => toggleSort('dateModified')}>dateModified{renderSortIndicator( 'dateModified')}</th> <th>More</th> </tr> </thead> <tbody> {sortedItems?.map(it => { return ( <tr key={it.key} className={'even:bg-base-200'} onDoubleClick={() =>{ console.log('==> [DEBUG]', JSON.stringify(it, null, 2)) }} > <td> <label className={'flex items-center'}> <input type="checkbox" checked={checkedItemsState[it.key].get() || false} onChange={e => { checkedItemsState[it.key].set(e.target.checked) checkedChangedState.set(p => p + 1) }} /> </label> </td> <td className={'pl-0'}> <a href={'#'} className={'block'} onClick={(e) => { console.log(JSON.stringify(it, null, 2)) // selected row const target = e.currentTarget const rowInput = target.closest('tr')?.querySelector('input[type="checkbox"]') as HTMLInputElement rowInput?.click() }}> <strong> {getItemTitle(it)} </strong> </a> </td> <td> <a className={'text-[13px] cursor-pointer flex gap-1 items-center opacity-80 hover:opacity-100'} onClick={async () => { const typeTag = await logseq.Editor.getTag(it.itemType) if (typeTag) { logseq.App.pushState('page', { name: typeTag.uuid }) closeMainDialog() } else { await logseq.UI.showMsg(`Logseq tag not found for item type: ${it.itemType}`, 'error') } }} > {it.itemType} <LucideExternalLink size={12} className={'hover-visible'}/> </a> </td> <td> <CollectionsLabels itemCollectionKeys={it.collections}/> </td> <td> {it.children?.map((att: ZoteroItemEntity) => { if (att.itemType !== 'attachment') return null return ( <code key={att.key} className={'badge badge-soft badge-xs mr-1'}> {shortenFilename(att.title)} </code> ) })} </td> <td>{it.dateModified}</td> {/*<td>{it.tags?.[0]?.tag}</td>*/} <td className={'flex'}> <PushItemButton item={it}/> <button className={'btn btn-xs btn-ghost px-1'} title={'Open page in Logseq'} onClick={async () => { try { await openItemInLogseq(it) closeMainDialog() } catch (e) { console.error('Error opening item in Logseq:', e) } }} > <LucideExternalLink size={14}/> </button> </td> </tr> ) })} </tbody> </table> ) } function TopEntityItemsFilteredContainer( { filteredQueryState }: { filteredQueryState: State<{ q: string, filterItemTypes: Array<string>, filterCollections: Array<string> }, {}> }, ) { const qInputRef = useRef<HTMLInputElement>(null) const topItems = useTopItems() const collectionsState = useCollections() const itemTypes = useMemo(() => { const typesSet = new Set<string>() topItems.items.forEach(it => { if (it.itemType) { typesSet.add(it.itemType) } }) return Array.from(typesSet).sort() }, [topItems.items?.length]) useEffect(() => { // clear input text when esc const onKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape') { if (qInputRef.current!.value !== '') { qInputRef.current!.value = '' filteredQueryState.q.set('') } else { closeMainDialog() } } } const onKeyup = (e: KeyboardEvent) => { const value = qInputRef.current!.value // clear q when input is empty if (e.key === 'Backspace' && value === '') { filteredQueryState.q.set('') } } window.addEventListener('keydown', onKeyDown) window.addEventListener('keyup', onKeyup) return () => { window.removeEventListener('keydown', onKeyDown) window.removeEventListener('keyup', onKeyup) } }, []) return ( <div className={'flex justify-between pb-3 px-1'}> <div> {[ ['item types', filteredQueryState.value.filterItemTypes, itemTypes, filteredQueryState.filterItemTypes], [ 'collections', filteredQueryState.value.filterCollections, collectionsState.items.map(it => { return it.key }), filteredQueryState.filterCollections, collectionsState.items.reduce((acc, it) => { acc[it.key] = it.name return acc }, {} as { [key: string]: any })]].map(([label, selectedItems, items, itState, itemsKeyMap]: any) => { return ( <div className="dropdown"> <div tabIndex={0} role="button" className="btn btn-sm m-1"> <LucideFilter size={14}/> <span className={'pl-1'}> {selectedItems.length > 0 ? `Filtered: ${selectedItems.map((it: string) => { return itemsKeyMap ? itemsKeyMap[it] : it }).join(', ')}` : `Filter by ${label}`} </span> </div> <ul tabIndex={-1} className="dropdown-content menu bg-base-100 rounded-box z-1 p-2 w-52 shadow-sm"> {items.map((type: string) => { const isChecked = selectedItems.includes(type) const labelText = itemsKeyMap ? itemsKeyMap[type] : type return ( <li key={type}> <label className="flex items-center gap-2 px-2 py-1"> <input type="checkbox" checked={isChecked} onChange={e => { const checked = e.target.checked const currentTypes = selectedItems if (checked) { // add itState.set([...currentTypes, type]) } else { // remove itState.set( currentTypes.filter((t: any) => t !== type), ) } }} /> <span>{labelText}</span> </label> </li> ) })} {/* clear all */} <li> <button className="btn btn-sm btn-ghost w-full" onClick={() => { itState.set([]) }} > Clear All </button> </li> </ul> </div> ) })} {/* reset all filter */} {(filteredQueryState.value.filterItemTypes.length > 0 || filteredQueryState.value.filterCollections.length > 0) && ( <button className={'btn btn-sm btn-ghost m-1 opacity-70 text-red-600'} onClick={() => { filteredQueryState.filterItemTypes.set([]) filteredQueryState.filterCollections.set([]) }} > <LucideRotateCcw size={14}/> Reset all filters </button> )} </div> <div> <form className={'flex items-center gap-2'} onSubmit={(e) => { const formData = new FormData(e.currentTarget) const q = formData.get('q') as string filteredQueryState.q.set(q) e.preventDefault() }} > <input type="text" name={'q'} className={'input input-sm'} placeholder={'Search items...'} ref={qInputRef} /> <button type={'submit'} className={'btn btn-sm'}> <LucideSearch size={16}/> </button> </form> </div> </div> ) } function AppContainer( props: PropsWithChildren<any>, ) { // setup shortcuts, global styles, etc. useEffect(() => { // close UI on ESC const onKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape') { const activeElement = document.activeElement as HTMLInputElement if (activeElement && activeElement.tagName === 'INPUT') { return } closeMainDialog() } } window.addEventListener('keydown', onKeyDown) return () => { window.removeEventListener('keydown', onKeyDown) } }, []) return (<div className="app-container"> {props.children} </div> ) } function SettingsTabContainer() { const appState = useAppState() const userSettings = appState.userSettings.get() as any const validatingState = useHookstate(false) return ( <form onSubmit={async (e) => { e.preventDefault() const formData = new FormData(e.currentTarget) const formDataPlain = Object.fromEntries(formData) const apiKey = formData.get('z_api_key') as string const userId = formData.get('z_user_id') as string console.log('Saving settings:', formDataPlain) try { validatingState.set(true) setZoteroUserSettings({ apiKey, userId, ...formDataPlain }) await validateZoteroCredentials() await logseq.UI.showMsg('Zotero user settings saved successfully.', 'success') } catch (e: any) { let msg = `Error saving Zotero user settings: ${e}` if (e?.response) { msg = `Failed to validate Zotero credentials. Please check your API Key and User ID. (${e.reason || e.response.statusText})` } console.error('Error saving Zotero user settings:', e) await logseq.UI.showMsg(msg, 'error') } finally { validatingState.set(false) } }}> <div className={'pt-4 px-2'}> <p className={'flex flex-col'}> <label htmlFor="z_api_key" className={'font-semibold opacity-90'}> Zotero API Key: </label> <input type="text" id="z_api_key" name={'z_api_key'} className="input input-bordered w-full max-w-xs mt-1" required={true} defaultValue={userSettings?.apiKey || ''} /> <small className={'opacity-60 pt-2'}> You can create a new API key from{' '} <a href={'https://www.zotero.org/settings/security'} target={'_blank'} className={'px-1 underline text-info'} > https://www.zotero.org/settings/security </a> </small> </p> <p className={'flex flex-col mt-6'}> <label htmlFor="z_user_id" className={'font-semibold opacity-90'}> Zotero User ID: </label> <input type="text" id="z_user_id" name={'z_user_id'} className="input input-bordered w-full max-w-xs mt-1" required={true} defaultValue={userSettings?.userId || ''} /> <small className={'opacity-60 pt-2'}> How to Find Your Zotero USER ID in SECONDS! <a href={'https://www.youtube.com/watch?v=7vDiZ8o_eHk'} target={'_blank'} className={'px-1 underline text-info'} > https://www.youtube.com/watch?v=7vDiZ8o_eHk </a> </small> </p> <p className={'flex flex-col mt-6'}> <label htmlFor={'z_data_dir'} className={'font-semibold opacity-90'}> Zotero data directory: </label> <input type="text" id={'z_data_dir'} className="input input-bordered w-full max-w-xs mt-1" placeholder={'/Users/username/Zotero'} name={'z_data_dir'} defaultValue={userSettings?.z_data_dir || ''} /> <small className={'opacity-60 pt-2'}> Locating Your Zotero Data. <a href="https://www.zotero.org/support/zotero_data" target={'_blank'} className={'px-1 underline text-info'} > https://www.zotero.org/support/zotero_data </a> </small> </p> <p className={'mt-6 text-sm text-gray-600'}> <button className={'btn'} type={'submit'} disabled={validatingState.get()} > {validatingState.get() ? 'Validating...' : 'Save Settings'} </button> </p> </div> </form> ) } function App() { // initialize effects useCacheZEntitiesEffects() const appState = useAppState() const zTopItemsState = useTopItems() const collectionsState = useCollections() // const zTagsState = useZTags() // const [groupedCollectionsView, setGroupedCollectionsView] = useState(false) const checkedItemsCountState = useHookstate(0) const checkedItemsStateRef = useRef<State<any, any>>(null) const currentTabState = useHookstate<'all-items' | 'settings'>('all-items') const filteredTopItemsState = useFilteredTopItems() const paginatedTopItems = usePaginatedTopItems({ limit: 20, filteredItems: filteredTopItemsState.filteredItems, }) const userSettings = appState.userSettings.get() const isInvalidUserSettings = !userSettings?.apiKey || !userSettings?.userId useEffect(() => { const isPushing = appState.isPushing.get() const isPulling = appState.isPulling.get() const isSyncing = isPushing || isPulling const syncingProgressMsg = appState.pullingOrPushingProgressMsg.get()?.trim() if (isSyncing && !!syncingProgressMsg) { logseq.UI.showMsg(syncingProgressMsg, 'success', { key: 'z-syncing-progress-msg', timeout: 0 }, ) } else { logseq.UI.closeMsg('z-syncing-progress-msg') } if (!!appState.pullingOrPushingErrorMsg.get()) { logseq.UI.showMsg(`${appState.pullingOrPushingErrorMsg.get()}`, 'error') appState.pullingOrPushingErrorMsg.set('') } }, [ appState.isPushing.get(), appState.isPulling.get(), appState.pullingOrPushingErrorMsg, appState.pullingOrPushingProgressMsg.get()]) if (!appState.isVisible.get()) { return <></> } const isSyncingRemote = collectionsState.loading || zTopItemsState.loading return ( <AppContainer> <div className={'flex justify-between'}> <div className={'flex gap-3'}> <div role="tablist" className="tabs tabs-lift"> <a role="tab" className={cn('tab', currentTabState.get() === 'all-items' && 'tab-active')} onClick={() => currentTabState.set('all-items')} > <LucideList size={18}/> <span className={'pl-1.5'}> All Zotero top items ({zTopItemsState.items.length}) </span> </a> <a role="tab" className={cn('tab', currentTabState.get() === 'settings' && 'tab-active')} onClick={() => currentTabState.set('settings')} > <LucideSettings2 size={18}/> <span className={'pl-1.5'}> Settings </span> </a> </div> </div> <div className={'flex gap-4 items-center'}> {!isInvalidUserSettings && (<> <span className={'label text-sm'}> {isSyncingRemote ? 'Syncing...' : ` ${zTopItemsState.items.length} top items loaded.`} </span> <button className={'btn btn-sm'} onClick={async () => { try { appState.isPulling.set(true) await collectionsState.refresh({}) await zTopItemsState.refresh({}) } catch (e) { console.error('Error pulling remote Zotero top items:', e) } finally { appState.isPulling.set(false) } }} disabled={isSyncingRemote} > {isSyncingRemote ? ( <LucideLoader2 size={18} className={'animate-spin'}/> ) : ( <LucideDownload size={18}/> )} Pull remote Zotero top items </button> {zTopItemsState.items.length > 0 && ( <button className={cn('btn btn-sm btn-outline', checkedItemsCountState.get() ? 'btn-dash btn-warning' : 'btn-success')} onClick={async () => { if (checkedItemsCountState.get()) { // push selected items const checkedItems = zTopItemsState.items.filter(it => { return checkedItemsStateRef.current?.get()?.[it.key] }) await startFullPushToLogseq({ items: checkedItems }) } else { // push all items await startFullPushToLogseq() } }} disabled={appState.isPushing.get()} > {appState.isPushing.get() ? ( <LucideLoader2 size={18} className={'animate-spin'}/>) : ( <LucideUpload size={18}/>)} {checkedItemsCountState.get() ? `Push selected items (${checkedItemsCountState.get()}) to Logseq` : 'Push all items to Logseq'} </button> )} </> )} <button className={cn('btn btn-circle btn-xs btn-outline', checkedItemsCountState.get() ? 'btn-warning btn-dash' : '')} onClick={() => { if (checkedItemsCountState.get() > 0) { checkedItemsStateRef.current?.set({}) checkedItemsCountState.set(0) } else { closeMainDialog() } }} > {checkedItemsCountState.get() ? <LucideMinus size={14}/> : <LucideX size={14}/>} </button> </div> </div> <div className={'py-4 h-[630px] mb-4'}> {(isInvalidUserSettings || currentTabState.get() === 'settings') ? ( <SettingsTabContainer/>) : ( <> <TopEntityItemsFilteredContainer filteredQueryState={filteredTopItemsState.filteredQueryState}/> <div className={'table-container'}> <TopEntityItemsTableContainer items={paginatedTopItems.paginatedItems} onCheckedItemsChange={(checkedItemsState1, checkedItemsCount) => { checkedItemsCountState.set(checkedItemsCount) checkedItemsStateRef.current = checkedItemsState1 }} /> </div> {paginatedTopItems.paginatedLabelNums.length > 1 && ( <div className={'flex justify-center pt-4 -mb-4'}> <div className="join"> <button className="join-item btn btn-xs" disabled={paginatedTopItems.currentPage === 0} onClick={() => { paginatedTopItems.goToPage(paginatedTopItems.currentPage - 1) }} >Prev </button> {paginatedTopItems.paginatedLabelNums.map((label, index) => { if (label === '...') { return ( <button key={index} className="join-item btn btn-xs" onClick={() => { paginatedTopItems.goToPage(Math.floor(paginatedTopItems.totalPages / 2)) }} >...</button> ) } else { const pageNum = Number(label) - 1 return ( <button key={index} className={cn('join-item btn btn-xs', paginatedTopItems.currentPage === pageNum && 'btn-success')} onClick={() => { paginatedTopItems.goToPage(pageNum) }} > {label} </button> ) } })} <button className="join-item btn btn-xs" disabled={paginatedTopItems.currentPage === paginatedTopItems.totalPages - 1} onClick={() => { paginatedTopItems.goToPage(paginatedTopItems.currentPage + 1) }} >Next </button> </div> </div> )} </> )} </div> </AppContainer> ) } export default App
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/common.ts
TypeScript
import { v5 } from 'uuid' import { appState, type ZoteroItemEntity } from './store.ts' import type { Immutable } from '@hookstate/core' export const isInLogseq = location.href.includes('v=lsp') const NAMESPACE_UUID = 'b83c1a7b-50ab-4cd1-b80f-39f5ef6f9dea' export function id2UUID(id: string): string { return v5(id, NAMESPACE_UUID) } export function closeMainDialog() { if (appState.isPushing.get()) return logseq?.hideMainUI() } export function delay(ms: number = 1000) { return new Promise(resolve => setTimeout(resolve, ms)) } export function removeHtmlTags(str: string): string { if (!str) return str return str.replace(/<[^>]*>/g, '') } export function truncateString(str: string, maxLength: number = 64): string { if (str.length <= maxLength) return str return str.slice(0, maxLength) + '...' } export function getItemTitle( item: Immutable<ZoteroItemEntity> ) { let title = item.title || item.caseName || item.note || 'Untitled' title = removeHtmlTags(title) title = truncateString(title, 100) return title } export function shortenFilename(filename: string, maxLength: number = 30): string { if (filename.length <= maxLength) return filename const extIndex = filename.lastIndexOf('.') const extension = extIndex !== -1 ? filename.slice(extIndex) : '' const namePart = extIndex !== -1 ? filename.slice(0, extIndex) : filename const truncatedName = namePart.slice(0, maxLength - extension.length - 3) return `${truncatedName}.${extension}` }
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/handlers.ts
TypeScript
import { appState, pushingLogger, zCollectionsState, type ZoteroItemEntity, zTopItemsState } from './store.ts' import type { Immutable, ImmutableArray } from '@hookstate/core' import { delay, id2UUID } from './common.ts' let itemTypesData: Array<any> = [] let itemTypesMapping: Record<string, Array<{ field: string }>> = {} async function resolveItemTypesData() { if (itemTypesData.length > 0) { return } const { default: { itemTypes } } = await import('./assets/z_item_types.json') itemTypesData = itemTypes for (const itemType of itemTypesData) { itemTypesMapping[itemType.itemType] = itemType.fields } } export async function pushItemTypesToLogseqTag() { await resolveItemTypesData() // 1. create root tag "Zotero" const zRootTagName = 'Zotero' const zRootTagUUID = id2UUID('zotero_' + zRootTagName) let zRootTag = await logseq.Editor.getPage(zRootTagUUID) if (!zRootTag) { // @ts-ignore zRootTag = await logseq.Editor.createTag(zRootTagName, { uuid: zRootTagUUID }) await logseq.Editor.upsertProperty('key', { type: 'default' }) await logseq.Editor.upsertProperty('ztags', { type: 'node', cardinality: 'many' }) await logseq.Editor.addTagProperty(zRootTag?.uuid!, 'key') await logseq.Editor.addTagProperty(zRootTag?.uuid!, 'ztags') } const pickedItemTypes = ['book', 'journalArticle', 'attachment', 'webpage', 'conferencePaper', 'thesis', 'report', 'document', 'magazineArticle', 'newspaperArticle', 'videoRecording', 'bookSection', 'note', 'case', 'collections' ] // 2. create tags for each item type and their fields for (const itemType of itemTypesData) { let tagName = itemType.itemType if (!tagName || !pickedItemTypes.includes(tagName)) continue let tag = await logseq.Editor.getTag(tagName) pushingLogger.log(`Processing item type tag: ${tagName} - Found: ${!!tag}`) const forceExtendsRootTag = async (tagUUID: string) => { await logseq.Editor.upsertBlockProperty(tagUUID, ':logseq.property.class/extends', [zRootTag?.id]) } if (tag) { await forceExtendsRootTag(tag.uuid) continue } tag = await logseq.Editor.createTag(tagName) await forceExtendsRootTag(tag?.uuid!) pushingLogger.log(`Created tag for item type: ${tagName} - UUID: ${tag!.uuid}`) for (const field of itemType.fields) { const fieldName = field.field try { const fieldProperty = await logseq.Editor.upsertProperty(fieldName, { type: 'default' }) await logseq.Editor.addTagProperty(tag?.uuid!, fieldName) await logseq.Editor.upsertBlockProperty(fieldProperty.uuid, ':logseq.property/hide-empty-value', true) } catch (e) { pushingLogger.error(`Error adding property ${fieldName} to tag ${tagName}`) console.error(e) } } await delay() } } export async function pushCollectionsToLogseqPage() { const collectionItems = zCollectionsState.get() for (const collection of collectionItems) { const pageUUID = id2UUID('zotero_' + collection.key) console.log('>> key & uuid:', collection.key, pageUUID) let page = await logseq.Editor.getPage(pageUUID) if (!page) { page = await logseq.Editor.createPage( `${collection.name}`, {}, { customUUID: pageUUID, redirect: false } as any ) console.log('>> Created new Collection page in Logseq:', page) } // upsert collection properties await logseq.Editor.upsertBlockProperty(page!.uuid, 'key', collection.key || '') // add collection tag const collectionsTag = await logseq.Editor.getTag('collections') await logseq.Editor.addBlockTag(page?.uuid!, collectionsTag?.uuid!) } } export async function pushItemToLogseq( item: Immutable<ZoteroItemEntity>, _isChildItem: boolean = false ) { console.log('>> Pushing item to Logseq:', item) await resolveItemTypesData() const pageUUID = id2UUID(item.key) const pageTitle = item.title || 'Untitled' let page = await logseq.Editor.getPage(pageUUID) if (!page) { page = await logseq.Editor.createPage( `${pageTitle}`, {}, { customUUID: pageUUID, redirect: false } as any ) console.log('>> Created new Z page in Logseq:', page) } // add tag with item type const itemTag = await logseq.Editor.getTag(item.itemType) if (!itemTag) { throw new Error('Logseq tag not found for item type: ' + item.itemType) } await logseq.Editor.addBlockTag(page!.uuid, itemTag.uuid) const fields = itemTypesMapping[item.itemType] || [] // upsert common block properties value const reservedFields = ['key', 'title', 'note'] await logseq.Editor.upsertBlockProperty(page!.uuid, 'key', item.key || '') await logseq.Editor.upsertBlockProperty(page!.uuid, 'title', item.title || '') if (!!item.collections) { // upsert collections as ztags property const collectionsIDs = await Promise.all(item.collections.map(async (colKey) => { const pageUUID = id2UUID('zotero_' + colKey) const colPage = await logseq.Editor.getPage(pageUUID) if (colPage) { return colPage.id } else { pushingLogger.error(`Collection page not found in Logseq for collection key: ${colKey}`) return null } })) await logseq.Editor.upsertBlockProperty(page!.uuid, 'ztags', collectionsIDs) } // upsert all item fields as block properties for (const field of fields) { const fieldName = field.field if (reservedFields.includes(fieldName)) continue const fieldValue = (item as any)[fieldName] || '' try { await logseq.Editor.upsertBlockProperty(page!.uuid, fieldName, fieldValue || '') } catch (e) { console.error(`Error upserting block property ${fieldName} for item ${item.title || 'Untitled'}:`, e) } } // upsert related blocks (notes, attachments, relations, etc.) const notesBlockUUID = id2UUID('zotero_note_' + item.key) let notesBlock = await logseq.Editor.getBlock(notesBlockUUID) const note = item.note?.trim() if (!!note) { if (!notesBlock) { notesBlock = await logseq.Editor.prependBlockInPage(page!.uuid, note, // @ts-ignore { customUUID: notesBlockUUID, }) } else { await logseq.Editor.updateBlock(notesBlock.uuid, note) } } // upsert children attachments as sub-blocks if (!!item.children) { const attachmentTag = await logseq.Editor.getTag('attachment') const attachmentsBlockUUID = id2UUID('zotero_attachments_' + item.key) let attachmentsBlock = await logseq.Editor.getBlock(attachmentsBlockUUID) if (!attachmentsBlock) { attachmentsBlock = await logseq.Editor.appendBlockInPage(page!.uuid, `[[${attachmentTag?.uuid || 'Attachments:'}]]`, // @ts-ignore { customUUID: attachmentsBlockUUID, }) } for (const childItem of item.children) { const attachmentPageUUID = await pushItemToLogseq(childItem, true) const attachmentChildUUID = id2UUID('zotero_child_' + childItem.key) let attachmentChildBlock = await logseq.Editor.getBlock(attachmentChildUUID) let blockContent = `[[${attachmentPageUUID}]] ` blockContent += childItem.url ? childItem.url : `[${childItem.filename}](zotero://select/library/items/${childItem.key})` if (!attachmentChildBlock) { attachmentChildBlock = await logseq.Editor.insertBlock( attachmentsBlock!.uuid, blockContent, // @ts-ignore { customUUID: attachmentChildUUID, } ) } else { await logseq.Editor.updateBlock(attachmentChildBlock.uuid, blockContent) } } } return pageUUID } export async function openItemInLogseq( item: Immutable<ZoteroItemEntity> ) { const pageUUID = id2UUID(item.key) const page = await logseq.Editor.getPage(pageUUID) if (page) { logseq.App.pushState('page', { name: page.name, uuid: page.uuid }) } else { await logseq.UI.showMsg(`Logseq page not found for item: ${item.title || 'Untitled'}`, 'error') throw new Error('Logseq page not found for item: ' + (item.title || 'Untitled')) } } export async function startFullPushToLogseq( opts?: { items: ImmutableArray<ZoteroItemEntity> }) { if (appState.isPushing.get()) return try { appState.isPushing.set(true) if (!opts?.items) { appState.pullingOrPushingProgressMsg.set(`Pushing item types to Logseq tags...`) await pushItemTypesToLogseqTag() appState.pullingOrPushingProgressMsg.set(`Pushing collections to Logseq pages...`) await pushCollectionsToLogseqPage() } appState.pullingOrPushingProgressMsg.set(`Pushing items to Logseq pages...`) const items = opts?.items || zTopItemsState.get() let count = 0 let successCount = 0 for (const item of items) { count++ appState.pullingOrPushingProgressMsg.set(`Pushing items to Logseq pages (${count}/${items.length}) - ${item.title} ...`) pushingLogger.log(`Pushing item ${count}/${items.length}: ${item.title || 'Untitled'}`) try { await pushItemToLogseq(item) successCount++ } catch (e) { const errMsg = `Error pushing item ${item.title || 'Untitled'} to Logseq: ${e}` appState.pullingOrPushingErrorMsg.set(errMsg) pushingLogger.error(errMsg) console.error(e) } await delay(500) // slight delay to avoid blocking } appState.pullingOrPushingProgressMsg.set(`Push to Logseq completed. Pushed ${successCount} items.`) pushingLogger.log('Full push to Logseq completed.') await delay(1000) } catch (e) { appState.pullingOrPushingErrorMsg.set(String(e)) console.error('Error starting full push to Logseq:', e) } finally { appState.isPushing.set(false) appState.pullingOrPushingProgressMsg.set('') } }
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/hooks/useTableSort.ts
TypeScript
// src/hooks/useTableSort.ts import { useMemo } from 'react' import { hookstate, useHookstate } from '@hookstate/core' export type SortDir = 'asc' | 'desc' export default function useTableSort( items: any, initialKey: string | null = null, initialDir: SortDir = 'asc', accessors?: Record<string, (it: any) => any>, ) { const sortKey = useHookstate<string | null>(initialKey) const sortDir = useHookstate<SortDir>(initialDir) const toggleSort = (key: string) => { if (sortKey.get() === key) { sortDir.set(prev => (prev === 'asc' ? 'desc' : 'asc')) } else { sortKey.set(key) sortDir.set('asc') } } const sortedItems = useMemo(() => { const list: any[] = items ? (Array.isArray(items) ? items.slice() : Array.from(items as any)) : [] const currentSortKey = sortKey.get() if (!currentSortKey) return list const getValue = (it: any) => { if (accessors?.[currentSortKey]) return accessors[currentSortKey](it) switch (currentSortKey) { case 'title': case 'itemType': return String(it?.[currentSortKey] || '').toLowerCase() case 'dateModified': { const t = Date.parse(it?.dateModified || '') return Number.isNaN(t) ? 0 : t } case 'collections': return (it?.collections || []).map((c: any) => String(c)).join(',').toLowerCase() case 'attachments': return (it?.children || []).length default: { const v = it?.[currentSortKey] return (v == null ? '' : String(v)).toLowerCase() } } } const currentSortDir = sortDir.get() list.sort((a, b) => { const va = getValue(a) const vb = getValue(b) if (va === vb) return 0 if (typeof va === 'number' && typeof vb === 'number') { return currentSortDir === 'asc' ? va - vb : vb - va } return currentSortDir === 'asc' ? String(va).localeCompare(String(vb)) : String(vb).localeCompare(String(va)) }) return list }, [items, sortKey.get(), sortDir.get(), accessors]) return { sortedItems, sortKey: sortKey.get(), sortDir: sortDir.get(), toggleSort, setSortKey: sortKey.set, setSortDir: sortDir.set, } }
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/index.css
CSS
@import "tailwindcss"; @plugin "daisyui";
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/main.tsx
TypeScript (TSX)
import { createRoot } from 'react-dom/client' import './index.css' import App from './App.tsx' import '@logseq/libs' import { isInLogseq } from './common.ts' import { appState } from './store.ts' function render () { createRoot(document.getElementById('root')!).render(<App/>) } if (isInLogseq) { logseq.ready().then(async () => { render() await logseq.UI.showMsg('hello, zotero') logseq.provideModel({ onZoteroIconClick: async () => { logseq.showMainUI() }, }) // debug icon logseq.App.registerUIItem('toolbar', { key: 'zotero-icon', template: `<a class="button" data-on-click="onZoteroIconClick" title="Zotero Extension"> <i class="ti ti-bookmarks"></i> </a>`, }) // shortcut key logseq.App.registerCommandPalette({ key: 'zotero-show-main-ui', label: 'Show Zotero Extension Main UI', keybinding: { binding: 'z z' }, }, () => { logseq.showMainUI() }) // on main ui show logseq.on('ui:visible:changed', ({ visible }: any) => { if (visible) { appState.isVisible.set(true) } else { setTimeout(() => {appState.isVisible.set(false)}, 300) } }) }, ).catch(console.error) } else { appState.isVisible.set(true) render() }
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
src/store.ts
TypeScript
// @ts-ignore import * as z from 'zotero-api-client' import { hookstate, type Immutable, type ImmutableArray, type State, useHookstate } from '@hookstate/core' import { useCallback, useEffect } from 'react' export type ZoteroItemEntity = { key: string, title: string, itemType: string, note: string, dateAdded: string, dateModified: string, tags: Array<any>, collections: Array<string>, children?: Array<ZoteroItemEntity>, [key: string]: any } export type ZoteroCollectionEntity = { key: string, name: string, parentCollectionKey: string | null, dateAdded: string, dateModified: string, [key: string]: any } export type ZoteroTagEntity = { tag: string, meta: any } export type UserSettings = { apiKey: string, userId: string, [key: string]: any } export const appState = hookstate({ isVisible: true, isPushing: false, // sync to logseq isPulling: false, // sync from remote Zotero pushingLogs: [''], pullingOrPushingErrorMsg: '', pullingOrPushingProgressMsg: '', userSettings: JSON.parse(localStorage.getItem('zotero_user_settings') || '{}') as UserSettings }) export const zTopItemsState = hookstate<Array<ZoteroItemEntity>>([]) export const zCollectionsState = hookstate<Array<ZoteroCollectionEntity>>([]) export const zTagsState = hookstate<Array<ZoteroTagEntity>>([]) function createLocalZoteroAPI() { const userSettings = appState.userSettings.get() as any const apiKey = userSettings.apiKey const userId = userSettings.userId return z.default(apiKey).library('user', userId) as any } export let zLocalApi = createLocalZoteroAPI() export function validateZoteroCredentials() { return zLocalApi.items().top().get({ limit: 1 }) } export function setZoteroUserSettings(settings: any) { const cachedSettings = localStorage.getItem('zotero_user_settings') const mergedSettings = { ...JSON.parse(cachedSettings || '{}'), ...settings } localStorage.setItem('zotero_user_settings', JSON.stringify(mergedSettings)) appState.userSettings.set(mergedSettings) zLocalApi = createLocalZoteroAPI() } function createZRequestHookState<T = any>(opts: { itemsState: State<T[], {}>, zGetFn: (opts: any) => Promise<any> }) { return () => { const loading = useHookstate(false) const items = useHookstate<T[]>(opts.itemsState) const fetch = useCallback(async (opts1: any) => { opts1 = { limit: 50, start: items.get().length, ...opts1 } try { const r = await opts.zGetFn(opts1) if (typeof r?.getData === 'function') { return r.getData() } else { return r } } catch (e) { console.error('Zotero API fetch error:', e) } }, []) const load = useCallback(async (opts1: any) => { if (loading.get()) return try { loading.set(true) const data = await fetch(opts1) items.merge(data) return data?.length } finally { loading.set(false) } }, []) const reset = useCallback(() => { items.set([]) loading.set(false) }, []) const refresh = useCallback(async (opts1: any) => { reset() await load(opts1) }, []) return { fetch, load, reset, refresh, loading: loading.get(), items: items.get() } } } function createLoggerActions(state: State<Array<string>>) { const actions = ['log', 'error', 'clear'] as const return actions.reduce((acc, action) => { acc[action] = (...args: any) => { const msg = args.length === 1 ? args[0] : args.join(' ') if (action === 'clear') { state.set([]) } else { const isError = action === 'error' const prefix = isError ? '[ERROR]' : '[LOG]' const timestamp = new Date().toLocaleTimeString() state.merge([`${timestamp} ${prefix} ${String(msg)}`]) if (isError) console.error(msg) } } return acc }, {} as { log: (msg: any) => void, error: (msg: any) => void, clear: () => void }) } export const pushingLogger = createLoggerActions(appState.pushingLogs) export const useAppState = () => { return useHookstate(appState) } export const useCollections = createZRequestHookState<ZoteroCollectionEntity>({ itemsState: zCollectionsState, zGetFn: async (opts: any) => { return zLocalApi.collections().get(opts) } }) export const useTopItems = createZRequestHookState<ZoteroItemEntity>({ itemsState: zTopItemsState, zGetFn: async (opts: any) => { const res = await zLocalApi.items().top().get(opts) const items: Array<ZoteroItemEntity> = res.getData() if (items?.length) { // fetch children notes for each item for (const item of items) { if (item.itemType === 'note') continue appState.pullingOrPushingProgressMsg.set(`Fetching children for item ${item.title || item.key}...`) try { const res = await zLocalApi.items(item.key).children().get() const children = res.getData() if (children?.length) { item.children = children } } catch (e) { console.error('Error fetching children for item', item.key, e) } } } return items } }) export const useZTags = createZRequestHookState({ itemsState: zTagsState, zGetFn: async (opts: any) => { return zLocalApi.tags().get(opts) } }) // @ts-ignore window.__state__ = { appState, zTopItemsState, zCollectionsState, zTagsState } export function useTopItemsGroupedByCollection() { const collectionsState = useCollections() const topItemsState = useTopItems() const groupedCollections: Record<string, ZoteroCollectionEntity> = collectionsState.items?.reduce((acc, coll) => { acc[coll.key] = coll return acc }, {} as any) const groupedItems: Record<string, Immutable<ZoteroItemEntity>[]> = {} for (const collection of collectionsState.items) { groupedItems[collection.key] = [] } groupedItems['uncategorized'] = [] for (const item of topItemsState.items) { if (item.collections && item.collections.length > 0) { for (const collKey of item.collections) { if (groupedItems[collKey]) { groupedItems[collKey].push(item) } } } else { groupedItems['uncategorized'].push(item) } } return { groupedCollections, groupedItems } } export function useCacheZEntitiesEffects() { const zTagsState1 = useZTags() const zCollectionsState1 = useCollections() const zTopItemsState1 = useTopItems() const persistData = useCallback((k: string, data: any) => { localStorage.setItem(`zotero_cache_${k}`, JSON.stringify(data)) }, []) const restoreData = useCallback((k: string) => { const data = localStorage.getItem(`zotero_cache_${k}`) return data ? JSON.parse(data) : null }, []) // restore cached entities on mount useEffect(() => { const cachedTags = restoreData('tags') zTagsState.set(cachedTags ?? []) const cachedCollections = restoreData('collections') zCollectionsState.set(cachedCollections ?? []) const cachedTopItems = restoreData('topItems') zTopItemsState.set(cachedTopItems ?? []) }, []) useEffect(() => { persistData('tags', zTagsState1.items) }, [zTagsState1.items?.length]) useEffect(() => { persistData('collections', zCollectionsState1.items) }, [zCollectionsState1.items?.length]) useEffect(() => { persistData('topItems', zTopItemsState1.items) }, [zTopItemsState1.items?.[0]?.key]) } export function useFilteredTopItems() { const zTopItemsState1 = useTopItems() const filteredQueryState = useHookstate({ q: '', filterItemTypes: [] as Array<string>, filterCollections: [] as Array<string> }) // filter items based on types let filteredItems = zTopItemsState1.items.filter(item => { const filterItemTypes = filteredQueryState.get().filterItemTypes if (filterItemTypes.length === 0) return true return filterItemTypes.includes(item.itemType) }) // filter items based on collections filteredItems = filteredItems.filter(item => { const filterCollections = filteredQueryState.get().filterCollections if (filterCollections.length === 0) return true if (!item.collections || item.collections.length === 0) { return filterCollections.includes('uncategorized') } return item.collections.some((collKey: string) => filterCollections.includes(collKey)) }) filteredItems = filteredItems.filter(item => { const qText = filteredQueryState.get().q.toLowerCase() if (!qText) return true const fieldsToSearch = [ item.title?.toLowerCase() || '', item.itemType?.toLowerCase() || '', (item.tags || []).map((t: any) => t.tag.toLowerCase()).join(' ') ] return fieldsToSearch.some(field => field.includes(qText)) }) return { filteredQueryState, filteredItems } } export function usePaginatedTopItems({ filteredItems, limit }: { limit: number, filteredItems: ImmutableArray<ZoteroItemEntity> }) { const currentPageState = useHookstate(0) limit = limit ?? 10 const totalItems = filteredItems.length const totalPages = Math.ceil(totalItems / limit) const paginatedItems = filteredItems.slice( currentPageState.get() * limit, (currentPageState.get() + 1) * limit ) const goToPage = (page: number) => { if (page < 0 || page >= totalPages) return currentPageState.set(page) } const reset = () => { currentPageState.set(0) } const paginatedLabelNums: Array<number | string> = [] for (let i = 0; i < totalPages; i++) { paginatedLabelNums.push(i + 1) } if (paginatedLabelNums.length > limit) { const maxHalf = Math.floor(paginatedLabelNums.length / 2) const start = Math.min(6, maxHalf) const spliceCount = Math.max(maxHalf - 5, 1) paginatedLabelNums.splice(start, spliceCount, '...') } return { paginatedItems, currentPage: currentPageState.get(), totalPages, goToPage, reset, paginatedLabelNums } }
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
vite.config.ts
TypeScript
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' // https://vite.dev/config/ export default defineConfig({ plugins: [ react(), tailwindcss() ], })
xyhp915/logseq-zotero-plugin
8
A simple Logseq plugin for Zotero.
TypeScript
xyhp915
Charlie
logseq
gsr/__init__.py
Python
"""Google Search Resource (GSR) - Research Tool Components"""
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
gsr/browser.py
Python
""" Browser initialization and standard environment configuration """ import random import time from playwright.sync_api import sync_playwright import logging logger = logging.getLogger(__name__) class BrowserManager: """Manages browser initialization with standard browser environment settings""" def __init__(self, session_manager, headless=False, block_images=False): self.session_manager = session_manager self.headless = headless self.block_images = block_images self.browser = None self.context = None self.page = None def initialize(self, session_data=None): """Initialize browser with standard environment configuration""" playwright = sync_playwright().start() if session_data: profile = session_data["profile"] else: profile = self.session_manager.create_session_profile() # Browser selection if "Firefox" in profile["user_agent"]: browser_type = playwright.firefox else: browser_type = playwright.chromium # Launch with standard browser arguments self.browser = browser_type.launch( headless=self.headless, args=[ "--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage", "--no-sandbox", "--disable-web-security", "--disable-features=IsolateOrigins,site-per-process", f'--window-size={profile["viewport"]["width"]},{profile["viewport"]["height"]}', ], ) # Create context context_params = { "viewport": profile["viewport"], "user_agent": profile["user_agent"], "timezone_id": profile["timezone"], "locale": profile["locale"], } if session_data and session_data.get("storage_state"): storage_path = session_data["path"] / "storage_state.json" if storage_path.exists(): context_params["storage_state"] = str(storage_path) self.context = self.browser.new_context(**context_params) if session_data and session_data.get("cookies"): self.context.add_cookies(session_data["cookies"]) self.page = self.context.new_page() # Block images if requested if self.block_images: self._setup_image_blocking() self._configure_standard_browser_environment() return profile def _setup_image_blocking(self): """Block image loading for faster page loads""" def handle_route(route): if route.request.resource_type in ["image", "media", "font", "stylesheet"]: route.abort() else: route.continue_() self.page.route("**/*", handle_route) logger.info("Image blocking enabled (faster loading, less bandwidth)") def _configure_standard_browser_environment(self): """ Configure browser to behave like a standard user browser for research purposes. Sets up realistic browser properties including navigator objects, plugins, and permissions to match typical browser behavior patterns. """ browser_config_js = """ // Configure navigator.webdriver property Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); // Configure standard plugins array Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] }); // Configure standard language preferences Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] }); // Configure Chrome runtime (for Chromium-based browsers) window.chrome = { runtime: {} }; // Configure standard permissions behavior const originalQuery = window.navigator.permissions.query; window.navigator.permissions.query = (parameters) => ( parameters.name === 'notifications' ? Promise.resolve({ state: Notification.permission }) : originalQuery(parameters) ); // Ensure native function appearance const originalToString = Function.prototype.toString; Function.prototype.toString = function() { if (this === window.navigator.permissions.query) { return 'function query() { [native code] }'; } return originalToString.call(this); }; """ self.page.add_init_script(browser_config_js) def warm_up_session(self): """Warm up session by navigating to Google""" logger.info("Warming up session...") self.page.goto("https://www.google.com") time.sleep(random.uniform(1, 3)) # Accept cookies if present self._handle_cookie_consent() # Random mouse movements self._random_mouse_movement() logger.info("Session warmup complete") def _handle_cookie_consent(self): """Handle cookie consent dialogs""" cookie_buttons = [ 'button:has-text("Accept all")', 'button:has-text("I agree")', 'button:has-text("Reject all")', 'button[id*="accept"]', 'button[id*="agree"]', 'div[role="button"]:has-text("Accept")', ] for button_selector in cookie_buttons: try: button = self.page.locator(button_selector).first if button.is_visible(timeout=2000): button.click() time.sleep(random.uniform(1, 2)) return except: continue def _random_mouse_movement(self): """Perform random mouse movements""" viewport = self.page.viewport_size if not viewport: return for _ in range(random.randint(2, 4)): x = random.randint(100, viewport["width"] - 100) y = random.randint(100, viewport["height"] - 100) self.page.mouse.move(x, y, steps=random.randint(5, 15)) time.sleep(random.uniform(0.1, 0.3)) def close(self): """Close browser and clean up""" if self.context: self.context.close() if self.browser: self.browser.close() self.page = None self.context = None self.browser = None
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
gsr/captcha.py
Python
""" CAPTCHA detection and handling """ import time from typing import Optional, Dict from datetime import datetime import logging from .enums import CAPTCHAType logger = logging.getLogger(__name__) class CAPTCHADetector: """Detects various types of Google CAPTCHAs and blocks""" @staticmethod def detect_captcha(page) -> tuple[bool, Optional[CAPTCHAType], Optional[Dict]]: """ Detect if CAPTCHA is present on the page Returns: (is_captcha_present, captcha_type, details) """ # Check page content page_content = page.content().lower() page_url = page.url.lower() # Detection patterns patterns = { CAPTCHAType.RECAPTCHA_V2: [ 'class="g-recaptcha"', "data-sitekey", "recaptcha/api2", "recaptcha__en", "recaptcha-checkbox", 'id="recaptcha"', ], CAPTCHAType.UNUSUAL_TRAFFIC: [ "unusual traffic", "automated requests", "computer network", "sorry, your computer or network may be sending automated queries", ], CAPTCHAType.SUSPICIOUS_ACTIVITY: [ "suspicious activity", "verify you are human", "confirm you are not a robot", ], } # Check for each CAPTCHA type for captcha_type, keywords in patterns.items(): for keyword in keywords: if keyword in page_content: logger.warning(f"CAPTCHA detected: {captcha_type.value}") # Extract additional details details = CAPTCHADetector._extract_captcha_details(page, captcha_type) return True, captcha_type, details # Check URL for CAPTCHA/sorry pages if "sorry/index" in page_url or "recaptcha" in page_url: logger.warning("CAPTCHA page detected in URL") return True, CAPTCHAType.UNKNOWN, {"url": page_url} # Check for reCAPTCHA iframe (must be visible and blocking) try: # Check if reCAPTCHA iframe actually exists and is visible recaptcha_iframes = page.locator('iframe[src*="recaptcha"]') if recaptcha_iframes.count() > 0: # Check if it's a visible challenge (not just the invisible badge) visible_challenge = page.locator('iframe[src*="recaptcha"][src*="bframe"]') if visible_challenge.count() > 0: logger.warning("reCAPTCHA iframe detected") return True, CAPTCHAType.RECAPTCHA_V2, {"has_iframe": True} except: pass # Check if search results are present (inverse check) try: if "google.com/search" in page_url and "tbm=isch" not in page_url: # We're on a search page - check for actual results search_div = page.locator("div#search").count() result_items = 0 # Strategy 1: Try stable selectors stable_selectors = ["div.g", "div[data-sokoban-container]", "a[jsname]"] for selector in stable_selectors: count = page.locator(selector).count() if count > 0: result_items = count break # Strategy 2: Dynamic discovery (look for divs with hash-like classes) if result_items == 0: # Find divs with 6-char mixed-case class names that contain h3+a all_divs = page.locator("div").all() for div in all_divs[:100]: # Limit search for performance try: class_attr = div.get_attribute("class") if class_attr: classes = class_attr.split() for cls in classes: if len(cls) == 6 and cls.isalpha(): if any(c.isupper() for c in cls) and any( c.islower() for c in cls ): # Check if it has result structure if ( div.locator("h3").count() > 0 and div.locator("a").count() > 0 ): result_items += 1 break except: continue if result_items > 0: break # If search div exists but no result items, might be blocked if search_div > 0 and result_items == 0: # Double check it's not just loading time.sleep(1) # Quick recheck with stable selectors for selector in stable_selectors: count = page.locator(selector).count() if count > 0: result_items = count break # Still no results - likely blocked if result_items == 0: logger.warning("No search results found - possible block") return True, CAPTCHAType.UNKNOWN, {"no_results": True} except: pass return False, None, None @staticmethod def _extract_captcha_details(page, captcha_type) -> Dict: """Extract details about the CAPTCHA for solving""" details = { "type": captcha_type.value, "url": page.url, "timestamp": datetime.now().isoformat(), } if captcha_type == CAPTCHAType.RECAPTCHA_V2: try: # Try to get site key sitekey_element = page.locator("[data-sitekey]") if sitekey_element.count() > 0: details["sitekey"] = sitekey_element.first.get_attribute("data-sitekey") # Check if it's invisible details["invisible"] = "invisible" in page.content().lower() except Exception as e: logger.error(f"Error extracting reCAPTCHA details: {e}") elif captcha_type == CAPTCHAType.UNUSUAL_TRAFFIC: # Extract any specific message try: message_element = page.locator('div:has-text("unusual traffic")') if message_element.count() > 0: details["message"] = message_element.first.text_content() except: pass return details
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
gsr/cli.py
Python
""" Google Search Resource (GSR) - Main Entry Point Research tool for analyzing Google search page structure """ import argparse import logging import sys import json from pathlib import Path from gsr.searcher import HumanLikeGoogleSearcher from gsr.enums import SearchStatus logger = logging.getLogger(__name__) def load_config_file(config_path): """Load configuration from YAML or JSON file""" if not config_path: return {} config_file = Path(config_path) if not config_file.exists(): logger.error(f"Config file not found: {config_path}") sys.exit(1) try: with open(config_file, "r") as f: content = f.read() # Try JSON first try: config = json.loads(content) logger.info(f"Loaded JSON config from {config_path}") return config except json.JSONDecodeError: pass # Try YAML try: import yaml config = yaml.safe_load(content) logger.info(f"Loaded YAML config from {config_path}") return config except ImportError: logger.error("YAML support requires 'pyyaml' package: pip install pyyaml") sys.exit(1) except Exception as e: logger.error(f"Failed to parse config file: {e}") sys.exit(1) except Exception as e: logger.error(f"Error reading config file: {e}") sys.exit(1) def merge_config(args, config): """ Merge config file with command-line args (CLI takes precedence) Priority order: 1. User explicitly set via CLI (not None) 2. Value from config file (if present) 3. Default value (applied last) """ # Define defaults here (to be applied last) defaults = { "query": "python web scraping", "headless": False, "new_session": False, "session_id": None, "typing": "normal", "max_results": 5, "verbose": 0, "quiet": False, "timeout": 30, "browser": None, "output_format": "text", "no_images": False, } # Map config keys to argument names config_mapping = { "query": "query", "headless": "headless", "new_session": "new_session", "session_id": "session_id", "typing": "typing", "max_results": "max_results", "verbose": "verbose", "quiet": "quiet", "timeout": "timeout", "browser": "browser", "output_format": "output_format", "no_images": "no_images", } # Apply values in priority order: CLI > Config > Defaults for config_key, arg_name in config_mapping.items(): current_value = getattr(args, arg_name) # If user explicitly set via CLI (not None), keep it if current_value is not None: continue # Try config file next if config and config_key in config: config_value = config[config_key] # Handle verbose specially (can be bool or int) if arg_name == "verbose" and isinstance(config_value, bool): setattr(args, arg_name, 1 if config_value else 0) else: setattr(args, arg_name, config_value) else: # Finally, apply default value setattr(args, arg_name, defaults[arg_name]) return args def parse_args(): """Parse command-line arguments""" parser = argparse.ArgumentParser( description="Google Search Resource (GSR) - Research Tool", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: %(prog)s # Default: visible browser, normal typing %(prog)s --headless # Run without browser window %(prog)s --query "machine learning" # Search for specific query %(prog)s --new-session # Force create new session %(prog)s --session-id session_123 # Use specific session %(prog)s --typing fast # Fast typing speed %(prog)s --headless --query "AI" --typing slow # Combined options """, ) parser.add_argument( "--query", "-q", type=str, default=None, help='Search query (default: "python web scraping")', ) parser.add_argument( "--headless", action="store_true", default=None, help="Run browser in headless mode (no window)" ) parser.add_argument( "--new-session", action="store_true", default=None, help="Force create new session instead of reusing" ) parser.add_argument( "--session-id", type=str, default=None, help="Force use specific session ID" ) parser.add_argument( "--typing", type=str, choices=["fast", "normal", "slow"], default=None, help="Typing speed style (default: normal)", ) parser.add_argument( "--max-results", type=int, default=None, help="Maximum number of results to display (default: 5)", ) parser.add_argument( "--verbose", "-v", action="count", default=None, help="Increase verbosity (-v: INFO, -vv: DEBUG)", ) parser.add_argument( "--quiet", action="store_true", default=None, help="Suppress all output except results (overrides --verbose)", ) parser.add_argument( "--timeout", type=int, default=None, help="Timeout in seconds for page operations (default: 30)", ) parser.add_argument( "--browser", type=str, choices=["chromium", "firefox"], default=None, help="Browser to use (default: auto-select)", ) parser.add_argument( "--output-format", type=str, choices=["text", "json", "csv"], default=None, help="Output format (default: text)", ) parser.add_argument( "--no-images", action="store_true", default=None, help="Disable image loading (faster, less bandwidth)" ) parser.add_argument("--config", type=str, help="Load configuration from file (YAML or JSON)") return parser.parse_args() def setup_logging(verbosity, quiet): """Configure logging based on verbosity level""" if quiet: # Suppress all logging logging.basicConfig(level=logging.CRITICAL + 1) return False # Don't show banner elif verbosity == 0: # Default: WARNING and above (minimal output) logging.basicConfig(level=logging.WARNING, format="%(levelname)s: %(message)s") return True elif verbosity == 1: # -v: INFO level logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(name)s: %(message)s") return True else: # -vv: DEBUG level logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(levelname)s:%(name)s: %(message)s" ) return True def output_results(results, format_type, query, args): """Output results in specified format""" if format_type == "json": import json output = {"query": query, "count": len(results), "results": results} print(json.dumps(output, indent=2)) elif format_type == "csv": import csv import io output = io.StringIO() if results: writer = csv.DictWriter(output, fieldnames=["title", "url", "snippet"]) writer.writeheader() writer.writerows(results) print(output.getvalue(), end="") else: # text format (default) print(f"Found {len(results)} results") print() for i, r in enumerate(results[: args.max_results], 1): print(f"{i}. {r['title']}") print(f" {r['url']}") if r["snippet"]: print(f" {r['snippet'][:100]}...") print() def main(): """Main entry point - simple search research example""" args = parse_args() # Load config file if specified config = load_config_file(args.config) args = merge_config(args, config) # Setup logging show_banner = setup_logging(args.verbose, args.quiet) # Show banner and configuration (unless quiet) if show_banner and not args.quiet: print("=" * 50) print("Google Search Resource (GSR)") print("Research Tool - Educational Use Only") print("=" * 50) print() # Show configuration if args.headless: print("🔕 Mode: Headless (no browser window)") else: print("👁️ Mode: Visible browser window") print(f"⌨️ Typing: {args.typing}") print(f"🔍 Query: {args.query}") if args.browser: print(f"🌐 Browser: {args.browser}") if args.session_id: print(f"📁 Session: {args.session_id} (forced)") elif args.new_session: print("📁 Session: New (forced)") if args.output_format != "text": print(f"📄 Output: {args.output_format}") print() searcher = HumanLikeGoogleSearcher( headless=args.headless, typing_style=args.typing, session_id=args.session_id, block_images=args.no_images, ) try: result = searcher.search(args.query, reuse_session=not args.new_session) if result.status == SearchStatus.SUCCESS: output_results(result.results, args.output_format, args.query, args) elif result.status == SearchStatus.CAPTCHA_DETECTED: print(f"CAPTCHA detected: {result.captcha_info['type']}") print("Rate limit reached - stopping as requested by Google") print(f"Details: {result.captcha_info}") elif result.status == SearchStatus.BLOCKED: print(f"Blocked! {result.error}") else: print(f"Error: {result.error}") # Show statistics (unless quiet or non-text output) if not args.quiet and args.output_format == "text": print() print("=" * 50) stats = searcher.get_statistics() print(f"Statistics:") print(f" Total searches: {stats['total_searches']}") print(f" Successful: {stats['successful_searches']}") print(f" CAPTCHAs: {stats['captcha_encounters']}") print(f" Success rate: {stats['success_rate']:.1%}") print("=" * 50) finally: searcher.close() if __name__ == "__main__": main()
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
gsr/enums.py
Python
""" Enumeration types for search status and CAPTCHA detection """ from enum import Enum class SearchStatus(Enum): """Status codes for search results""" SUCCESS = "success" CAPTCHA_DETECTED = "captcha_detected" BLOCKED = "blocked" RATE_LIMITED = "rate_limited" ERROR = "error" TIMEOUT = "timeout" class CAPTCHAType(Enum): """Types of CAPTCHAs/blocks Google uses""" RECAPTCHA_V2 = "recaptcha_v2" RECAPTCHA_V3 = "recaptcha_v3" UNUSUAL_TRAFFIC = "unusual_traffic" SUSPICIOUS_ACTIVITY = "suspicious_activity" UNKNOWN = "unknown"
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
gsr/models.py
Python
""" Data models for search results """ from typing import List, Dict from datetime import datetime from .enums import SearchStatus class SearchResult: """Container for search results with status information""" def __init__( self, status: SearchStatus, results: List = None, captcha_info: Dict = None, error: str = None, ): self.status = status self.results = results or [] self.captcha_info = captcha_info self.error = error self.timestamp = datetime.now().isoformat() def to_dict(self): return { "status": self.status.value, "results": self.results, "captcha_info": self.captcha_info, "error": self.error, "timestamp": self.timestamp, }
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
gsr/searcher.py
Python
""" Human-like Google search implementation for research purposes """ import random import time from datetime import datetime, timedelta from typing import Optional, Callable import logging from .enums import SearchStatus, CAPTCHAType from .models import SearchResult from .captcha import CAPTCHADetector from .session import SessionManager from .browser import BrowserManager logger = logging.getLogger(__name__) class HumanLikeGoogleSearcher: """Enhanced Google searcher with CAPTCHA detection and handling""" def __init__( self, captcha_callback: Optional[Callable] = None, auto_retry_on_captcha: bool = False, max_retries: int = 3, headless: bool = False, typing_style: str = "normal", session_id: Optional[str] = None, block_images: bool = False, ): """ Initialize searcher with CAPTCHA handling options Args: captcha_callback: Function to call when CAPTCHA detected auto_retry_on_captcha: Whether to retry on CAPTCHA max_retries: Maximum retry attempts headless: Run browser in headless mode (no window) typing_style: Typing speed ('fast', 'normal', 'slow') session_id: Force specific session ID (None = auto) block_images: Block image loading (faster, less bandwidth) """ self.session_manager = SessionManager() self.captcha_detector = CAPTCHADetector() self.browser_manager = None self.current_session = None self.forced_session_id = session_id self.headless = headless self.default_typing_style = typing_style self.block_images = block_images # CAPTCHA handling self.captcha_callback = captcha_callback self.auto_retry_on_captcha = auto_retry_on_captcha self.max_retries = max_retries self.captcha_count = 0 self.last_captcha_time = None # Statistics self.stats = { "total_searches": 0, "successful_searches": 0, "captcha_encounters": 0, "blocks": 0, "errors": 0, } self.typing_patterns = { "fast": (5, 40), "normal": (30, 110), "slow": (100, 250), } def search(self, query: str, reuse_session: bool = True, retry_count: int = 0) -> SearchResult: """Perform a search with CAPTCHA detection""" try: logger.info(f"Searching for: {query}") # Initialize browser if needed if not self.browser_manager or not self.browser_manager.page: self._initialize_or_reuse_session(reuse_session) page = self.browser_manager.page # Navigate to Google if needed if "google.com" not in page.url: page.goto("https://www.google.com") time.sleep(random.uniform(1, 2)) # Check for CAPTCHA is_captcha, captcha_type, details = self.captcha_detector.detect_captcha(page) if is_captcha: return self._handle_captcha(captcha_type, details, query, retry_count) # Perform search self._perform_search_actions(query) # Check for CAPTCHA after search is_captcha, captcha_type, details = self.captcha_detector.detect_captcha(page) if is_captcha: return self._handle_captcha(captcha_type, details, query, retry_count) # Extract results results = self._extract_results() # Update statistics self.stats["total_searches"] += 1 self.stats["successful_searches"] += 1 # Update session if self.current_session: self.current_session["profile"]["search_count"] += 1 self.current_session["profile"]["last_used"] = datetime.now().isoformat() self._save_current_session() return SearchResult(status=SearchStatus.SUCCESS, results=results) except Exception as e: logger.error(f"Search error: {e}") self.stats["errors"] += 1 return SearchResult(status=SearchStatus.ERROR, error=str(e)) def _handle_captcha( self, captcha_type: CAPTCHAType, details: dict, query: str, retry_count: int ) -> SearchResult: """Handle CAPTCHA detection""" logger.warning(f"CAPTCHA encountered: {captcha_type.value}") self.captcha_count += 1 self.last_captcha_time = datetime.now() self.stats["captcha_encounters"] += 1 captcha_info = { "type": captcha_type.value, "details": details, "encounter_count": self.captcha_count, "session_id": self.current_session["profile"]["id"] if self.current_session else None, } # Check if it's a hard block if captcha_type == CAPTCHAType.UNUSUAL_TRAFFIC: self.stats["blocks"] += 1 self._close_browser() self.current_session = None return SearchResult( status=SearchStatus.BLOCKED, captcha_info=captcha_info, error="Blocked by Google - unusual traffic detected", ) # Try callback if provided if self.captcha_callback: try: solution = self.captcha_callback(captcha_type, details, self.browser_manager.page) if solution: return self.search(query, reuse_session=True, retry_count=retry_count) except Exception as e: logger.error(f"CAPTCHA callback error: {e}") # Auto-retry with new session if configured if self.auto_retry_on_captcha and retry_count < self.max_retries: wait_time = min(30 * (retry_count + 1), 120) logger.info(f"Auto-retry {retry_count + 1}/{self.max_retries} after {wait_time}s") time.sleep(wait_time) self._close_browser() self.current_session = None return self.search(query, reuse_session=False, retry_count=retry_count + 1) return SearchResult(status=SearchStatus.CAPTCHA_DETECTED, captcha_info=captcha_info) def _initialize_or_reuse_session(self, reuse_session: bool): """Initialize or reuse browser session""" # If forced session ID is specified, load it if self.forced_session_id: self.current_session = self.session_manager.load_session(self.forced_session_id) if self.current_session: logger.info(f"Using forced session: {self.forced_session_id}") self.browser_manager = BrowserManager( self.session_manager, self.headless, self.block_images ) self.browser_manager.initialize(self.current_session) self.browser_manager.warm_up_session() return else: logger.warning(f"Forced session '{self.forced_session_id}' not found, creating new") reuse_session = False # Check if we should create new session due to recent CAPTCHA if self.last_captcha_time: time_since_captcha = datetime.now() - self.last_captcha_time if time_since_captcha < timedelta(minutes=5): reuse_session = False # Decide whether to use existing session or create new one if reuse_session and self.current_session: if not self.session_manager.should_create_new_session(self.current_session): return else: self._close_browser() self.current_session = None # Load or create session if self.current_session is None: if reuse_session: self.current_session = self.session_manager.load_session() if self.current_session: logger.info(f"Loaded session: {self.current_session['profile']['id']}") self.browser_manager = BrowserManager( self.session_manager, self.headless, self.block_images ) self.browser_manager.initialize(self.current_session) self.browser_manager.warm_up_session() return # Create new session self.browser_manager = BrowserManager(self.session_manager, self.headless) profile = self.browser_manager.initialize() self.current_session = { "profile": profile, "cookies": None, "storage_state": None, "path": self.session_manager.session_dir / profile["id"], } logger.info(f"Created session: {profile['id']}") self.browser_manager.warm_up_session() def _perform_search_actions(self, query): """Perform the actual search with human-like behavior""" page = self.browser_manager.page # Find search box search_box = None selectors = [ 'textarea[name="q"]', 'input[name="q"]', 'textarea[title*="Search"]', 'input[title*="Search"]', ] for selector in selectors: try: search_box = page.locator(selector) if search_box.count() > 0: break except: continue if not search_box or search_box.count() == 0: raise Exception("Search box not found") # Click search box search_box.click(position={"x": random.randint(10, 50), "y": random.randint(5, 15)}) time.sleep(random.uniform(0.3, 0.8)) # Clear and type query search_box.clear() # Use default_typing_style if set, otherwise use session profile typing_speed = self.default_typing_style if not typing_speed and self.current_session: typing_speed = self.current_session["profile"].get("typing_speed", "normal") self._type_with_personality(search_box, query, typing_speed or "normal") # Submit time.sleep(random.uniform(0.5, 1.5)) search_box.press("Enter") # Wait for results try: page.wait_for_selector("div#search", timeout=10000) except: pass time.sleep(random.uniform(1, 2)) def _type_with_personality(self, element, text, typing_speed="normal"): """Type with human-like patterns""" pattern = self.typing_patterns.get(typing_speed, self.typing_patterns["normal"]) for char in text: element.type(char, delay=random.randint(*pattern)) if random.random() < 0.05: time.sleep(random.uniform(0.5, 1.5)) def _discover_result_containers(self, page): """Dynamically discover result containers by structure, not hardcoded classes""" try: # Look for divs that contain the structure of a search result (h3 + link) # This is more resilient than hardcoded class names containers = page.query_selector_all("div") result_containers = [] for container in containers: # Check if this div looks like a result container try: # Must have: h3 (title) and a (link) has_title = container.query_selector("h3") is not None has_link = container.query_selector("a") is not None if has_title and has_link: # Check if class name looks like a hash (6 chars, mixed case) class_attr = container.get_attribute("class") if class_attr: classes = class_attr.split() for cls in classes: # Hash pattern: 6 chars, contains both upper and lower if len(cls) == 6 and cls.isalpha(): if any(c.isupper() for c in cls) and any( c.islower() for c in cls ): result_containers.append(container) break except: continue return result_containers except: return [] def _extract_results(self): """Extract search results""" results = [] page = self.browser_manager.page try: # Strategy 1: Try known stable selectors first stable_selectors = [ "div.g", # Classic (stable) "div[data-sokoban-container]", # Attribute-based (stable) ] result_elements = [] for selector in stable_selectors: result_elements = page.query_selector_all(selector) if result_elements: logger.info(f"Found results using stable selector: {selector}") break # Strategy 2: If stable selectors fail, discover containers dynamically if not result_elements: logger.info("Stable selectors failed, discovering containers dynamically...") result_elements = self._discover_result_containers(page) if result_elements: logger.info(f"Discovered {len(result_elements)} result containers by structure") # Strategy 3: Last resort - try current known working selector if not result_elements: result_elements = page.query_selector_all("div.MjjYud") if result_elements: logger.info("Found results using known working selector: div.MjjYud") if not result_elements: logger.warning("No result containers found using any strategy") return results for element in result_elements[:10]: try: title_elem = element.query_selector("h3") link_elem = element.query_selector("a") # Try multiple snippet selectors (Google changes these frequently) snippet_elem = element.query_selector( "div[data-content-feature], div.VwiC3b, div[data-sncf], span" ) if title_elem and link_elem: results.append( { "title": title_elem.text_content(), "url": link_elem.get_attribute("href"), "snippet": snippet_elem.text_content() if snippet_elem else None, } ) except: continue logger.info(f"Extracted {len(results)} results") except Exception as e: logger.error(f"Error extracting results: {e}") return results def _save_current_session(self): """Save session state""" if not self.current_session or not self.browser_manager.context: return try: cookies = self.browser_manager.context.cookies() storage_state = self.browser_manager.context.storage_state() self.session_manager.save_session( self.current_session["profile"], cookies, storage_state ) except Exception as e: logger.error(f"Error saving session: {e}") def _close_browser(self): """Close browser and clean up""" if self.browser_manager: self._save_current_session() self.browser_manager.close() self.browser_manager = None def get_statistics(self): """Get search statistics""" return { **self.stats, "success_rate": ( self.stats["successful_searches"] / self.stats["total_searches"] if self.stats["total_searches"] > 0 else 0 ), "captcha_rate": ( self.stats["captcha_encounters"] / self.stats["total_searches"] if self.stats["total_searches"] > 0 else 0 ), "current_session": ( self.current_session["profile"]["id"] if self.current_session else None ), "last_captcha": self.last_captcha_time.isoformat() if self.last_captcha_time else None, } def close(self): """Clean shutdown""" self._close_browser() logger.info(f"Final statistics: {self.get_statistics()}")
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
gsr/session.py
Python
""" Session management for browser persistence """ import random import json from datetime import datetime, timedelta from pathlib import Path class SessionManager: """Manages browser sessions""" def __init__(self, session_dir="./sessions"): self.session_dir = Path(session_dir) self.session_dir.mkdir(exist_ok=True) def create_session_profile(self): """Create a unique session profile""" session_id = ( f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{random.randint(1000, 9999)}" ) profile = { "id": session_id, "created_at": datetime.now().isoformat(), "last_used": datetime.now().isoformat(), "search_count": 0, "searches": [], "user_agent": self._get_random_user_agent(), "viewport": {"width": random.randint(1200, 1920), "height": random.randint(800, 1080)}, "timezone": random.choice( ["America/New_York", "America/Chicago", "America/Los_Angeles", "Europe/London"] ), "locale": random.choice(["en-US", "en-GB", "en-CA"]), "typing_speed": random.choice(["fast", "normal", "slow"]), "behavior_pattern": random.choice(["casual", "researcher", "quick"]), } return profile def _get_random_user_agent(self): """Get random user agent""" user_agents = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0", ] return random.choice(user_agents) def save_session(self, session_data, cookies=None, storage_state=None): """Save session data""" session_path = self.session_dir / session_data["id"] session_path.mkdir(exist_ok=True) with open(session_path / "session.json", "w") as f: json.dump(session_data, f, indent=2) if cookies: with open(session_path / "cookies.json", "w") as f: json.dump(cookies, f, indent=2) if storage_state: with open(session_path / "storage_state.json", "w") as f: json.dump(storage_state, f, indent=2) def load_session(self, session_id=None): """Load an existing session""" if session_id is None: sessions = list(self.session_dir.glob("session_*/session.json")) if not sessions: return None # Get most recent sessions_data = [] for session_file in sessions: with open(session_file, "r") as f: data = json.load(f) sessions_data.append((data, session_file.parent)) sessions_data.sort(key=lambda x: x[0]["last_used"], reverse=True) session_data, session_path = sessions_data[0] else: session_path = self.session_dir / session_id if not session_path.exists(): return None with open(session_path / "session.json", "r") as f: session_data = json.load(f) # Load cookies and storage cookies = None cookies_file = session_path / "cookies.json" if cookies_file.exists(): with open(cookies_file, "r") as f: cookies = json.load(f) storage_state = None storage_file = session_path / "storage_state.json" if storage_file.exists(): with open(storage_file, "r") as f: storage_state = json.load(f) return { "profile": session_data, "cookies": cookies, "storage_state": storage_state, "path": session_path, } def should_create_new_session(self, current_session): """Determine if new session needed""" if not current_session: return True profile = current_session["profile"] if profile["search_count"] >= random.randint(5, 15): return True last_used = datetime.fromisoformat(profile["last_used"]) if datetime.now() - last_used > timedelta(hours=random.uniform(1, 4)): return True return random.random() < 0.1
yaacov/gsr
1
A tool for researching and analyzing Google search page behavior and structure.
Python
yaacov
Yaacov Zamir
Red Hat
.devcontainer/post-install.sh
Shell
#!/bin/bash set -x curl -Lo ./kind https://kind.sigs.k8s.io/dl/latest/kind-linux-amd64 chmod +x ./kind mv ./kind /usr/local/bin/kind curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/linux/amd64 chmod +x kubebuilder mv kubebuilder /usr/local/bin/ KUBECTL_VERSION=$(curl -L -s https://dl.k8s.io/release/stable.txt) curl -LO "https://dl.k8s.io/release/$KUBECTL_VERSION/bin/linux/amd64/kubectl" chmod +x kubectl mv kubectl /usr/local/bin/kubectl docker network create -d=bridge --subnet=172.19.0.0/24 kind kind version kubebuilder version docker --version go version kubectl version --client
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
api/v1/groupversion_info.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package v1 contains API Schema definitions for the pipeline v1 API group // +kubebuilder:object:generate=true // +groupName=pipeline.yaacov.io package v1 import ( "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/scheme" ) var ( // GroupVersion is group version used to register these objects GroupVersion = schema.GroupVersion{Group: "pipeline.yaacov.io", Version: "v1"} // SchemeBuilder is used to add go types to the GroupVersionKind scheme SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. AddToScheme = SchemeBuilder.AddToScheme )
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
api/v1/pipeline_types.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1 import ( batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // PipelineSpec defines the desired state of Pipeline type PipelineSpec struct { // Steps defines the list of jobs to run // +kubebuilder:validation:MinItems=1 Steps []PipelineStep `json:"steps"` // ServiceAccountName is the service account to use for all jobs // Can be overridden per step in the job's pod spec // +optional ServiceAccountName string `json:"serviceAccountName,omitempty"` // SharedVolume defines a volume that will be mounted to all steps // +optional SharedVolume *SharedVolumeSpec `json:"sharedVolume,omitempty"` // PodTemplate defines common pod configuration applied to all steps // +optional PodTemplate *PodTemplateDefaults `json:"podTemplate,omitempty"` } // SharedVolumeSpec defines the shared volume configuration type SharedVolumeSpec struct { // Name is the name of the volume // +kubebuilder:default=workspace // +optional Name string `json:"name,omitempty"` // MountPath is where the volume will be mounted in each step // +kubebuilder:default=/workspace // +optional MountPath string `json:"mountPath,omitempty"` // VolumeSource defines the volume source (PVC, emptyDir, etc.) corev1.VolumeSource `json:",inline"` } // PodTemplateDefaults defines common pod settings applied to all steps type PodTemplateDefaults struct { // NodeSelector must match a node's labels for pods to be scheduled // +optional NodeSelector map[string]string `json:"nodeSelector,omitempty"` // Affinity defines scheduling constraints // +optional Affinity *corev1.Affinity `json:"affinity,omitempty"` // Tolerations allow scheduling onto nodes with matching taints // +optional Tolerations []corev1.Toleration `json:"tolerations,omitempty"` // SecurityContext holds pod-level security attributes // +optional SecurityContext *corev1.PodSecurityContext `json:"securityContext,omitempty"` // ImagePullSecrets for pulling container images // +optional ImagePullSecrets []corev1.LocalObjectReference `json:"imagePullSecrets,omitempty"` // PriorityClassName for pod priority // +optional PriorityClassName string `json:"priorityClassName,omitempty"` // RuntimeClassName for container runtime // +optional RuntimeClassName *string `json:"runtimeClassName,omitempty"` // SchedulerName for custom scheduler // +optional SchedulerName string `json:"schedulerName,omitempty"` // Labels to add to all pods // +optional Labels map[string]string `json:"labels,omitempty"` // Annotations to add to all pods // +optional Annotations map[string]string `json:"annotations,omitempty"` // DefaultResources applied to containers without resource specs // +optional DefaultResources *corev1.ResourceRequirements `json:"defaultResources,omitempty"` // Image is the default container image applied to containers without an image // +optional Image string `json:"image,omitempty"` // Env variables injected into all containers // +optional Env []corev1.EnvVar `json:"env,omitempty"` // EnvFrom sources injected into all containers // +optional EnvFrom []corev1.EnvFromSource `json:"envFrom,omitempty"` } // PipelineStep defines a single step in the pipeline type PipelineStep struct { // Name is the unique identifier for this step // +kubebuilder:validation:Required // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=63 // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?$` Name string `json:"name"` // RunIf defines conditional execution for this step // If not specified, the step runs sequentially (after all previous steps succeed) // +optional RunIf *RunIfCondition `json:"runIf,omitempty"` // JobSpec is the specification of the job to run // +kubebuilder:validation:Required JobSpec batchv1.JobSpec `json:"jobSpec"` } // RunIfCondition defines when a step should run based on other steps type RunIfCondition struct { // Condition determines whether to check for success or failure // +kubebuilder:validation:Enum=success;fail // +kubebuilder:default=success // +optional Condition RunIfConditionType `json:"condition,omitempty"` // Operator determines whether ALL or ANY steps must meet the condition // +kubebuilder:validation:Enum=and;or // +kubebuilder:default=and // +optional Operator RunIfOperator `json:"operator,omitempty"` // Steps is the list of step names to check // +kubebuilder:validation:Required // +kubebuilder:validation:MinItems=1 Steps []string `json:"steps"` } // RunIfConditionType defines whether to check for success or failure // +kubebuilder:validation:Enum=success;fail type RunIfConditionType string const ( // RunIfConditionSuccess checks if steps succeeded RunIfConditionSuccess RunIfConditionType = "success" // RunIfConditionFail checks if steps failed RunIfConditionFail RunIfConditionType = "fail" ) // RunIfOperator defines whether ALL or ANY steps must meet the condition // +kubebuilder:validation:Enum=and;or type RunIfOperator string const ( // RunIfOperatorAnd requires ALL steps to meet the condition RunIfOperatorAnd RunIfOperator = "and" // RunIfOperatorOr requires ANY step to meet the condition RunIfOperatorOr RunIfOperator = "or" ) // PipelinePhase represents the current phase of the pipeline // +kubebuilder:validation:Enum=Pending;Running;Suspended;Succeeded;Failed type PipelinePhase string const ( PipelinePhasePending PipelinePhase = "Pending" PipelinePhaseRunning PipelinePhase = "Running" PipelinePhaseSuspended PipelinePhase = "Suspended" PipelinePhaseSucceeded PipelinePhase = "Succeeded" PipelinePhaseFailed PipelinePhase = "Failed" ) // StepPhase represents the current phase of a step // +kubebuilder:validation:Enum=Pending;Running;Suspended;Succeeded;Failed;Skipped type StepPhase string const ( StepPhasePending StepPhase = "Pending" StepPhaseRunning StepPhase = "Running" StepPhaseSuspended StepPhase = "Suspended" StepPhaseSucceeded StepPhase = "Succeeded" StepPhaseFailed StepPhase = "Failed" StepPhaseSkipped StepPhase = "Skipped" ) // StepStatus defines the observed state of a single step type StepStatus struct { // Name is the name of the step Name string `json:"name"` // Phase is the current phase of this step Phase StepPhase `json:"phase,omitempty"` // JobName is the name of the Job created for this step // +optional JobName string `json:"jobName,omitempty"` // JobStatus from the underlying job // +optional JobStatus *batchv1.JobStatus `json:"jobStatus,omitempty"` } // PipelineStatus defines the observed state of Pipeline type PipelineStatus struct { // Phase is the current phase of the pipeline // +kubebuilder:default=Pending Phase PipelinePhase `json:"phase,omitempty"` // StartTime is when the pipeline started // +optional StartTime *metav1.Time `json:"startTime,omitempty"` // CompletionTime is when the pipeline completed // +optional CompletionTime *metav1.Time `json:"completionTime,omitempty"` // Steps contains the status of each step // +optional Steps []StepStatus `json:"steps,omitempty"` // Conditions represent the latest observations of the pipeline's state // +optional // +patchMergeKey=type // +patchStrategy=merge // +listType=map // +listMapKey=type Conditions []metav1.Condition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` } // +kubebuilder:object:root=true // +kubebuilder:subresource:status // +kubebuilder:resource:shortName=pl;pipe // +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase` // +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` // Pipeline is the Schema for the pipelines API type Pipeline struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec PipelineSpec `json:"spec,omitempty"` Status PipelineStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true // PipelineList contains a list of Pipeline type PipelineList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Pipeline `json:"items"` } func init() { SchemeBuilder.Register(&Pipeline{}, &PipelineList{}) } // Helper methods func (s *SharedVolumeSpec) GetName() string { if s.Name == "" { return "workspace" } return s.Name } func (s *SharedVolumeSpec) GetMountPath() string { if s.MountPath == "" { return "/workspace" } return s.MountPath } // HasConditionalExecution returns true if the step has a runIf condition func (s *PipelineStep) HasConditionalExecution() bool { return s.RunIf != nil } // GetCondition returns the condition type (defaults to success) func (r *RunIfCondition) GetCondition() RunIfConditionType { if r.Condition == "" { return RunIfConditionSuccess } return r.Condition } // GetOperator returns the operator (defaults to and) func (r *RunIfCondition) GetOperator() RunIfOperator { if r.Operator == "" { return RunIfOperatorAnd } return r.Operator } // IsCheckingSuccess returns true if checking for success func (r *RunIfCondition) IsCheckingSuccess() bool { return r.GetCondition() == RunIfConditionSuccess } // IsCheckingFailure returns true if checking for failure func (r *RunIfCondition) IsCheckingFailure() bool { return r.GetCondition() == RunIfConditionFail } // RequiresAll returns true if all steps must meet the condition func (r *RunIfCondition) RequiresAll() bool { return r.GetOperator() == RunIfOperatorAnd } // RequiresAny returns true if any step must meet the condition func (r *RunIfCondition) RequiresAny() bool { return r.GetOperator() == RunIfOperatorOr }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
api/v1/zz_generated.deepcopy.go
Go
//go:build !ignore_autogenerated /* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Code generated by controller-gen. DO NOT EDIT. package v1 import ( batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Pipeline) DeepCopyInto(out *Pipeline) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Pipeline. func (in *Pipeline) DeepCopy() *Pipeline { if in == nil { return nil } out := new(Pipeline) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Pipeline) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PipelineList) DeepCopyInto(out *PipelineList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Pipeline, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineList. func (in *PipelineList) DeepCopy() *PipelineList { if in == nil { return nil } out := new(PipelineList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *PipelineList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PipelineSpec) DeepCopyInto(out *PipelineSpec) { *out = *in if in.Steps != nil { in, out := &in.Steps, &out.Steps *out = make([]PipelineStep, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.SharedVolume != nil { in, out := &in.SharedVolume, &out.SharedVolume *out = new(SharedVolumeSpec) (*in).DeepCopyInto(*out) } if in.PodTemplate != nil { in, out := &in.PodTemplate, &out.PodTemplate *out = new(PodTemplateDefaults) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineSpec. func (in *PipelineSpec) DeepCopy() *PipelineSpec { if in == nil { return nil } out := new(PipelineSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PipelineStatus) DeepCopyInto(out *PipelineStatus) { *out = *in if in.StartTime != nil { in, out := &in.StartTime, &out.StartTime *out = (*in).DeepCopy() } if in.CompletionTime != nil { in, out := &in.CompletionTime, &out.CompletionTime *out = (*in).DeepCopy() } if in.Steps != nil { in, out := &in.Steps, &out.Steps *out = make([]StepStatus, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]metav1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineStatus. func (in *PipelineStatus) DeepCopy() *PipelineStatus { if in == nil { return nil } out := new(PipelineStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PipelineStep) DeepCopyInto(out *PipelineStep) { *out = *in if in.RunIf != nil { in, out := &in.RunIf, &out.RunIf *out = new(RunIfCondition) (*in).DeepCopyInto(*out) } in.JobSpec.DeepCopyInto(&out.JobSpec) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PipelineStep. func (in *PipelineStep) DeepCopy() *PipelineStep { if in == nil { return nil } out := new(PipelineStep) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PodTemplateDefaults) DeepCopyInto(out *PodTemplateDefaults) { *out = *in if in.NodeSelector != nil { in, out := &in.NodeSelector, &out.NodeSelector *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Affinity != nil { in, out := &in.Affinity, &out.Affinity *out = new(corev1.Affinity) (*in).DeepCopyInto(*out) } if in.Tolerations != nil { in, out := &in.Tolerations, &out.Tolerations *out = make([]corev1.Toleration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.SecurityContext != nil { in, out := &in.SecurityContext, &out.SecurityContext *out = new(corev1.PodSecurityContext) (*in).DeepCopyInto(*out) } if in.ImagePullSecrets != nil { in, out := &in.ImagePullSecrets, &out.ImagePullSecrets *out = make([]corev1.LocalObjectReference, len(*in)) copy(*out, *in) } if in.RuntimeClassName != nil { in, out := &in.RuntimeClassName, &out.RuntimeClassName *out = new(string) **out = **in } if in.Labels != nil { in, out := &in.Labels, &out.Labels *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Annotations != nil { in, out := &in.Annotations, &out.Annotations *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.DefaultResources != nil { in, out := &in.DefaultResources, &out.DefaultResources *out = new(corev1.ResourceRequirements) (*in).DeepCopyInto(*out) } if in.Env != nil { in, out := &in.Env, &out.Env *out = make([]corev1.EnvVar, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.EnvFrom != nil { in, out := &in.EnvFrom, &out.EnvFrom *out = make([]corev1.EnvFromSource, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodTemplateDefaults. func (in *PodTemplateDefaults) DeepCopy() *PodTemplateDefaults { if in == nil { return nil } out := new(PodTemplateDefaults) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RunIfCondition) DeepCopyInto(out *RunIfCondition) { *out = *in if in.Steps != nil { in, out := &in.Steps, &out.Steps *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RunIfCondition. func (in *RunIfCondition) DeepCopy() *RunIfCondition { if in == nil { return nil } out := new(RunIfCondition) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SharedVolumeSpec) DeepCopyInto(out *SharedVolumeSpec) { *out = *in in.VolumeSource.DeepCopyInto(&out.VolumeSource) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SharedVolumeSpec. func (in *SharedVolumeSpec) DeepCopy() *SharedVolumeSpec { if in == nil { return nil } out := new(SharedVolumeSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *StepStatus) DeepCopyInto(out *StepStatus) { *out = *in if in.JobStatus != nil { in, out := &in.JobStatus, &out.JobStatus *out = new(batchv1.JobStatus) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new StepStatus. func (in *StepStatus) DeepCopy() *StepStatus { if in == nil { return nil } out := new(StepStatus) in.DeepCopyInto(out) return out }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
cmd/main.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "crypto/tls" "flag" "os" "path/filepath" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/certwatcher" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" "sigs.k8s.io/controller-runtime/pkg/metrics/filters" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" pipelinev1 "github.com/yaacov/jobrunner/api/v1" "github.com/yaacov/jobrunner/internal/controller" // +kubebuilder:scaffold:imports ) var ( scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") ) func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(pipelinev1.AddToScheme(scheme)) // +kubebuilder:scaffold:scheme } // nolint:gocyclo func main() { var metricsAddr string var metricsCertPath, metricsCertName, metricsCertKey string var webhookCertPath, webhookCertName, webhookCertKey string var enableLeaderElection bool var probeAddr string var secureMetrics bool var enableHTTP2 bool var tlsOpts []func(*tls.Config) flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") flag.BoolVar(&enableLeaderElection, "leader-elect", false, "Enable leader election for controller manager. "+ "Enabling this will ensure there is only one active controller manager.") flag.BoolVar(&secureMetrics, "metrics-secure", true, "If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.") flag.StringVar(&webhookCertPath, "webhook-cert-path", "", "The directory that contains the webhook certificate.") flag.StringVar(&webhookCertName, "webhook-cert-name", "tls.crt", "The name of the webhook certificate file.") flag.StringVar(&webhookCertKey, "webhook-cert-key", "tls.key", "The name of the webhook key file.") flag.StringVar(&metricsCertPath, "metrics-cert-path", "", "The directory that contains the metrics server certificate.") flag.StringVar(&metricsCertName, "metrics-cert-name", "tls.crt", "The name of the metrics server certificate file.") flag.StringVar(&metricsCertKey, "metrics-cert-key", "tls.key", "The name of the metrics server key file.") flag.BoolVar(&enableHTTP2, "enable-http2", false, "If set, HTTP/2 will be enabled for the metrics and webhook servers") opts := zap.Options{ Development: true, } opts.BindFlags(flag.CommandLine) flag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will // prevent from being vulnerable to the HTTP/2 Stream Cancellation and // Rapid Reset CVEs. For more information see: // - https://github.com/advisories/GHSA-qppj-fm5r-hxr3 // - https://github.com/advisories/GHSA-4374-p667-p6c8 disableHTTP2 := func(c *tls.Config) { setupLog.Info("disabling http/2") c.NextProtos = []string{"http/1.1"} } if !enableHTTP2 { tlsOpts = append(tlsOpts, disableHTTP2) } // Create watchers for metrics and webhooks certificates var metricsCertWatcher, webhookCertWatcher *certwatcher.CertWatcher // Initial webhook TLS options webhookTLSOpts := tlsOpts if len(webhookCertPath) > 0 { setupLog.Info("Initializing webhook certificate watcher using provided certificates", "webhook-cert-path", webhookCertPath, "webhook-cert-name", webhookCertName, "webhook-cert-key", webhookCertKey) var err error webhookCertWatcher, err = certwatcher.New( filepath.Join(webhookCertPath, webhookCertName), filepath.Join(webhookCertPath, webhookCertKey), ) if err != nil { setupLog.Error(err, "Failed to initialize webhook certificate watcher") os.Exit(1) } webhookTLSOpts = append(webhookTLSOpts, func(config *tls.Config) { config.GetCertificate = webhookCertWatcher.GetCertificate }) } webhookServer := webhook.NewServer(webhook.Options{ TLSOpts: webhookTLSOpts, }) // Metrics endpoint is enabled in 'config/default/kustomization.yaml'. The Metrics options configure the server. // More info: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/metrics/server // - https://book.kubebuilder.io/reference/metrics.html metricsServerOptions := metricsserver.Options{ BindAddress: metricsAddr, SecureServing: secureMetrics, TLSOpts: tlsOpts, } if secureMetrics { // FilterProvider is used to protect the metrics endpoint with authn/authz. // These configurations ensure that only authorized users and service accounts // can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info: // https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.21.0/pkg/metrics/filters#WithAuthenticationAndAuthorization metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization } // If the certificate is not specified, controller-runtime will automatically // generate self-signed certificates for the metrics server. While convenient for development and testing, // this setup is not recommended for production. // // TODO(user): If you enable certManager, uncomment the following lines: // - [METRICS-WITH-CERTS] at config/default/kustomization.yaml to generate and use certificates // managed by cert-manager for the metrics server. // - [PROMETHEUS-WITH-CERTS] at config/prometheus/kustomization.yaml for TLS certification. if len(metricsCertPath) > 0 { setupLog.Info("Initializing metrics certificate watcher using provided certificates", "metrics-cert-path", metricsCertPath, "metrics-cert-name", metricsCertName, "metrics-cert-key", metricsCertKey) var err error metricsCertWatcher, err = certwatcher.New( filepath.Join(metricsCertPath, metricsCertName), filepath.Join(metricsCertPath, metricsCertKey), ) if err != nil { setupLog.Error(err, "to initialize metrics certificate watcher", "error", err) os.Exit(1) } metricsServerOptions.TLSOpts = append(metricsServerOptions.TLSOpts, func(config *tls.Config) { config.GetCertificate = metricsCertWatcher.GetCertificate }) } mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, Metrics: metricsServerOptions, WebhookServer: webhookServer, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "80974f40.yaacov.io", // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily // when the Manager ends. This requires the binary to immediately end when the // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly // speeds up voluntary leader transitions as the new leader don't have to wait // LeaseDuration time first. // // In the default scaffold provided, the program ends immediately after // the manager stops, so would be fine to enable this option. However, // if you are doing or is intended to do any operation such as perform cleanups // after the manager stops then its usage might be unsafe. // LeaderElectionReleaseOnCancel: true, }) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) } if err = (&controller.PipelineReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Pipeline") os.Exit(1) } // +kubebuilder:scaffold:builder if metricsCertWatcher != nil { setupLog.Info("Adding metrics certificate watcher to manager") if err := mgr.Add(metricsCertWatcher); err != nil { setupLog.Error(err, "unable to add metrics certificate watcher to manager") os.Exit(1) } } if webhookCertWatcher != nil { setupLog.Info("Adding webhook certificate watcher to manager") if err := mgr.Add(webhookCertWatcher); err != nil { setupLog.Error(err, "unable to add webhook certificate watcher to manager") os.Exit(1) } } if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up health check") os.Exit(1) } if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up ready check") os.Exit(1) } setupLog.Info("starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_controller.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "context" "time" batchv1 "k8s.io/api/batch/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) const ( pipelineFinalizer = "pipeline.yaacov.io/finalizer" ) // PipelineReconciler reconciles a Pipeline object type PipelineReconciler struct { client.Client Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=pipeline.yaacov.io,resources=pipelines,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=pipeline.yaacov.io,resources=pipelines/status,verbs=get;update;patch // +kubebuilder:rbac:groups=pipeline.yaacov.io,resources=pipelines/finalizers,verbs=update // +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=batch,resources=jobs/status,verbs=get // +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. func (r *PipelineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { logger := log.FromContext(ctx) // Fetch the Pipeline instance pipeline := &pipelinev1.Pipeline{} if err := r.Get(ctx, req.NamespacedName, pipeline); err != nil { if apierrors.IsNotFound(err) { // Pipeline was deleted return ctrl.Result{}, nil } logger.Error(err, "unable to fetch Pipeline") return ctrl.Result{}, err } // Handle deletion if !pipeline.DeletionTimestamp.IsZero() { return r.reconcileDelete(ctx, pipeline) } // Add finalizer if not present if !controllerutil.ContainsFinalizer(pipeline, pipelineFinalizer) { controllerutil.AddFinalizer(pipeline, pipelineFinalizer) if err := r.Update(ctx, pipeline); err != nil { return ctrl.Result{}, err } } // Initialize status if needed if pipeline.Status.Phase == "" { pipeline.Status.Phase = pipelinev1.PipelinePhasePending pipeline.Status.StartTime = &metav1.Time{Time: time.Now()} if err := r.Status().Update(ctx, pipeline); err != nil { return ctrl.Result{}, err } return ctrl.Result{Requeue: true}, nil } // Skip reconciliation for completed pipelines if pipeline.Status.Phase == pipelinev1.PipelinePhaseSucceeded || pipeline.Status.Phase == pipelinev1.PipelinePhaseFailed { logger.V(1).Info("Pipeline already completed, skipping reconciliation", "phase", pipeline.Status.Phase) return ctrl.Result{}, nil } // Reconcile the pipeline return r.reconcilePipeline(ctx, pipeline) } // SetupWithManager sets up the controller with the Manager. func (r *PipelineReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&pipelinev1.Pipeline{}). Owns(&batchv1.Job{}). Complete(r) }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_dependencies.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "sigs.k8s.io/controller-runtime/pkg/log" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) // areDependenciesSatisfied checks if a step's dependencies are met and whether it should run // Returns (ready, shouldSkip) where: // - ready=true means the step can start now // - shouldSkip=true means the step should be skipped (conditions not met) func (r *PipelineReconciler) areDependenciesSatisfied(pipeline *pipelinev1.Pipeline, step *pipelinev1.PipelineStep) (ready bool, shouldSkip bool) { // If step has a runIf condition, check it if step.HasConditionalExecution() { return r.checkConditionalExecution(pipeline, step) } // Default behavior: sequential execution - wait for all previous steps to succeed return r.checkSequentialExecution(pipeline, step) } // checkSequentialExecution checks if all previous steps have succeeded (default behavior) // Steps run in order of the list - each step waits for all previous steps to succeed func (r *PipelineReconciler) checkSequentialExecution(pipeline *pipelinev1.Pipeline, step *pipelinev1.PipelineStep) (ready bool, shouldSkip bool) { // Find the index of this step stepIndex := -1 for i, s := range pipeline.Spec.Steps { if s.Name == step.Name { stepIndex = i break } } if stepIndex == 0 { // First step is always ready log.Log.V(1).Info("First step in pipeline is ready", "step", step.Name) return true, false } // Check all previous steps pendingSteps := []string{} failedSteps := []string{} for i := 0; i < stepIndex; i++ { prevStep := &pipeline.Spec.Steps[i] prevStatus := r.getStepStatus(pipeline, prevStep.Name) switch prevStatus.Phase { case pipelinev1.StepPhaseSucceeded: // Previous step succeeded, continue checking continue case pipelinev1.StepPhaseFailed: // A previous step failed, skip this step failedSteps = append(failedSteps, prevStep.Name) case pipelinev1.StepPhaseSkipped: // A previous step was skipped, skip this step too failedSteps = append(failedSteps, prevStep.Name) case pipelinev1.StepPhasePending, pipelinev1.StepPhaseRunning: // Previous step not complete, wait pendingSteps = append(pendingSteps, prevStep.Name) } } // If any previous steps are pending or running, wait if len(pendingSteps) > 0 { log.Log.V(1).Info("Step waiting for previous steps to complete (sequential execution)", "step", step.Name, "pendingSteps", pendingSteps) return false, false } // If any previous steps failed or were skipped, skip this step if len(failedSteps) > 0 { log.Log.Info("Step skipped - previous steps failed or were skipped (sequential execution)", "step", step.Name, "failedSteps", failedSteps) return false, true } // All previous steps succeeded log.Log.Info("Step ready to run - all previous steps succeeded (sequential execution)", "step", step.Name) return true, false } // checkConditionalExecution checks the runIf condition // These allow steps to run out of order based on specific conditions func (r *PipelineReconciler) checkConditionalExecution(pipeline *pipelinev1.Pipeline, step *pipelinev1.PipelineStep) (ready bool, shouldSkip bool) { runIf := step.RunIf if runIf == nil { // Should not happen, but handle gracefully return false, false } checkFailure := runIf.IsCheckingFailure() checkAll := runIf.RequiresAll() conditionMet, allComplete := r.checkStepStatuses(pipeline, runIf.Steps, checkAll, checkFailure) if !allComplete { log.Log.V(1).Info("Step waiting for runIf steps to complete", "step", step.Name, "condition", runIf.GetCondition(), "operator", runIf.GetOperator(), "waitingFor", runIf.Steps) return false, false } if !conditionMet { log.Log.Info("Step skipped - runIf condition not met", "step", step.Name, "condition", runIf.GetCondition(), "operator", runIf.GetOperator(), "steps", runIf.Steps) return false, true } log.Log.Info("Step ready to run - runIf condition met", "step", step.Name, "condition", runIf.GetCondition(), "operator", runIf.GetOperator(), "steps", runIf.Steps) return true, false } // checkStepStatuses checks the status of a list of steps // Returns (conditionMet, allComplete) where: // - conditionMet: true if the condition is satisfied (all/any success/fail based on params) // - allComplete: true if all steps are in a terminal state // // If checkAll is true, checks if ALL steps meet the condition; otherwise checks if ANY step meets it // If checkFailure is true, checks for failure; otherwise checks for success func (r *PipelineReconciler) checkStepStatuses(pipeline *pipelinev1.Pipeline, stepNames []string, checkAll bool, checkFailure bool) (conditionMet bool, allComplete bool) { allComplete = true matchCount := 0 for _, name := range stepNames { status := r.getStepStatus(pipeline, name) if status == nil { log.Log.Info("Referenced step not found", "referencedStep", name, "pipeline", pipeline.Name) allComplete = false continue } switch status.Phase { case pipelinev1.StepPhaseSucceeded: if !checkFailure { matchCount++ } case pipelinev1.StepPhaseFailed: if checkFailure { matchCount++ } case pipelinev1.StepPhaseSkipped: // Skipped steps don't match any condition continue case pipelinev1.StepPhasePending, pipelinev1.StepPhaseRunning: allComplete = false } } if !allComplete { return false, false } // Check if condition is met if checkAll { // All steps must match conditionMet = (matchCount == len(stepNames)) } else { // At least one step must match conditionMet = (matchCount > 0) } return conditionMet, true } // shouldSkipStep checks if a step should be skipped for other reasons // This is a placeholder for future validation logic func (r *PipelineReconciler) shouldSkipStep(pipeline *pipelinev1.Pipeline, step *pipelinev1.PipelineStep) bool { // Additional validation logic can go here // For now, this is a placeholder for future enhancements return false } // hasPendingFailureHandlers checks if there are pending steps that handle failures func (r *PipelineReconciler) hasPendingFailureHandlers(pipeline *pipelinev1.Pipeline) bool { pendingHandlers := []string{} // Check if there are any pending steps that could run on failure for i := range pipeline.Spec.Steps { step := &pipeline.Spec.Steps[i] stepStatus := r.getStepStatus(pipeline, step.Name) if stepStatus.Phase != pipelinev1.StepPhasePending { continue } // Check if this step has failure-related conditions if step.RunIf != nil && step.RunIf.IsCheckingFailure() { pendingHandlers = append(pendingHandlers, step.Name) } } if len(pendingHandlers) > 0 { log.Log.Info("Pending failure handlers detected", "pipeline", pipeline.Name, "handlers", pendingHandlers) return true } return false }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_dependencies_test.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "testing" batchv1 "k8s.io/api/batch/v1" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) func TestCheckSequentialExecution(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline step *pipelinev1.PipelineStep wantReady bool wantSkip bool }{ { name: "first step is always ready", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhasePending}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step1"}, wantReady: true, wantSkip: false, }, { name: "second step ready when first succeeds", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step2"}, wantReady: true, wantSkip: false, }, { name: "second step waits when first is running", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseRunning}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step2"}, wantReady: false, wantSkip: false, }, { name: "second step waits when first is pending", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhasePending}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step2"}, wantReady: false, wantSkip: false, }, { name: "second step skipped when first fails", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step2"}, wantReady: false, wantSkip: true, }, { name: "second step skipped when first is skipped", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSkipped}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step2"}, wantReady: false, wantSkip: true, }, { name: "third step ready when all previous succeed", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "step3", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step3"}, wantReady: true, wantSkip: false, }, { name: "third step waits when second is running", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "step3", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseRunning}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step3"}, wantReady: false, wantSkip: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ready, skip := r.checkSequentialExecution(tt.pipeline, tt.step) if ready != tt.wantReady { t.Errorf("ready = %v, want %v", ready, tt.wantReady) } if skip != tt.wantSkip { t.Errorf("skip = %v, want %v", skip, tt.wantSkip) } }) } } func TestCheckConditionalExecution(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline step *pipelinev1.PipelineStep wantReady bool wantSkip bool }{ { name: "runIf success AND - all succeed", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "step3", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "step3", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Operator: pipelinev1.RunIfOperatorAnd, Steps: []string{"step1", "step2"}, }, }, wantReady: true, wantSkip: false, }, { name: "runIf success AND - one fails", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "step3", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "step3", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Operator: pipelinev1.RunIfOperatorAnd, Steps: []string{"step1", "step2"}, }, }, wantReady: false, wantSkip: true, }, { name: "runIf success OR - one succeeds", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "step3", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "step3", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Operator: pipelinev1.RunIfOperatorOr, Steps: []string{"step1", "step2"}, }, }, wantReady: true, wantSkip: false, }, { name: "runIf success OR - all fail", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "step3", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "step3", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Operator: pipelinev1.RunIfOperatorOr, Steps: []string{"step1", "step2"}, }, }, wantReady: false, wantSkip: true, }, { name: "runIf fail AND - all fail", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "cleanup", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, {Name: "cleanup", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "cleanup", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionFail, Operator: pipelinev1.RunIfOperatorAnd, Steps: []string{"step1", "step2"}, }, }, wantReady: true, wantSkip: false, }, { name: "runIf fail OR - one fails", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "cleanup", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, {Name: "cleanup", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "cleanup", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionFail, Operator: pipelinev1.RunIfOperatorOr, Steps: []string{"step1", "step2"}, }, }, wantReady: true, wantSkip: false, }, { name: "runIf waits when dependency is running", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseRunning}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "step2", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Operator: pipelinev1.RunIfOperatorAnd, Steps: []string{"step1"}, }, }, wantReady: false, wantSkip: false, }, { name: "runIf waits when dependency is pending", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhasePending}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "step2", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Operator: pipelinev1.RunIfOperatorAnd, Steps: []string{"step1"}, }, }, wantReady: false, wantSkip: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ready, skip := r.checkConditionalExecution(tt.pipeline, tt.step) if ready != tt.wantReady { t.Errorf("ready = %v, want %v", ready, tt.wantReady) } if skip != tt.wantSkip { t.Errorf("skip = %v, want %v", skip, tt.wantSkip) } }) } } func TestAreDependenciesSatisfied(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline step *pipelinev1.PipelineStep wantReady bool wantSkip bool }{ { name: "step with runIf uses conditional execution", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{ Name: "step2", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Steps: []string{"step1"}, }, }, wantReady: true, wantSkip: false, }, { name: "step without runIf uses sequential execution", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, step: &pipelinev1.PipelineStep{Name: "step2"}, wantReady: true, wantSkip: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ready, skip := r.areDependenciesSatisfied(tt.pipeline, tt.step) if ready != tt.wantReady { t.Errorf("ready = %v, want %v", ready, tt.wantReady) } if skip != tt.wantSkip { t.Errorf("skip = %v, want %v", skip, tt.wantSkip) } }) } } func TestCheckStepStatuses(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline stepNames []string checkAll bool checkFailure bool wantConditionMet bool wantAllComplete bool }{ { name: "all success - checkAll=true, checkFailure=false", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseSucceeded}, }, }, }, stepNames: []string{"step1", "step2"}, checkAll: true, checkFailure: false, wantConditionMet: true, wantAllComplete: true, }, { name: "one success - checkAll=true, checkFailure=false", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, }, }, }, stepNames: []string{"step1", "step2"}, checkAll: true, checkFailure: false, wantConditionMet: false, wantAllComplete: true, }, { name: "one success - checkAll=false, checkFailure=false", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, }, }, }, stepNames: []string{"step1", "step2"}, checkAll: false, checkFailure: false, wantConditionMet: true, wantAllComplete: true, }, { name: "all failed - checkAll=true, checkFailure=true", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, }, }, }, stepNames: []string{"step1", "step2"}, checkAll: true, checkFailure: true, wantConditionMet: true, wantAllComplete: true, }, { name: "one failed - checkAll=false, checkFailure=true", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, }, }, }, stepNames: []string{"step1", "step2"}, checkAll: false, checkFailure: true, wantConditionMet: true, wantAllComplete: true, }, { name: "one running - not complete", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseRunning}, }, }, }, stepNames: []string{"step1", "step2"}, checkAll: true, checkFailure: false, wantConditionMet: false, wantAllComplete: false, }, { name: "skipped steps don't match", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSkipped}, {Name: "step2", Phase: pipelinev1.StepPhaseSucceeded}, }, }, }, stepNames: []string{"step1", "step2"}, checkAll: true, checkFailure: false, wantConditionMet: false, // step1 is skipped, not succeeded wantAllComplete: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { conditionMet, allComplete := r.checkStepStatuses(tt.pipeline, tt.stepNames, tt.checkAll, tt.checkFailure) if conditionMet != tt.wantConditionMet { t.Errorf("conditionMet = %v, want %v", conditionMet, tt.wantConditionMet) } if allComplete != tt.wantAllComplete { t.Errorf("allComplete = %v, want %v", allComplete, tt.wantAllComplete) } }) } } func TestHasPendingFailureHandlers(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline want bool }{ { name: "has pending failure handler", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, { Name: "cleanup", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionFail, Steps: []string{"step1"}, }, JobSpec: batchv1.JobSpec{}, }, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "cleanup", Phase: pipelinev1.StepPhasePending}, }, }, }, want: true, }, { name: "no pending failure handlers", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, want: false, }, { name: "failure handler already running", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, { Name: "cleanup", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionFail, Steps: []string{"step1"}, }, JobSpec: batchv1.JobSpec{}, }, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "cleanup", Phase: pipelinev1.StepPhaseRunning}, }, }, }, want: false, }, { name: "pending step with success condition is not a failure handler", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, { Name: "step2", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionSuccess, Steps: []string{"step1"}, }, JobSpec: batchv1.JobSpec{}, }, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := r.hasPendingFailureHandlers(tt.pipeline) if got != tt.want { t.Errorf("hasPendingFailureHandlers() = %v, want %v", got, tt.want) } }) } }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_jobs.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "context" "fmt" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) // startReadySteps attempts to start all steps that are ready to run func (r *PipelineReconciler) startReadySteps(ctx context.Context, pipeline *pipelinev1.Pipeline) error { logger := log.FromContext(ctx) for i := range pipeline.Spec.Steps { step := &pipeline.Spec.Steps[i] stepStatus := r.getStepStatus(pipeline, step.Name) // Skip if already started if stepStatus.Phase != pipelinev1.StepPhasePending { continue } // Check if this step should be skipped based on conditions if r.shouldSkipStep(pipeline, step) { logger.Info("Skipping step due to unmet conditions", "step", step.Name) stepStatus.Phase = pipelinev1.StepPhaseSkipped if err := r.Status().Update(ctx, pipeline); err != nil { return err } continue } // Check if dependencies are satisfied ready, shouldSkip := r.areDependenciesSatisfied(pipeline, step) if shouldSkip { logger.Info("Skipping step due to dependency conditions", "step", step.Name) stepStatus.Phase = pipelinev1.StepPhaseSkipped if err := r.Status().Update(ctx, pipeline); err != nil { return err } continue } if !ready { continue } // Create the job for this step if err := r.createJobForStep(ctx, pipeline, step, stepStatus); err != nil { logger.Error(err, "unable to create job for step", "step", step.Name) return err } logger.Info("Started step", "step", step.Name, "job", stepStatus.JobName) // Update status to Running stepStatus.Phase = pipelinev1.StepPhaseRunning if err := r.Status().Update(ctx, pipeline); err != nil { return err } } return nil } // createJobForStep creates a Kubernetes Job for a pipeline step func (r *PipelineReconciler) createJobForStep(ctx context.Context, pipeline *pipelinev1.Pipeline, step *pipelinev1.PipelineStep, stepStatus *pipelinev1.StepStatus) error { logger := log.FromContext(ctx) jobName := fmt.Sprintf("%s-%s", pipeline.Name, step.Name) stepStatus.JobName = jobName logger.Info("Creating job for step", "step", step.Name, "job", jobName, "pipeline", pipeline.Name) job := &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{ Name: jobName, Namespace: pipeline.Namespace, Labels: map[string]string{ "pipeline.yaacov.io/pipeline": pipeline.Name, "pipeline.yaacov.io/step": step.Name, }, }, Spec: step.JobSpec, } // Set backoffLimit to 0 if not specified (fail fast for pipeline steps) if job.Spec.BackoffLimit == nil { backoffLimit := int32(0) job.Spec.BackoffLimit = &backoffLimit logger.V(1).Info("Setting default backoffLimit to 0 for pipeline step", "step", step.Name) } // Apply pod template defaults if pipeline.Spec.PodTemplate != nil { logger.V(1).Info("Applying pod template defaults", "step", step.Name) } r.applyPodTemplateDefaults(pipeline, job) // Apply shared volume if configured if pipeline.Spec.SharedVolume != nil { logger.V(1).Info("Applying shared volume configuration", "step", step.Name, "volume", pipeline.Spec.SharedVolume.GetName(), "mountPath", pipeline.Spec.SharedVolume.GetMountPath()) } r.applySharedVolume(pipeline, step, job) // Set controller reference if err := controllerutil.SetControllerReference(pipeline, job, r.Scheme); err != nil { logger.Error(err, "Failed to set controller reference", "job", jobName) return err } // Create the job if err := r.Create(ctx, job); err != nil { logger.Error(err, "Failed to create job", "job", jobName, "step", step.Name) return err } logger.Info("Job created successfully", "job", jobName, "step", step.Name, "namespace", pipeline.Namespace) return nil } // applyPodTemplateDefaults applies pipeline-level pod template defaults to a job func (r *PipelineReconciler) applyPodTemplateDefaults(pipeline *pipelinev1.Pipeline, job *batchv1.Job) { if pipeline.Spec.PodTemplate == nil { // Still apply service account even without pod template r.applyServiceAccountName(pipeline, &job.Spec.Template.Spec) return } podTemplate := pipeline.Spec.PodTemplate podSpec := &job.Spec.Template.Spec r.applyPodSpecDefaults(podTemplate, podSpec) r.applyPodMetadataDefaults(podTemplate, job) r.applyContainerDefaults(podTemplate, podSpec) r.applyServiceAccountName(pipeline, podSpec) } // applyPodSpecDefaults applies pod-level scheduling and configuration defaults func (r *PipelineReconciler) applyPodSpecDefaults(podTemplate *pipelinev1.PodTemplateDefaults, podSpec *corev1.PodSpec) { // Apply node selector if len(podTemplate.NodeSelector) > 0 { if podSpec.NodeSelector == nil { podSpec.NodeSelector = make(map[string]string) } for k, v := range podTemplate.NodeSelector { if _, exists := podSpec.NodeSelector[k]; !exists { podSpec.NodeSelector[k] = v } } } // Apply affinity if podTemplate.Affinity != nil && podSpec.Affinity == nil { podSpec.Affinity = podTemplate.Affinity } // Apply tolerations if len(podTemplate.Tolerations) > 0 { podSpec.Tolerations = append(podSpec.Tolerations, podTemplate.Tolerations...) } // Apply security context if podTemplate.SecurityContext != nil && podSpec.SecurityContext == nil { podSpec.SecurityContext = podTemplate.SecurityContext } // Apply image pull secrets if len(podTemplate.ImagePullSecrets) > 0 { podSpec.ImagePullSecrets = append(podSpec.ImagePullSecrets, podTemplate.ImagePullSecrets...) } // Apply priority class name if podTemplate.PriorityClassName != "" && podSpec.PriorityClassName == "" { podSpec.PriorityClassName = podTemplate.PriorityClassName } // Apply runtime class name if podTemplate.RuntimeClassName != nil && podSpec.RuntimeClassName == nil { podSpec.RuntimeClassName = podTemplate.RuntimeClassName } // Apply scheduler name if podTemplate.SchedulerName != "" && podSpec.SchedulerName == "" { podSpec.SchedulerName = podTemplate.SchedulerName } } // applyPodMetadataDefaults applies labels and annotations to the pod template func (r *PipelineReconciler) applyPodMetadataDefaults(podTemplate *pipelinev1.PodTemplateDefaults, job *batchv1.Job) { // Apply labels to pod template if len(podTemplate.Labels) > 0 { if job.Spec.Template.Labels == nil { job.Spec.Template.Labels = make(map[string]string) } for k, v := range podTemplate.Labels { if _, exists := job.Spec.Template.Labels[k]; !exists { job.Spec.Template.Labels[k] = v } } } // Apply annotations to pod template if len(podTemplate.Annotations) > 0 { if job.Spec.Template.Annotations == nil { job.Spec.Template.Annotations = make(map[string]string) } for k, v := range podTemplate.Annotations { if _, exists := job.Spec.Template.Annotations[k]; !exists { job.Spec.Template.Annotations[k] = v } } } } // applyContainerDefaults applies defaults to all containers in the pod spec func (r *PipelineReconciler) applyContainerDefaults(podTemplate *pipelinev1.PodTemplateDefaults, podSpec *corev1.PodSpec) { // Apply environment variables to all containers if len(podTemplate.Env) > 0 || len(podTemplate.EnvFrom) > 0 { for i := range podSpec.Containers { podSpec.Containers[i].Env = append(podSpec.Containers[i].Env, podTemplate.Env...) podSpec.Containers[i].EnvFrom = append(podSpec.Containers[i].EnvFrom, podTemplate.EnvFrom...) } } // Apply default resources to containers without resources if podTemplate.DefaultResources != nil { for i := range podSpec.Containers { if podSpec.Containers[i].Resources.Limits == nil && podSpec.Containers[i].Resources.Requests == nil { podSpec.Containers[i].Resources = *podTemplate.DefaultResources } } } // Apply default image to containers without an image if podTemplate.Image != "" { for i := range podSpec.Containers { if podSpec.Containers[i].Image == "" { podSpec.Containers[i].Image = podTemplate.Image } } } } // applyServiceAccountName applies the service account name from the pipeline spec func (r *PipelineReconciler) applyServiceAccountName(pipeline *pipelinev1.Pipeline, podSpec *corev1.PodSpec) { if pipeline.Spec.ServiceAccountName != "" && podSpec.ServiceAccountName == "" { podSpec.ServiceAccountName = pipeline.Spec.ServiceAccountName } } // applySharedVolume configures shared volume mounting for a job func (r *PipelineReconciler) applySharedVolume(pipeline *pipelinev1.Pipeline, step *pipelinev1.PipelineStep, job *batchv1.Job) { if pipeline.Spec.SharedVolume == nil { return } sharedVol := pipeline.Spec.SharedVolume podSpec := &job.Spec.Template.Spec // Add volume volume := corev1.Volume{ Name: sharedVol.GetName(), VolumeSource: sharedVol.VolumeSource, } podSpec.Volumes = append(podSpec.Volumes, volume) // Mount volume in all containers volumeMount := corev1.VolumeMount{ Name: sharedVol.GetName(), MountPath: sharedVol.GetMountPath(), } containerCount := len(podSpec.Containers) for i := range podSpec.Containers { podSpec.Containers[i].VolumeMounts = append(podSpec.Containers[i].VolumeMounts, volumeMount) } log.Log.V(1).Info("Mounted shared volume in containers", "step", step.Name, "containerCount", containerCount, "volumeName", sharedVol.GetName()) }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_jobs_test.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "testing" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) func TestApplyPodSpecDefaults(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string podTemplate *pipelinev1.PodTemplateDefaults podSpec *corev1.PodSpec wantCheck func(t *testing.T, podSpec *corev1.PodSpec) }{ { name: "applies node selector when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ NodeSelector: map[string]string{"disktype": "ssd"}, }, podSpec: &corev1.PodSpec{}, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.NodeSelector["disktype"] != "ssd" { t.Errorf("expected disktype=ssd, got %v", podSpec.NodeSelector) } }, }, { name: "does not override existing node selector keys", podTemplate: &pipelinev1.PodTemplateDefaults{ NodeSelector: map[string]string{"disktype": "ssd", "region": "us-west"}, }, podSpec: &corev1.PodSpec{ NodeSelector: map[string]string{"disktype": "hdd"}, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.NodeSelector["disktype"] != "hdd" { t.Errorf("expected disktype=hdd (not overridden), got %v", podSpec.NodeSelector["disktype"]) } if podSpec.NodeSelector["region"] != "us-west" { t.Errorf("expected region=us-west to be added, got %v", podSpec.NodeSelector["region"]) } }, }, { name: "applies affinity when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ Affinity: &corev1.Affinity{ NodeAffinity: &corev1.NodeAffinity{ RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{ NodeSelectorTerms: []corev1.NodeSelectorTerm{ { MatchExpressions: []corev1.NodeSelectorRequirement{ {Key: "test", Operator: corev1.NodeSelectorOpIn, Values: []string{"value"}}, }, }, }, }, }, }, }, podSpec: &corev1.PodSpec{}, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.Affinity == nil { t.Error("expected affinity to be set") } }, }, { name: "does not override existing affinity", podTemplate: &pipelinev1.PodTemplateDefaults{ Affinity: &corev1.Affinity{ NodeAffinity: &corev1.NodeAffinity{}, }, }, podSpec: &corev1.PodSpec{ Affinity: &corev1.Affinity{ PodAffinity: &corev1.PodAffinity{}, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.Affinity.PodAffinity == nil { t.Error("expected existing affinity to be preserved") } }, }, { name: "appends tolerations", podTemplate: &pipelinev1.PodTemplateDefaults{ Tolerations: []corev1.Toleration{ {Key: "key1", Operator: corev1.TolerationOpExists}, }, }, podSpec: &corev1.PodSpec{ Tolerations: []corev1.Toleration{ {Key: "existing", Operator: corev1.TolerationOpExists}, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if len(podSpec.Tolerations) != 2 { t.Errorf("expected 2 tolerations, got %d", len(podSpec.Tolerations)) } }, }, { name: "applies security context when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ SecurityContext: &corev1.PodSecurityContext{ RunAsNonRoot: boolPtr(true), }, }, podSpec: &corev1.PodSpec{}, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.SecurityContext == nil || podSpec.SecurityContext.RunAsNonRoot == nil || !*podSpec.SecurityContext.RunAsNonRoot { t.Error("expected security context with RunAsNonRoot=true") } }, }, { name: "appends image pull secrets", podTemplate: &pipelinev1.PodTemplateDefaults{ ImagePullSecrets: []corev1.LocalObjectReference{ {Name: "secret1"}, }, }, podSpec: &corev1.PodSpec{ ImagePullSecrets: []corev1.LocalObjectReference{ {Name: "existing-secret"}, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if len(podSpec.ImagePullSecrets) != 2 { t.Errorf("expected 2 image pull secrets, got %d", len(podSpec.ImagePullSecrets)) } }, }, { name: "applies priority class name when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ PriorityClassName: "high-priority", }, podSpec: &corev1.PodSpec{}, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.PriorityClassName != "high-priority" { t.Errorf("expected priority class name 'high-priority', got %s", podSpec.PriorityClassName) } }, }, { name: "does not override existing priority class name", podTemplate: &pipelinev1.PodTemplateDefaults{ PriorityClassName: "high-priority", }, podSpec: &corev1.PodSpec{ PriorityClassName: "low-priority", }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.PriorityClassName != "low-priority" { t.Errorf("expected priority class name 'low-priority' (not overridden), got %s", podSpec.PriorityClassName) } }, }, { name: "applies runtime class name when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ RuntimeClassName: stringPtr("gvisor"), }, podSpec: &corev1.PodSpec{}, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.RuntimeClassName == nil || *podSpec.RuntimeClassName != "gvisor" { t.Error("expected runtime class name 'gvisor'") } }, }, { name: "applies scheduler name when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ SchedulerName: "custom-scheduler", }, podSpec: &corev1.PodSpec{}, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.SchedulerName != "custom-scheduler" { t.Errorf("expected scheduler name 'custom-scheduler', got %s", podSpec.SchedulerName) } }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r.applyPodSpecDefaults(tt.podTemplate, tt.podSpec) tt.wantCheck(t, tt.podSpec) }) } } func TestApplyPodMetadataDefaults(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string podTemplate *pipelinev1.PodTemplateDefaults job *batchv1.Job wantCheck func(t *testing.T, job *batchv1.Job) }{ { name: "applies labels when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ Labels: map[string]string{"app": "test", "env": "prod"}, }, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{}, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Labels["app"] != "test" { t.Errorf("expected app=test, got %v", job.Spec.Template.Labels) } if job.Spec.Template.Labels["env"] != "prod" { t.Errorf("expected env=prod, got %v", job.Spec.Template.Labels) } }, }, { name: "does not override existing labels", podTemplate: &pipelinev1.PodTemplateDefaults{ Labels: map[string]string{"app": "default", "env": "prod"}, }, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{"app": "custom"}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Labels["app"] != "custom" { t.Errorf("expected app=custom (not overridden), got %v", job.Spec.Template.Labels["app"]) } if job.Spec.Template.Labels["env"] != "prod" { t.Errorf("expected env=prod to be added, got %v", job.Spec.Template.Labels["env"]) } }, }, { name: "applies annotations when not set", podTemplate: &pipelinev1.PodTemplateDefaults{ Annotations: map[string]string{"prometheus.io/scrape": "true"}, }, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{}, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Annotations["prometheus.io/scrape"] != "true" { t.Errorf("expected annotation to be set, got %v", job.Spec.Template.Annotations) } }, }, { name: "does not override existing annotations", podTemplate: &pipelinev1.PodTemplateDefaults{ Annotations: map[string]string{"key": "default"}, }, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{"key": "custom"}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Annotations["key"] != "custom" { t.Errorf("expected key=custom (not overridden), got %v", job.Spec.Template.Annotations["key"]) } }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r.applyPodMetadataDefaults(tt.podTemplate, tt.job) tt.wantCheck(t, tt.job) }) } } func TestApplyContainerDefaults(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string podTemplate *pipelinev1.PodTemplateDefaults podSpec *corev1.PodSpec wantCheck func(t *testing.T, podSpec *corev1.PodSpec) }{ { name: "applies env variables to all containers", podTemplate: &pipelinev1.PodTemplateDefaults{ Env: []corev1.EnvVar{ {Name: "LOG_LEVEL", Value: "debug"}, }, }, podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ {Name: "container1"}, {Name: "container2"}, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { for i, c := range podSpec.Containers { if len(c.Env) != 1 || c.Env[0].Name != "LOG_LEVEL" { t.Errorf("container %d: expected LOG_LEVEL env var, got %v", i, c.Env) } } }, }, { name: "appends env variables to existing ones", podTemplate: &pipelinev1.PodTemplateDefaults{ Env: []corev1.EnvVar{ {Name: "NEW_VAR", Value: "value"}, }, }, podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ { Name: "container1", Env: []corev1.EnvVar{{Name: "EXISTING", Value: "val"}}, }, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if len(podSpec.Containers[0].Env) != 2 { t.Errorf("expected 2 env vars, got %d", len(podSpec.Containers[0].Env)) } }, }, { name: "applies envFrom to all containers", podTemplate: &pipelinev1.PodTemplateDefaults{ EnvFrom: []corev1.EnvFromSource{ {ConfigMapRef: &corev1.ConfigMapEnvSource{LocalObjectReference: corev1.LocalObjectReference{Name: "config"}}}, }, }, podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ {Name: "container1"}, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if len(podSpec.Containers[0].EnvFrom) != 1 { t.Errorf("expected 1 envFrom, got %d", len(podSpec.Containers[0].EnvFrom)) } }, }, { name: "applies default resources to containers without resources", podTemplate: &pipelinev1.PodTemplateDefaults{ DefaultResources: &corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("100m"), corev1.ResourceMemory: resource.MustParse("128Mi"), }, }, }, podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ {Name: "no-resources"}, { Name: "has-resources", Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("200m"), }, }, }, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { // Container without resources should get defaults if podSpec.Containers[0].Resources.Requests.Cpu().String() != "100m" { t.Errorf("expected 100m CPU for container without resources, got %v", podSpec.Containers[0].Resources.Requests.Cpu()) } // Container with resources should keep its own if podSpec.Containers[1].Resources.Requests.Cpu().String() != "200m" { t.Errorf("expected 200m CPU for container with resources (not overridden), got %v", podSpec.Containers[1].Resources.Requests.Cpu()) } }, }, { name: "applies default image to containers without image", podTemplate: &pipelinev1.PodTemplateDefaults{ Image: "default-image:latest", }, podSpec: &corev1.PodSpec{ Containers: []corev1.Container{ {Name: "no-image"}, {Name: "has-image", Image: "custom-image:v1"}, }, }, wantCheck: func(t *testing.T, podSpec *corev1.PodSpec) { if podSpec.Containers[0].Image != "default-image:latest" { t.Errorf("expected default-image:latest, got %s", podSpec.Containers[0].Image) } if podSpec.Containers[1].Image != "custom-image:v1" { t.Errorf("expected custom-image:v1 (not overridden), got %s", podSpec.Containers[1].Image) } }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r.applyContainerDefaults(tt.podTemplate, tt.podSpec) tt.wantCheck(t, tt.podSpec) }) } } func TestApplyServiceAccountName(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline podSpec *corev1.PodSpec want string }{ { name: "applies service account when not set", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ ServiceAccountName: "pipeline-sa", }, }, podSpec: &corev1.PodSpec{}, want: "pipeline-sa", }, { name: "does not override existing service account", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ ServiceAccountName: "pipeline-sa", }, }, podSpec: &corev1.PodSpec{ ServiceAccountName: "custom-sa", }, want: "custom-sa", }, { name: "does nothing when pipeline has no service account", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{}, }, podSpec: &corev1.PodSpec{}, want: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r.applyServiceAccountName(tt.pipeline, tt.podSpec) if tt.podSpec.ServiceAccountName != tt.want { t.Errorf("expected service account %q, got %q", tt.want, tt.podSpec.ServiceAccountName) } }) } } func TestApplyPodTemplateDefaults(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline job *batchv1.Job wantCheck func(t *testing.T, job *batchv1.Job) }{ { name: "applies all defaults", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ ServiceAccountName: "test-sa", PodTemplate: &pipelinev1.PodTemplateDefaults{ NodeSelector: map[string]string{"zone": "us-west-1a"}, Labels: map[string]string{"app": "pipeline"}, Image: "busybox:latest", }, }, }, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{{Name: "main"}}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Spec.NodeSelector["zone"] != "us-west-1a" { t.Error("expected node selector to be applied") } if job.Spec.Template.Labels["app"] != "pipeline" { t.Error("expected labels to be applied") } if job.Spec.Template.Spec.Containers[0].Image != "busybox:latest" { t.Error("expected default image to be applied") } if job.Spec.Template.Spec.ServiceAccountName != "test-sa" { t.Error("expected service account to be applied") } }, }, { name: "applies service account even without pod template", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ ServiceAccountName: "standalone-sa", }, }, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{{Name: "main"}}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Spec.ServiceAccountName != "standalone-sa" { t.Errorf("expected service account 'standalone-sa', got %q", job.Spec.Template.Spec.ServiceAccountName) } }, }, { name: "does nothing when no pod template and no service account", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{}, }, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{{Name: "main", Image: "original:v1"}}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Spec.Containers[0].Image != "original:v1" { t.Error("expected job to remain unchanged") } }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r.applyPodTemplateDefaults(tt.pipeline, tt.job) tt.wantCheck(t, tt.job) }) } } func TestApplySharedVolume(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline step *pipelinev1.PipelineStep job *batchv1.Job wantCheck func(t *testing.T, job *batchv1.Job) }{ { name: "applies shared volume with defaults", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ SharedVolume: &pipelinev1.SharedVolumeSpec{ VolumeSource: corev1.VolumeSource{ EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }, }, }, step: &pipelinev1.PipelineStep{Name: "test-step"}, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{{Name: "main"}}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if len(job.Spec.Template.Spec.Volumes) != 1 { t.Errorf("expected 1 volume, got %d", len(job.Spec.Template.Spec.Volumes)) } if job.Spec.Template.Spec.Volumes[0].Name != "workspace" { t.Errorf("expected volume name 'workspace', got %q", job.Spec.Template.Spec.Volumes[0].Name) } if len(job.Spec.Template.Spec.Containers[0].VolumeMounts) != 1 { t.Errorf("expected 1 volume mount, got %d", len(job.Spec.Template.Spec.Containers[0].VolumeMounts)) } if job.Spec.Template.Spec.Containers[0].VolumeMounts[0].MountPath != "/workspace" { t.Errorf("expected mount path '/workspace', got %q", job.Spec.Template.Spec.Containers[0].VolumeMounts[0].MountPath) } }, }, { name: "applies shared volume with custom name and path", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ SharedVolume: &pipelinev1.SharedVolumeSpec{ Name: "custom-vol", MountPath: "/data", VolumeSource: corev1.VolumeSource{ EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }, }, }, step: &pipelinev1.PipelineStep{Name: "test-step"}, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{{Name: "main"}}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if job.Spec.Template.Spec.Volumes[0].Name != "custom-vol" { t.Errorf("expected volume name 'custom-vol', got %q", job.Spec.Template.Spec.Volumes[0].Name) } if job.Spec.Template.Spec.Containers[0].VolumeMounts[0].MountPath != "/data" { t.Errorf("expected mount path '/data', got %q", job.Spec.Template.Spec.Containers[0].VolumeMounts[0].MountPath) } }, }, { name: "mounts to all containers", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ SharedVolume: &pipelinev1.SharedVolumeSpec{ VolumeSource: corev1.VolumeSource{ EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }, }, }, step: &pipelinev1.PipelineStep{Name: "test-step"}, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{ {Name: "container1"}, {Name: "container2"}, {Name: "container3"}, }, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { for i, c := range job.Spec.Template.Spec.Containers { if len(c.VolumeMounts) != 1 { t.Errorf("container %d: expected 1 volume mount, got %d", i, len(c.VolumeMounts)) } } }, }, { name: "does nothing when no shared volume configured", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{}, }, step: &pipelinev1.PipelineStep{Name: "test-step"}, job: &batchv1.Job{ Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{{Name: "main"}}, }, }, }, }, wantCheck: func(t *testing.T, job *batchv1.Job) { if len(job.Spec.Template.Spec.Volumes) != 0 { t.Errorf("expected 0 volumes, got %d", len(job.Spec.Template.Spec.Volumes)) } }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r.applySharedVolume(tt.pipeline, tt.step, tt.job) tt.wantCheck(t, tt.job) }) } } // Helper functions func boolPtr(b bool) *bool { return &b } func stringPtr(s string) *string { return &s }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_reconciler.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "context" "time" batchv1 "k8s.io/api/batch/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) // reconcileDelete handles cleanup when a Pipeline is being deleted func (r *PipelineReconciler) reconcileDelete(ctx context.Context, pipeline *pipelinev1.Pipeline) (ctrl.Result, error) { logger := log.FromContext(ctx) logger.Info("Deleting pipeline", "pipeline", pipeline.Name, "namespace", pipeline.Namespace) if controllerutil.ContainsFinalizer(pipeline, pipelineFinalizer) { // Cleanup: delete all jobs created by this pipeline jobList := &batchv1.JobList{} if err := r.List(ctx, jobList, client.InNamespace(pipeline.Namespace), client.MatchingLabels{ "pipeline.yaacov.io/pipeline": pipeline.Name, }); err != nil { logger.Error(err, "Failed to list jobs for cleanup") return ctrl.Result{}, err } logger.Info("Cleaning up jobs", "count", len(jobList.Items)) for i := range jobList.Items { jobName := jobList.Items[i].Name if err := r.Delete(ctx, &jobList.Items[i], client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil { logger.Error(err, "Failed to delete job", "job", jobName) return ctrl.Result{}, err } logger.V(1).Info("Deleted job", "job", jobName) } // Remove finalizer logger.V(1).Info("Removing finalizer") controllerutil.RemoveFinalizer(pipeline, pipelineFinalizer) if err := r.Update(ctx, pipeline); err != nil { logger.Error(err, "Failed to remove finalizer") return ctrl.Result{}, err } logger.Info("Pipeline deleted successfully", "pipeline", pipeline.Name) } return ctrl.Result{}, nil } // reconcilePipeline is the main reconciliation logic for an active Pipeline func (r *PipelineReconciler) reconcilePipeline(ctx context.Context, pipeline *pipelinev1.Pipeline) (ctrl.Result, error) { logger := log.FromContext(ctx) logger.V(1).Info("Reconciling pipeline", "pipeline", pipeline.Name, "phase", pipeline.Status.Phase, "stepCount", len(pipeline.Spec.Steps)) // Initialize step statuses if needed if len(pipeline.Status.Steps) == 0 { logger.Info("Initializing step statuses") if err := r.initializeStepStatuses(ctx, pipeline); err != nil { logger.Error(err, "Failed to initialize step statuses") return ctrl.Result{}, err } } // Update status of existing jobs if err := r.updateStepStatuses(ctx, pipeline); err != nil { logger.Error(err, "Failed to update step statuses") return ctrl.Result{}, err } // Analyze pipeline completion state pipelineState := r.analyzePipelineState(pipeline) logger.V(1).Info("Pipeline state analyzed", "allSucceeded", pipelineState.allSucceeded, "anyFailed", pipelineState.anyFailed, "anyRunning", pipelineState.anyRunning, "anyPending", pipelineState.anyPending, "hasPendingFailureHandlers", pipelineState.hasPendingFailureHandlers) // Update pipeline phase based on analysis if err := r.updatePipelinePhase(ctx, pipeline, pipelineState); err != nil { logger.Error(err, "Failed to update pipeline phase") return ctrl.Result{}, err } // If pipeline is complete, no need to requeue if pipeline.Status.Phase == pipelinev1.PipelinePhaseSucceeded || pipeline.Status.Phase == pipelinev1.PipelinePhaseFailed { logger.Info("Pipeline completed", "phase", pipeline.Status.Phase) return ctrl.Result{}, nil } // If pipeline is suspended, log it but still requeue to detect when resumed if pipeline.Status.Phase == pipelinev1.PipelinePhaseSuspended { logger.Info("Pipeline is suspended, waiting for jobs to be resumed", "suspendedSteps", pipelineState.suspendedSteps) } // Try to start pending steps if err := r.startReadySteps(ctx, pipeline); err != nil { logger.Error(err, "Failed to start ready steps") return ctrl.Result{}, err } // Requeue to check status again logger.V(1).Info("Requeuing pipeline for status check") return ctrl.Result{RequeueAfter: 10 * time.Second}, nil } // pipelineState represents the current state of the pipeline type pipelineState struct { allSucceeded bool anyFailed bool anyRunning bool anyPending bool anySuspended bool suspendedSteps []string hasPendingFailureHandlers bool } // analyzePipelineState analyzes the current state of all steps func (r *PipelineReconciler) analyzePipelineState(pipeline *pipelinev1.Pipeline) pipelineState { state := pipelineState{ allSucceeded: true, suspendedSteps: []string{}, } succeededCount := 0 skippedCount := 0 failedCount := 0 runningCount := 0 pendingCount := 0 suspendedCount := 0 for _, stepStatus := range pipeline.Status.Steps { switch stepStatus.Phase { case pipelinev1.StepPhaseSucceeded: succeededCount++ case pipelinev1.StepPhaseSkipped: skippedCount++ case pipelinev1.StepPhaseFailed: failedCount++ state.anyFailed = true state.allSucceeded = false case pipelinev1.StepPhaseRunning: runningCount++ state.anyRunning = true state.allSucceeded = false case pipelinev1.StepPhasePending: pendingCount++ state.anyPending = true state.allSucceeded = false case pipelinev1.StepPhaseSuspended: suspendedCount++ state.anySuspended = true state.suspendedSteps = append(state.suspendedSteps, stepStatus.Name) state.allSucceeded = false } } // Check if there are any failure handlers that could still run if state.anyPending && state.anyFailed { state.hasPendingFailureHandlers = r.hasPendingFailureHandlers(pipeline) } return state } // updatePipelinePhase updates the pipeline phase based on current state func (r *PipelineReconciler) updatePipelinePhase(ctx context.Context, pipeline *pipelinev1.Pipeline, state pipelineState) error { logger := log.FromContext(ctx) oldPhase := pipeline.Status.Phase // Determine new phase if state.anySuspended && !state.anyRunning { // Pipeline is suspended - a step is waiting to be resumed pipeline.Status.Phase = pipelinev1.PipelinePhaseSuspended } else if state.anyFailed && !state.anyRunning && !state.anySuspended && !state.hasPendingFailureHandlers { // Pipeline failed and no cleanup/failure handlers are pending pipeline.Status.Phase = pipelinev1.PipelinePhaseFailed if pipeline.Status.CompletionTime == nil { now := metav1.Now() pipeline.Status.CompletionTime = &now } } else if state.allSucceeded { // All steps completed successfully (or were skipped) pipeline.Status.Phase = pipelinev1.PipelinePhaseSucceeded if pipeline.Status.CompletionTime == nil { now := metav1.Now() pipeline.Status.CompletionTime = &now } } else if state.anyRunning || state.hasPendingFailureHandlers { pipeline.Status.Phase = pipelinev1.PipelinePhaseRunning } // Update conditions r.updateConditions(pipeline, state) // Update status if changed if oldPhase != pipeline.Status.Phase { logger.Info("Pipeline phase changed", "old", oldPhase, "new", pipeline.Status.Phase) if err := r.Status().Update(ctx, pipeline); err != nil { return err } } return nil } // initializeStepStatuses creates initial status entries for all steps func (r *PipelineReconciler) initializeStepStatuses(ctx context.Context, pipeline *pipelinev1.Pipeline) error { logger := log.FromContext(ctx) for _, step := range pipeline.Spec.Steps { pipeline.Status.Steps = append(pipeline.Status.Steps, pipelinev1.StepStatus{ Name: step.Name, Phase: pipelinev1.StepPhasePending, }) logger.V(1).Info("Initialized step status", "step", step.Name, "phase", "Pending") } if err := r.Status().Update(ctx, pipeline); err != nil { logger.Error(err, "Failed to update pipeline status during initialization") return err } logger.Info("Step statuses initialized", "count", len(pipeline.Status.Steps)) return nil } // getStepStatus retrieves the status for a given step by name func (r *PipelineReconciler) getStepStatus(pipeline *pipelinev1.Pipeline, stepName string) *pipelinev1.StepStatus { for i := range pipeline.Status.Steps { if pipeline.Status.Steps[i].Name == stepName { return &pipeline.Status.Steps[i] } } return nil }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_reconciler_test.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "testing" batchv1 "k8s.io/api/batch/v1" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) func TestAnalyzePipelineState(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline wantAllSucceeded bool wantAnyFailed bool wantAnyRunning bool wantAnyPending bool wantHasPendingFailureHandlers bool }{ { name: "all steps succeeded", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step3", Phase: pipelinev1.StepPhaseSucceeded}, }, }, }, wantAllSucceeded: true, wantAnyFailed: false, wantAnyRunning: false, wantAnyPending: false, wantHasPendingFailureHandlers: false, }, { name: "all steps succeeded or skipped", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseSkipped}, {Name: "step3", Phase: pipelinev1.StepPhaseSucceeded}, }, }, }, wantAllSucceeded: true, wantAnyFailed: false, wantAnyRunning: false, wantAnyPending: false, wantHasPendingFailureHandlers: false, }, { name: "one step failed", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, }, }, }, wantAllSucceeded: false, wantAnyFailed: true, wantAnyRunning: false, wantAnyPending: false, wantHasPendingFailureHandlers: false, }, { name: "one step running", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseRunning}, }, }, }, wantAllSucceeded: false, wantAnyFailed: false, wantAnyRunning: true, wantAnyPending: false, wantHasPendingFailureHandlers: false, }, { name: "one step pending", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhasePending}, }, }, }, wantAllSucceeded: false, wantAnyFailed: false, wantAnyRunning: false, wantAnyPending: true, wantHasPendingFailureHandlers: false, }, { name: "failed with pending failure handler", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, { Name: "cleanup", RunIf: &pipelinev1.RunIfCondition{ Condition: pipelinev1.RunIfConditionFail, Steps: []string{"step1"}, }, JobSpec: batchv1.JobSpec{}, }, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseFailed}, {Name: "cleanup", Phase: pipelinev1.StepPhasePending}, }, }, }, wantAllSucceeded: false, wantAnyFailed: true, wantAnyRunning: false, wantAnyPending: true, wantHasPendingFailureHandlers: true, }, { name: "mixed states", pipeline: &pipelinev1.Pipeline{ Spec: pipelinev1.PipelineSpec{ Steps: []pipelinev1.PipelineStep{ {Name: "step1", JobSpec: batchv1.JobSpec{}}, {Name: "step2", JobSpec: batchv1.JobSpec{}}, {Name: "step3", JobSpec: batchv1.JobSpec{}}, {Name: "step4", JobSpec: batchv1.JobSpec{}}, }, }, Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, {Name: "step3", Phase: pipelinev1.StepPhaseRunning}, {Name: "step4", Phase: pipelinev1.StepPhasePending}, }, }, }, wantAllSucceeded: false, wantAnyFailed: true, wantAnyRunning: true, wantAnyPending: true, wantHasPendingFailureHandlers: false, // No failure handler configured }, { name: "empty pipeline", pipeline: &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{}, }, }, wantAllSucceeded: true, // vacuously true wantAnyFailed: false, wantAnyRunning: false, wantAnyPending: false, wantHasPendingFailureHandlers: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { state := r.analyzePipelineState(tt.pipeline) if state.allSucceeded != tt.wantAllSucceeded { t.Errorf("allSucceeded = %v, want %v", state.allSucceeded, tt.wantAllSucceeded) } if state.anyFailed != tt.wantAnyFailed { t.Errorf("anyFailed = %v, want %v", state.anyFailed, tt.wantAnyFailed) } if state.anyRunning != tt.wantAnyRunning { t.Errorf("anyRunning = %v, want %v", state.anyRunning, tt.wantAnyRunning) } if state.anyPending != tt.wantAnyPending { t.Errorf("anyPending = %v, want %v", state.anyPending, tt.wantAnyPending) } if state.hasPendingFailureHandlers != tt.wantHasPendingFailureHandlers { t.Errorf("hasPendingFailureHandlers = %v, want %v", state.hasPendingFailureHandlers, tt.wantHasPendingFailureHandlers) } }) } } func TestGetStepStatus(t *testing.T) { r := &PipelineReconciler{} pipeline := &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded, JobName: "job1"}, {Name: "step2", Phase: pipelinev1.StepPhaseRunning, JobName: "job2"}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, } tests := []struct { name string stepName string wantNil bool want *pipelinev1.StepStatus }{ { name: "finds existing step", stepName: "step1", wantNil: false, }, { name: "finds second step", stepName: "step2", wantNil: false, }, { name: "returns nil for non-existent step", stepName: "nonexistent", wantNil: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := r.getStepStatus(pipeline, tt.stepName) if tt.wantNil { if got != nil { t.Errorf("expected nil, got %v", got) } } else { if got == nil { t.Error("expected non-nil result") } else if got.Name != tt.stepName { t.Errorf("expected step name %q, got %q", tt.stepName, got.Name) } } }) } } func TestGetStepStatusModification(t *testing.T) { r := &PipelineReconciler{} pipeline := &pipelinev1.Pipeline{ Status: pipelinev1.PipelineStatus{ Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhasePending}, }, }, } // Get pointer and modify status := r.getStepStatus(pipeline, "step1") if status == nil { t.Fatal("expected to find step1") } status.Phase = pipelinev1.StepPhaseRunning status.JobName = "test-job" // Verify modification persisted if pipeline.Status.Steps[0].Phase != pipelinev1.StepPhaseRunning { t.Error("modification should persist to original pipeline") } if pipeline.Status.Steps[0].JobName != "test-job" { t.Error("job name modification should persist to original pipeline") } }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_status.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "context" "fmt" "time" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/log" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) // updateStepStatuses fetches and updates the status of all running jobs func (r *PipelineReconciler) updateStepStatuses(ctx context.Context, pipeline *pipelinev1.Pipeline) error { logger := log.FromContext(ctx) changed := false checkedJobs := 0 for i := range pipeline.Status.Steps { stepStatus := &pipeline.Status.Steps[i] if stepStatus.JobName == "" { continue } checkedJobs++ // Fetch the job job := &batchv1.Job{} if err := r.Get(ctx, types.NamespacedName{ Name: stepStatus.JobName, Namespace: pipeline.Namespace, }, job); err != nil { if apierrors.IsNotFound(err) { logger.Info("Job not found, may have been deleted", "job", stepStatus.JobName, "step", stepStatus.Name) continue } logger.Error(err, "Failed to fetch job", "job", stepStatus.JobName, "step", stepStatus.Name) return err } // Update status from job oldPhase := stepStatus.Phase stepStatus.JobStatus = &job.Status // Determine phase from job conditions newPhase := r.determineStepPhase(job, stepStatus.Phase) if oldPhase != newPhase { stepStatus.Phase = newPhase logger.Info("Step phase changed", "step", stepStatus.Name, "job", stepStatus.JobName, "oldPhase", oldPhase, "newPhase", newPhase, "active", job.Status.Active, "succeeded", job.Status.Succeeded, "failed", job.Status.Failed) changed = true } else { logger.V(1).Info("Step status checked", "step", stepStatus.Name, "phase", stepStatus.Phase, "active", job.Status.Active) } } if changed { logger.Info("Updating pipeline status", "changedSteps", true) if err := r.Status().Update(ctx, pipeline); err != nil { logger.Error(err, "Failed to update pipeline status") return err } } else { logger.V(1).Info("No step status changes detected", "checkedJobs", checkedJobs) } return nil } // determineStepPhase determines the step phase based on job status func (r *PipelineReconciler) determineStepPhase(job *batchv1.Job, currentPhase pipelinev1.StepPhase) pipelinev1.StepPhase { // Check job conditions for terminal states for _, condition := range job.Status.Conditions { if condition.Type == batchv1.JobComplete && condition.Status == corev1.ConditionTrue { log.Log.V(1).Info("Job completed successfully", "job", job.Name, "completionTime", condition.LastTransitionTime) return pipelinev1.StepPhaseSucceeded } else if condition.Type == batchv1.JobFailed && condition.Status == corev1.ConditionTrue { log.Log.Info("Job failed", "job", job.Name, "reason", condition.Reason, "message", condition.Message, "failedPods", job.Status.Failed) return pipelinev1.StepPhaseFailed } else if condition.Type == batchv1.JobSuspended && condition.Status == corev1.ConditionTrue { log.Log.Info("Job suspended", "job", job.Name, "reason", condition.Reason, "message", condition.Message) return pipelinev1.StepPhaseSuspended } } // Check if job is actively running if job.Status.Active > 0 { if currentPhase != pipelinev1.StepPhaseRunning { log.Log.V(1).Info("Job is now running", "job", job.Name, "activePods", job.Status.Active) } return pipelinev1.StepPhaseRunning } // No change detected, keep current phase return currentPhase } // updateConditions updates the pipeline status conditions based on current phase func (r *PipelineReconciler) updateConditions(pipeline *pipelinev1.Pipeline, state pipelineState) { now := metav1.Now() var condition metav1.Condition switch pipeline.Status.Phase { case pipelinev1.PipelinePhasePending: condition = metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, Reason: "Pending", Message: "Pipeline is pending", LastTransitionTime: now, } case pipelinev1.PipelinePhaseRunning: // Count running/pending/completed steps for message runningCount := 0 completedCount := 0 for _, step := range pipeline.Status.Steps { switch step.Phase { case pipelinev1.StepPhaseRunning: runningCount++ case pipelinev1.StepPhaseSucceeded, pipelinev1.StepPhaseSkipped: completedCount++ } } condition = metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, Reason: "Running", Message: fmt.Sprintf("Pipeline is running (%d/%d steps completed, %d running)", completedCount, len(pipeline.Status.Steps), runningCount), LastTransitionTime: now, } case pipelinev1.PipelinePhaseSuspended: message := "Pipeline is suspended" if len(state.suspendedSteps) > 0 { message = fmt.Sprintf("Pipeline is suspended (suspended steps: %v)", state.suspendedSteps) } condition = metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, Reason: "Suspended", Message: message, LastTransitionTime: now, } case pipelinev1.PipelinePhaseSucceeded: duration := "" if pipeline.Status.StartTime != nil && pipeline.Status.CompletionTime != nil { d := pipeline.Status.CompletionTime.Sub(pipeline.Status.StartTime.Time) duration = fmt.Sprintf(" in %s", d.Round(time.Second)) } condition = metav1.Condition{ Type: "Ready", Status: metav1.ConditionTrue, Reason: "Succeeded", Message: fmt.Sprintf("Pipeline completed successfully%s", duration), LastTransitionTime: now, } case pipelinev1.PipelinePhaseFailed: // Find which steps failed failedSteps := []string{} for _, step := range pipeline.Status.Steps { if step.Phase == pipelinev1.StepPhaseFailed { failedSteps = append(failedSteps, step.Name) } } message := "Pipeline failed" if len(failedSteps) > 0 { message = fmt.Sprintf("Pipeline failed (failed steps: %v)", failedSteps) } condition = metav1.Condition{ Type: "Ready", Status: metav1.ConditionFalse, Reason: "Failed", Message: message, LastTransitionTime: now, } } // Check if condition actually changed before logging existingCondition := meta.FindStatusCondition(pipeline.Status.Conditions, "Ready") if existingCondition == nil || existingCondition.Status != condition.Status || existingCondition.Reason != condition.Reason { log.Log.Info("Updating pipeline condition", "pipeline", pipeline.Name, "condition", "Ready", "status", condition.Status, "reason", condition.Reason, "message", condition.Message) } meta.SetStatusCondition(&pipeline.Status.Conditions, condition) }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
internal/controller/pipeline_status_test.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controller import ( "testing" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" pipelinev1 "github.com/yaacov/jobrunner/api/v1" ) func TestDetermineStepPhase(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string job *batchv1.Job currentPhase pipelinev1.StepPhase want pipelinev1.StepPhase }{ { name: "job completed successfully", job: &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{Name: "test-job"}, Status: batchv1.JobStatus{ Conditions: []batchv1.JobCondition{ { Type: batchv1.JobComplete, Status: corev1.ConditionTrue, }, }, }, }, currentPhase: pipelinev1.StepPhaseRunning, want: pipelinev1.StepPhaseSucceeded, }, { name: "job failed", job: &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{Name: "test-job"}, Status: batchv1.JobStatus{ Conditions: []batchv1.JobCondition{ { Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded", Message: "Job has reached the specified backoff limit", }, }, Failed: 1, }, }, currentPhase: pipelinev1.StepPhaseRunning, want: pipelinev1.StepPhaseFailed, }, { name: "job is running with active pods", job: &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{Name: "test-job"}, Status: batchv1.JobStatus{ Active: 1, }, }, currentPhase: pipelinev1.StepPhasePending, want: pipelinev1.StepPhaseRunning, }, { name: "job has no terminal condition and no active pods - keep current", job: &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{Name: "test-job"}, Status: batchv1.JobStatus{ Active: 0, }, }, currentPhase: pipelinev1.StepPhaseRunning, want: pipelinev1.StepPhaseRunning, }, { name: "job condition is false - not complete", job: &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{Name: "test-job"}, Status: batchv1.JobStatus{ Conditions: []batchv1.JobCondition{ { Type: batchv1.JobComplete, Status: corev1.ConditionFalse, }, }, Active: 1, }, }, currentPhase: pipelinev1.StepPhaseRunning, want: pipelinev1.StepPhaseRunning, }, { name: "job suspended returns suspended phase", job: &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{Name: "test-job"}, Status: batchv1.JobStatus{ Conditions: []batchv1.JobCondition{ { Type: batchv1.JobSuspended, Status: corev1.ConditionTrue, }, }, }, }, currentPhase: pipelinev1.StepPhaseRunning, want: pipelinev1.StepPhaseSuspended, }, { name: "complete takes precedence over active", job: &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{Name: "test-job"}, Status: batchv1.JobStatus{ Conditions: []batchv1.JobCondition{ { Type: batchv1.JobComplete, Status: corev1.ConditionTrue, }, }, Active: 1, // Shouldn't matter if Complete is true }, }, currentPhase: pipelinev1.StepPhaseRunning, want: pipelinev1.StepPhaseSucceeded, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := r.determineStepPhase(tt.job, tt.currentPhase) if got != tt.want { t.Errorf("determineStepPhase() = %v, want %v", got, tt.want) } }) } } func TestUpdateConditions(t *testing.T) { r := &PipelineReconciler{} tests := []struct { name string pipeline *pipelinev1.Pipeline wantConditionType string wantStatus metav1.ConditionStatus wantReason string }{ { name: "pending pipeline", pipeline: &pipelinev1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "test-pipeline"}, Status: pipelinev1.PipelineStatus{ Phase: pipelinev1.PipelinePhasePending, Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhasePending}, }, }, }, wantConditionType: "Ready", wantStatus: metav1.ConditionFalse, wantReason: "Pending", }, { name: "running pipeline", pipeline: &pipelinev1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "test-pipeline"}, Status: pipelinev1.PipelineStatus{ Phase: pipelinev1.PipelinePhaseRunning, Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseRunning}, {Name: "step3", Phase: pipelinev1.StepPhasePending}, }, }, }, wantConditionType: "Ready", wantStatus: metav1.ConditionFalse, wantReason: "Running", }, { name: "succeeded pipeline", pipeline: &pipelinev1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "test-pipeline"}, Status: pipelinev1.PipelineStatus{ Phase: pipelinev1.PipelinePhaseSucceeded, Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseSucceeded}, }, }, }, wantConditionType: "Ready", wantStatus: metav1.ConditionTrue, wantReason: "Succeeded", }, { name: "failed pipeline", pipeline: &pipelinev1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "test-pipeline"}, Status: pipelinev1.PipelineStatus{ Phase: pipelinev1.PipelinePhaseFailed, Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, }, }, }, wantConditionType: "Ready", wantStatus: metav1.ConditionFalse, wantReason: "Failed", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r.updateConditions(tt.pipeline, pipelineState{}) if len(tt.pipeline.Status.Conditions) == 0 { t.Fatal("expected at least one condition") } found := false for _, cond := range tt.pipeline.Status.Conditions { if cond.Type == tt.wantConditionType { found = true if cond.Status != tt.wantStatus { t.Errorf("condition status = %v, want %v", cond.Status, tt.wantStatus) } if cond.Reason != tt.wantReason { t.Errorf("condition reason = %v, want %v", cond.Reason, tt.wantReason) } break } } if !found { t.Errorf("condition type %q not found", tt.wantConditionType) } }) } } func TestUpdateConditionsMessage(t *testing.T) { r := &PipelineReconciler{} t.Run("running pipeline shows step counts", func(t *testing.T) { pipeline := &pipelinev1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "test-pipeline"}, Status: pipelinev1.PipelineStatus{ Phase: pipelinev1.PipelinePhaseRunning, Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseSkipped}, {Name: "step3", Phase: pipelinev1.StepPhaseRunning}, {Name: "step4", Phase: pipelinev1.StepPhasePending}, }, }, } r.updateConditions(pipeline, pipelineState{}) if len(pipeline.Status.Conditions) == 0 { t.Fatal("expected condition to be set") } cond := pipeline.Status.Conditions[0] // Should show 2 completed (1 succeeded + 1 skipped), 4 total, 1 running if cond.Message == "" { t.Error("expected non-empty message") } }) t.Run("failed pipeline shows failed steps", func(t *testing.T) { pipeline := &pipelinev1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "test-pipeline"}, Status: pipelinev1.PipelineStatus{ Phase: pipelinev1.PipelinePhaseFailed, Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseSucceeded}, {Name: "step2", Phase: pipelinev1.StepPhaseFailed}, {Name: "step3", Phase: pipelinev1.StepPhaseFailed}, }, }, } r.updateConditions(pipeline, pipelineState{}) if len(pipeline.Status.Conditions) == 0 { t.Fatal("expected condition to be set") } cond := pipeline.Status.Conditions[0] // Should mention the failed steps if cond.Message == "" { t.Error("expected non-empty message") } }) } func TestUpdateConditionsPreservesExisting(t *testing.T) { r := &PipelineReconciler{} pipeline := &pipelinev1.Pipeline{ ObjectMeta: metav1.ObjectMeta{Name: "test-pipeline"}, Status: pipelinev1.PipelineStatus{ Phase: pipelinev1.PipelinePhaseRunning, Conditions: []metav1.Condition{ { Type: "CustomCondition", Status: metav1.ConditionTrue, Reason: "Custom", Message: "Custom condition", LastTransitionTime: metav1.Now(), }, }, Steps: []pipelinev1.StepStatus{ {Name: "step1", Phase: pipelinev1.StepPhaseRunning}, }, }, } r.updateConditions(pipeline, pipelineState{}) // Should have both conditions foundReady := false foundCustom := false for _, cond := range pipeline.Status.Conditions { if cond.Type == "Ready" { foundReady = true } if cond.Type == "CustomCondition" { foundCustom = true } } if !foundReady { t.Error("expected Ready condition to be added") } if !foundCustom { t.Error("expected CustomCondition to be preserved") } }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
test/e2e/e2e_suite_test.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package e2e import ( "fmt" "os" "os/exec" "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/yaacov/jobrunner/test/utils" ) var ( // Optional Environment Variables: // - CERT_MANAGER_INSTALL_SKIP=true: Skips CertManager installation during test setup. // These variables are useful if CertManager is already installed, avoiding // re-installation and conflicts. skipCertManagerInstall = os.Getenv("CERT_MANAGER_INSTALL_SKIP") == "true" // isCertManagerAlreadyInstalled will be set true when CertManager CRDs be found on the cluster isCertManagerAlreadyInstalled = false // projectImage is the name of the image which will be build and loaded // with the code source changes to be tested. projectImage = "example.com/jobrunner:v0.0.1" ) // TestE2E runs the end-to-end (e2e) test suite for the project. These tests execute in an isolated, // temporary environment to validate project changes with the purposed to be used in CI jobs. // The default setup requires Kind, builds/loads the Manager Docker image locally, and installs // CertManager. func TestE2E(t *testing.T) { RegisterFailHandler(Fail) _, _ = fmt.Fprintf(GinkgoWriter, "Starting jobrunner integration test suite\n") RunSpecs(t, "e2e suite") } var _ = BeforeSuite(func() { By("building the manager(Operator) image") cmd := exec.Command("make", "docker-build", fmt.Sprintf("IMG=%s", projectImage)) _, err := utils.Run(cmd) ExpectWithOffset(1, err).NotTo(HaveOccurred(), "Failed to build the manager(Operator) image") // TODO(user): If you want to change the e2e test vendor from Kind, ensure the image is // built and available before running the tests. Also, remove the following block. By("loading the manager(Operator) image on Kind") err = utils.LoadImageToKindClusterWithName(projectImage) ExpectWithOffset(1, err).NotTo(HaveOccurred(), "Failed to load the manager(Operator) image into Kind") // The tests-e2e are intended to run on a temporary cluster that is created and destroyed for testing. // To prevent errors when tests run in environments with CertManager already installed, // we check for its presence before execution. // Setup CertManager before the suite if not skipped and if not already installed if !skipCertManagerInstall { By("checking if cert manager is installed already") isCertManagerAlreadyInstalled = utils.IsCertManagerCRDsInstalled() if !isCertManagerAlreadyInstalled { _, _ = fmt.Fprintf(GinkgoWriter, "Installing CertManager...\n") Expect(utils.InstallCertManager()).To(Succeed(), "Failed to install CertManager") } else { _, _ = fmt.Fprintf(GinkgoWriter, "WARNING: CertManager is already installed. Skipping installation...\n") } } }) var _ = AfterSuite(func() { // Teardown CertManager after the suite if not skipped and if it was not already installed if !skipCertManagerInstall && !isCertManagerAlreadyInstalled { _, _ = fmt.Fprintf(GinkgoWriter, "Uninstalling CertManager...\n") utils.UninstallCertManager() } })
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
test/e2e/e2e_test.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package e2e import ( "encoding/json" "fmt" "os" "os/exec" "path/filepath" "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/yaacov/jobrunner/test/utils" ) // namespace where the project is deployed in const namespace = "jobrunner-system" // serviceAccountName created for the project const serviceAccountName = "jobrunner-controller-manager" // metricsServiceName is the name of the metrics service of the project const metricsServiceName = "jobrunner-controller-manager-metrics-service" // metricsRoleBindingName is the name of the RBAC that will be created to allow get the metrics data const metricsRoleBindingName = "jobrunner-metrics-binding" var _ = Describe("Manager", Ordered, func() { var controllerPodName string // Before running the tests, set up the environment by creating the namespace, // enforce the restricted security policy to the namespace, installing CRDs, // and deploying the controller. BeforeAll(func() { By("creating manager namespace") cmd := exec.Command("kubectl", "create", "ns", namespace) _, err := utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to create namespace") By("labeling the namespace to enforce the restricted security policy") cmd = exec.Command("kubectl", "label", "--overwrite", "ns", namespace, "pod-security.kubernetes.io/enforce=restricted") _, err = utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to label namespace with restricted policy") By("installing CRDs") cmd = exec.Command("make", "install") _, err = utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to install CRDs") By("deploying the controller-manager") cmd = exec.Command("make", "deploy", fmt.Sprintf("IMG=%s", projectImage)) _, err = utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to deploy the controller-manager") }) // After all tests have been executed, clean up by undeploying the controller, uninstalling CRDs, // and deleting the namespace. AfterAll(func() { By("cleaning up the curl pod for metrics") cmd := exec.Command("kubectl", "delete", "pod", "curl-metrics", "-n", namespace) _, _ = utils.Run(cmd) By("undeploying the controller-manager") cmd = exec.Command("make", "undeploy") _, _ = utils.Run(cmd) By("uninstalling CRDs") cmd = exec.Command("make", "uninstall") _, _ = utils.Run(cmd) By("removing manager namespace") cmd = exec.Command("kubectl", "delete", "ns", namespace) _, _ = utils.Run(cmd) }) // After each test, check for failures and collect logs, events, // and pod descriptions for debugging. AfterEach(func() { specReport := CurrentSpecReport() if specReport.Failed() { By("Fetching controller manager pod logs") cmd := exec.Command("kubectl", "logs", controllerPodName, "-n", namespace) controllerLogs, err := utils.Run(cmd) if err == nil { _, _ = fmt.Fprintf(GinkgoWriter, "Controller logs:\n %s", controllerLogs) } else { _, _ = fmt.Fprintf(GinkgoWriter, "Failed to get Controller logs: %s", err) } By("Fetching Kubernetes events") cmd = exec.Command("kubectl", "get", "events", "-n", namespace, "--sort-by=.lastTimestamp") eventsOutput, err := utils.Run(cmd) if err == nil { _, _ = fmt.Fprintf(GinkgoWriter, "Kubernetes events:\n%s", eventsOutput) } else { _, _ = fmt.Fprintf(GinkgoWriter, "Failed to get Kubernetes events: %s", err) } By("Fetching curl-metrics logs") cmd = exec.Command("kubectl", "logs", "curl-metrics", "-n", namespace) metricsOutput, err := utils.Run(cmd) if err == nil { _, _ = fmt.Fprintf(GinkgoWriter, "Metrics logs:\n %s", metricsOutput) } else { _, _ = fmt.Fprintf(GinkgoWriter, "Failed to get curl-metrics logs: %s", err) } By("Fetching controller manager pod description") cmd = exec.Command("kubectl", "describe", "pod", controllerPodName, "-n", namespace) podDescription, err := utils.Run(cmd) if err == nil { fmt.Println("Pod description:\n", podDescription) } else { fmt.Println("Failed to describe controller pod") } } }) SetDefaultEventuallyTimeout(2 * time.Minute) SetDefaultEventuallyPollingInterval(time.Second) Context("Manager", func() { It("should run successfully", func() { By("validating that the controller-manager pod is running as expected") verifyControllerUp := func(g Gomega) { // Get the name of the controller-manager pod cmd := exec.Command("kubectl", "get", "pods", "-l", "control-plane=controller-manager", "-o", "go-template={{ range .items }}"+ "{{ if not .metadata.deletionTimestamp }}"+ "{{ .metadata.name }}"+ "{{ \"\\n\" }}{{ end }}{{ end }}", "-n", namespace, ) podOutput, err := utils.Run(cmd) g.Expect(err).NotTo(HaveOccurred(), "Failed to retrieve controller-manager pod information") podNames := utils.GetNonEmptyLines(podOutput) g.Expect(podNames).To(HaveLen(1), "expected 1 controller pod running") controllerPodName = podNames[0] g.Expect(controllerPodName).To(ContainSubstring("controller-manager")) // Validate the pod's status cmd = exec.Command("kubectl", "get", "pods", controllerPodName, "-o", "jsonpath={.status.phase}", "-n", namespace, ) output, err := utils.Run(cmd) g.Expect(err).NotTo(HaveOccurred()) g.Expect(output).To(Equal("Running"), "Incorrect controller-manager pod status") } Eventually(verifyControllerUp).Should(Succeed()) }) It("should ensure the metrics endpoint is serving metrics", func() { By("creating a ClusterRoleBinding for the service account to allow access to metrics") cmd := exec.Command("kubectl", "create", "clusterrolebinding", metricsRoleBindingName, "--clusterrole=jobrunner-metrics-reader", fmt.Sprintf("--serviceaccount=%s:%s", namespace, serviceAccountName), ) _, err := utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to create ClusterRoleBinding") By("validating that the metrics service is available") cmd = exec.Command("kubectl", "get", "service", metricsServiceName, "-n", namespace) _, err = utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Metrics service should exist") By("getting the service account token") token, err := serviceAccountToken() Expect(err).NotTo(HaveOccurred()) Expect(token).NotTo(BeEmpty()) By("waiting for the metrics endpoint to be ready") verifyMetricsEndpointReady := func(g Gomega) { cmd := exec.Command("kubectl", "get", "endpoints", metricsServiceName, "-n", namespace) output, err := utils.Run(cmd) g.Expect(err).NotTo(HaveOccurred()) g.Expect(output).To(ContainSubstring("8443"), "Metrics endpoint is not ready") } Eventually(verifyMetricsEndpointReady).Should(Succeed()) By("verifying that the controller manager is serving the metrics server") verifyMetricsServerStarted := func(g Gomega) { cmd := exec.Command("kubectl", "logs", controllerPodName, "-n", namespace) output, err := utils.Run(cmd) g.Expect(err).NotTo(HaveOccurred()) g.Expect(output).To(ContainSubstring("controller-runtime.metrics\tServing metrics server"), "Metrics server not yet started") } Eventually(verifyMetricsServerStarted).Should(Succeed()) By("creating the curl-metrics pod to access the metrics endpoint") cmd = exec.Command("kubectl", "run", "curl-metrics", "--restart=Never", "--namespace", namespace, "--image=curlimages/curl:latest", "--overrides", fmt.Sprintf(`{ "spec": { "containers": [{ "name": "curl", "image": "curlimages/curl:latest", "command": ["/bin/sh", "-c"], "args": ["curl -v -k -H 'Authorization: Bearer %s' https://%s.%s.svc.cluster.local:8443/metrics"], "securityContext": { "allowPrivilegeEscalation": false, "capabilities": { "drop": ["ALL"] }, "runAsNonRoot": true, "runAsUser": 1000, "seccompProfile": { "type": "RuntimeDefault" } } }], "serviceAccount": "%s" } }`, token, metricsServiceName, namespace, serviceAccountName)) _, err = utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to create curl-metrics pod") By("waiting for the curl-metrics pod to complete.") verifyCurlUp := func(g Gomega) { cmd := exec.Command("kubectl", "get", "pods", "curl-metrics", "-o", "jsonpath={.status.phase}", "-n", namespace) output, err := utils.Run(cmd) g.Expect(err).NotTo(HaveOccurred()) g.Expect(output).To(Equal("Succeeded"), "curl pod in wrong status") } Eventually(verifyCurlUp, 5*time.Minute).Should(Succeed()) By("getting the metrics by checking curl-metrics logs") metricsOutput := getMetricsOutput() Expect(metricsOutput).To(ContainSubstring( "controller_runtime_reconcile_total", )) }) // +kubebuilder:scaffold:e2e-webhooks-checks // TODO: Customize the e2e test suite with scenarios specific to your project. // Consider applying sample/CR(s) and check their status and/or verifying // the reconciliation by using the metrics, i.e.: // metricsOutput := getMetricsOutput() // Expect(metricsOutput).To(ContainSubstring( // fmt.Sprintf(`controller_runtime_reconcile_total{controller="%s",result="success"} 1`, // strings.ToLower(<Kind>), // )) }) }) // serviceAccountToken returns a token for the specified service account in the given namespace. // It uses the Kubernetes TokenRequest API to generate a token by directly sending a request // and parsing the resulting token from the API response. func serviceAccountToken() (string, error) { const tokenRequestRawString = `{ "apiVersion": "authentication.k8s.io/v1", "kind": "TokenRequest" }` // Temporary file to store the token request secretName := fmt.Sprintf("%s-token-request", serviceAccountName) tokenRequestFile := filepath.Join("/tmp", secretName) err := os.WriteFile(tokenRequestFile, []byte(tokenRequestRawString), os.FileMode(0o644)) if err != nil { return "", err } var out string verifyTokenCreation := func(g Gomega) { // Execute kubectl command to create the token cmd := exec.Command("kubectl", "create", "--raw", fmt.Sprintf( "/api/v1/namespaces/%s/serviceaccounts/%s/token", namespace, serviceAccountName, ), "-f", tokenRequestFile) output, err := cmd.CombinedOutput() g.Expect(err).NotTo(HaveOccurred()) // Parse the JSON output to extract the token var token tokenRequest err = json.Unmarshal(output, &token) g.Expect(err).NotTo(HaveOccurred()) out = token.Status.Token } Eventually(verifyTokenCreation).Should(Succeed()) return out, err } // getMetricsOutput retrieves and returns the logs from the curl pod used to access the metrics endpoint. func getMetricsOutput() string { By("getting the curl-metrics logs") cmd := exec.Command("kubectl", "logs", "curl-metrics", "-n", namespace) metricsOutput, err := utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to retrieve logs from curl pod") Expect(metricsOutput).To(ContainSubstring("< HTTP/1.1 200 OK")) return metricsOutput } // tokenRequest is a simplified representation of the Kubernetes TokenRequest API response, // containing only the token field that we need to extract. type tokenRequest struct { Status struct { Token string `json:"token"` } `json:"status"` }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
test/utils/utils.go
Go
/* Copyright 2025. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package utils import ( "bufio" "bytes" "fmt" "os" "os/exec" "strings" . "github.com/onsi/ginkgo/v2" // nolint:revive,staticcheck ) const ( prometheusOperatorVersion = "v0.77.1" prometheusOperatorURL = "https://github.com/prometheus-operator/prometheus-operator/" + "releases/download/%s/bundle.yaml" certmanagerVersion = "v1.16.3" certmanagerURLTmpl = "https://github.com/cert-manager/cert-manager/releases/download/%s/cert-manager.yaml" ) func warnError(err error) { _, _ = fmt.Fprintf(GinkgoWriter, "warning: %v\n", err) } // Run executes the provided command within this context func Run(cmd *exec.Cmd) (string, error) { dir, _ := GetProjectDir() cmd.Dir = dir if err := os.Chdir(cmd.Dir); err != nil { _, _ = fmt.Fprintf(GinkgoWriter, "chdir dir: %q\n", err) } cmd.Env = append(os.Environ(), "GO111MODULE=on") command := strings.Join(cmd.Args, " ") _, _ = fmt.Fprintf(GinkgoWriter, "running: %q\n", command) output, err := cmd.CombinedOutput() if err != nil { return string(output), fmt.Errorf("%q failed with error %q: %w", command, string(output), err) } return string(output), nil } // InstallPrometheusOperator installs the prometheus Operator to be used to export the enabled metrics. func InstallPrometheusOperator() error { url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion) cmd := exec.Command("kubectl", "create", "-f", url) _, err := Run(cmd) return err } // UninstallPrometheusOperator uninstalls the prometheus func UninstallPrometheusOperator() { url := fmt.Sprintf(prometheusOperatorURL, prometheusOperatorVersion) cmd := exec.Command("kubectl", "delete", "-f", url) if _, err := Run(cmd); err != nil { warnError(err) } } // IsPrometheusCRDsInstalled checks if any Prometheus CRDs are installed // by verifying the existence of key CRDs related to Prometheus. func IsPrometheusCRDsInstalled() bool { // List of common Prometheus CRDs prometheusCRDs := []string{ "prometheuses.monitoring.coreos.com", "prometheusrules.monitoring.coreos.com", "prometheusagents.monitoring.coreos.com", } cmd := exec.Command("kubectl", "get", "crds", "-o", "custom-columns=NAME:.metadata.name") output, err := Run(cmd) if err != nil { return false } crdList := GetNonEmptyLines(output) for _, crd := range prometheusCRDs { for _, line := range crdList { if strings.Contains(line, crd) { return true } } } return false } // UninstallCertManager uninstalls the cert manager func UninstallCertManager() { url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion) cmd := exec.Command("kubectl", "delete", "-f", url) if _, err := Run(cmd); err != nil { warnError(err) } } // InstallCertManager installs the cert manager bundle. func InstallCertManager() error { url := fmt.Sprintf(certmanagerURLTmpl, certmanagerVersion) cmd := exec.Command("kubectl", "apply", "-f", url) if _, err := Run(cmd); err != nil { return err } // Wait for cert-manager-webhook to be ready, which can take time if cert-manager // was re-installed after uninstalling on a cluster. cmd = exec.Command("kubectl", "wait", "deployment.apps/cert-manager-webhook", "--for", "condition=Available", "--namespace", "cert-manager", "--timeout", "5m", ) _, err := Run(cmd) return err } // IsCertManagerCRDsInstalled checks if any Cert Manager CRDs are installed // by verifying the existence of key CRDs related to Cert Manager. func IsCertManagerCRDsInstalled() bool { // List of common Cert Manager CRDs certManagerCRDs := []string{ "certificates.cert-manager.io", "issuers.cert-manager.io", "clusterissuers.cert-manager.io", "certificaterequests.cert-manager.io", "orders.acme.cert-manager.io", "challenges.acme.cert-manager.io", } // Execute the kubectl command to get all CRDs cmd := exec.Command("kubectl", "get", "crds") output, err := Run(cmd) if err != nil { return false } // Check if any of the Cert Manager CRDs are present crdList := GetNonEmptyLines(output) for _, crd := range certManagerCRDs { for _, line := range crdList { if strings.Contains(line, crd) { return true } } } return false } // LoadImageToKindClusterWithName loads a local container image to the kind cluster func LoadImageToKindClusterWithName(name string) error { cluster := "kind" if v, ok := os.LookupEnv("KIND_CLUSTER"); ok { cluster = v } // Check if we should use podman (CONTAINER_TOOL=podman) containerTool := os.Getenv("CONTAINER_TOOL") if containerTool == "podman" { // For podman, save the image to a tar archive and load it with kind archivePath := "/tmp/kind-image.tar" saveCmd := exec.Command("podman", "save", "-o", archivePath, name) if _, err := Run(saveCmd); err != nil { return fmt.Errorf("failed to save podman image: %w", err) } defer func() { _ = os.Remove(archivePath) }() kindOptions := []string{"load", "image-archive", archivePath, "--name", cluster} cmd := exec.Command("kind", kindOptions...) _, err := Run(cmd) return err } // Default: use docker kindOptions := []string{"load", "docker-image", name, "--name", cluster} cmd := exec.Command("kind", kindOptions...) _, err := Run(cmd) return err } // GetNonEmptyLines converts given command output string into individual objects // according to line breakers, and ignores the empty elements in it. func GetNonEmptyLines(output string) []string { var res []string elements := strings.Split(output, "\n") for _, element := range elements { if element != "" { res = append(res, element) } } return res } // GetProjectDir will return the directory where the project is func GetProjectDir() (string, error) { wd, err := os.Getwd() if err != nil { return wd, fmt.Errorf("failed to get current working directory: %w", err) } wd = strings.ReplaceAll(wd, "/test/e2e", "") return wd, nil } // UncommentCode searches for target in the file and remove the comment prefix // of the target content. The target content may span multiple lines. func UncommentCode(filename, target, prefix string) error { // false positive // nolint:gosec content, err := os.ReadFile(filename) if err != nil { return fmt.Errorf("failed to read file %q: %w", filename, err) } strContent := string(content) idx := strings.Index(strContent, target) if idx < 0 { return fmt.Errorf("unable to find the code %q to be uncomment", target) } out := new(bytes.Buffer) _, err = out.Write(content[:idx]) if err != nil { return fmt.Errorf("failed to write to output: %w", err) } scanner := bufio.NewScanner(bytes.NewBufferString(target)) if !scanner.Scan() { return nil } for { if _, err = out.WriteString(strings.TrimPrefix(scanner.Text(), prefix)); err != nil { return fmt.Errorf("failed to write to output: %w", err) } // Avoid writing a newline in case the previous line was the last in target. if !scanner.Scan() { break } if _, err = out.WriteString("\n"); err != nil { return fmt.Errorf("failed to write to output: %w", err) } } if _, err = out.Write(content[idx+len(target):]); err != nil { return fmt.Errorf("failed to write to output: %w", err) } // false positive // nolint:gosec if err = os.WriteFile(filename, out.Bytes(), 0644); err != nil { return fmt.Errorf("failed to write file %q: %w", filename, err) } return nil }
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
ui/eslint.config.js
JavaScript
import eslint from '@eslint/js'; import tseslint from '@typescript-eslint/eslint-plugin'; import tsparser from '@typescript-eslint/parser'; export default [ eslint.configs.recommended, { files: ['src/**/*.ts', 'src/**/*.js'], languageOptions: { parser: tsparser, parserOptions: { ecmaVersion: 'latest', sourceType: 'module', }, globals: { console: 'readonly', window: 'readonly', document: 'readonly', fetch: 'readonly', URL: 'readonly', URLPattern: 'readonly', URLSearchParams: 'readonly', HTMLElement: 'readonly', HTMLInputElement: 'readonly', HTMLSelectElement: 'readonly', HTMLTextAreaElement: 'readonly', CustomEvent: 'readonly', Event: 'readonly', KeyboardEvent: 'readonly', MouseEvent: 'readonly', Node: 'readonly', EventListener: 'readonly', setInterval: 'readonly', clearInterval: 'readonly', setTimeout: 'readonly', confirm: 'readonly', alert: 'readonly', btoa: 'readonly', atob: 'readonly', Bun: 'readonly', }, }, plugins: { '@typescript-eslint': tseslint, }, rules: { // TypeScript specific rules '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }], '@typescript-eslint/no-explicit-any': 'warn', // General rules 'no-unused-vars': 'off', // Use TypeScript version instead 'no-undef': 'off', // TypeScript handles this 'no-console': 'off', 'prefer-const': 'warn', 'no-var': 'error', }, }, { ignores: ['dist/**', 'node_modules/**'], }, ];
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat
ui/public/index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JobRunner - Pipeline Builder & Monitor</title> <link rel="icon" type="image/svg+xml" href="/jobrunner-logo.svg"> <!-- Red Hat fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Red+Hat+Display:wght@400;500;600;700&family=Red+Hat+Mono:wght@400;500&family=Red+Hat+Text:wght@400;500;600&display=swap" rel="stylesheet"> <!-- RHDS Light DOM styles for components that need them --> <link rel="stylesheet" href="/node_modules/@rhds/elements/elements/rh-breadcrumb/rh-breadcrumb-lightdom.css"> <link rel="stylesheet" href="/node_modules/@rhds/elements/elements/rh-navigation-primary/rh-navigation-primary-lightdom.css"> <link rel="stylesheet" href="/node_modules/@rhds/elements/elements/rh-navigation-vertical/rh-navigation-vertical-lightdom.css"> <link rel="stylesheet" href="/node_modules/@rhds/elements/elements/rh-table/rh-table-lightdom.css"> <style> *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { /* RHDS-inspired tokens */ --rh-color-brand-red: #ee0000; --rh-color-brand-red-dark: #a60000; --rh-color-surface-lightest: #ffffff; --rh-color-surface-lighter: #f5f5f5; --rh-color-surface-light: #e0e0e0; --rh-color-text-primary: #151515; --rh-color-text-secondary: #6a6e73; --rh-color-border-subtle: #d2d2d2; --rh-color-green-50: #3e8635; --rh-color-red-50: #c9190b; --rh-color-teal-50: #009596; --rh-color-yellow-50: #f0ab00; --rh-color-gray-30: #d2d2d2; --rh-color-gray-40: #8a8d90; --rh-space-xs: 4px; --rh-space-sm: 8px; --rh-space-md: 16px; --rh-space-lg: 24px; --rh-space-xl: 32px; --rh-space-2xl: 48px; --rh-font-family-heading: 'Red Hat Display', sans-serif; --rh-font-family-body: 'Red Hat Text', sans-serif; --rh-font-family-code: 'Red Hat Mono', monospace; --rh-font-size-heading-lg: 1.75rem; --rh-font-size-heading-md: 1.5rem; --rh-font-size-heading-sm: 1.25rem; --rh-font-size-heading-xs: 1.125rem; --rh-font-size-body-lg: 1.125rem; --rh-font-size-body-md: 1rem; --rh-font-size-body-sm: 0.875rem; --rh-font-size-body-xs: 0.75rem; --rh-border-radius-default: 3px; --rh-border-radius-pill: 64px; --rh-box-shadow-sm: 0 1px 2px 0 rgba(21, 21, 21, 0.08); --rh-box-shadow-md: 0 4px 6px -1px rgba(21, 21, 21, 0.1); --rh-box-shadow-lg: 0 10px 15px -3px rgba(21, 21, 21, 0.1); } html, body { font-family: var(--rh-font-family-body); background: var(--rh-color-surface-lightest); color: var(--rh-color-text-primary); line-height: 1.5; min-height: 100vh; } /* Loading state */ .app-loading { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; gap: 1rem; color: var(--rh-color-text-secondary); } .app-loading-spinner { width: 40px; height: 40px; border: 3px solid var(--rh-color-gray-30); border-top-color: var(--rh-color-brand-red); border-radius: 50%; animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } /* Ensure RHDS components render correctly */ rh-card { display: block; } /* Remove blue focus outline from RHDS tab components */ rh-tabs, rh-tab, rh-tab-panel { outline: none !important; } rh-tabs:focus, rh-tabs:focus-visible, rh-tabs:focus-within, rh-tab:focus, rh-tab:focus-visible, rh-tab:focus-within, rh-tab-panel:focus, rh-tab-panel:focus-visible { outline: none !important; box-shadow: none !important; } /* Override RHDS focus styling via CSS custom properties */ rh-tabs { --rh-tabs-link-focus-outline: none; --rh-tabs-focus-outline-color: transparent; --rh-tabs-focus-outline-width: 0; } rh-tab { --rh-tab-focus-outline: none; --rh-focus-outline-color: transparent; --rh-focus-outline-width: 0; } </style> </head> <body> <div id="app" class="app-loading"> <div class="app-loading-spinner"></div> <span>Loading JobRunner...</span> </div> <script type="module" src="/main.js"></script> </body> </html>
yaacov/jobrunner
1
A job runner runs Kubernetes jobs sequentially.
TypeScript
yaacov
Yaacov Zamir
Red Hat