diff --git a/.github/workflows/chrome-extension-ci.yml b/.github/workflows/chrome-extension-ci.yml index 3d65d43..a8ed94f 100644 --- a/.github/workflows/chrome-extension-ci.yml +++ b/.github/workflows/chrome-extension-ci.yml @@ -1,144 +1,24 @@ name: Chrome Extension CI - on: push: - branches: [ main, develop, test ] + branches: [main, develop, 'feat/**'] pull_request: - branches: [ main ] - permissions: - contents: write - pull-requests: write - issues: write - + contents: read jobs: - version-check: + verify: runs-on: ubuntu-latest - if: github.event_name == 'pull_request' && github.base_ref == 'main' && github.head_ref == 'test' - steps: - - name: Checkout main branch - uses: actions/checkout@v3 - with: - ref: main - - - name: Get main version - id: main_version - run: | - MAIN_VERSION=$(grep '"version"' manifest.json | cut -d '"' -f 4) - echo "main_version=$MAIN_VERSION" >> $GITHUB_OUTPUT - - - name: Checkout PR branch - uses: actions/checkout@v3 - - - name: Get PR version - id: pr_version - run: | - PR_VERSION=$(grep '"version"' manifest.json | cut -d '"' -f 4) - echo "pr_version=$PR_VERSION" >> $GITHUB_OUTPUT - - - name: Compare versions - run: | - if [ "${{ steps.main_version.outputs.main_version }}" == "${{ steps.pr_version.outputs.pr_version }}" ]; then - echo "Error: Version in manifest.json has not been updated." - exit 1 - else - echo "Version has been updated from ${{ steps.main_version.outputs.main_version }} to ${{ steps.pr_version.outputs.pr_version }}" - fi - - lint: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Use Node.js - uses: actions/setup-node@v3 - with: - node-version: '16' - - - name: Install ESLint and plugins - run: | - npm install eslint@7.32.0 \ - @typescript-eslint/eslint-plugin@4.33.0 \ - @typescript-eslint/parser@4.33.0 - - - name: Create ESLint config if not exists - run: | - if [ ! -f ".eslintrc.js" ] && [ ! -f ".eslintrc.json" ] && [ ! -f ".eslintrc.yaml" ] && [ ! -f ".eslintrc.yml" ]; then - echo "module.exports = { - root: true, - extends: [ - 'eslint:recommended', - 'plugin:@typescript-eslint/recommended', - ], - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint'], - rules: { - '@typescript-eslint/ban-ts-comment': 'off', - '@typescript-eslint/no-explicit-any': 'off', - 'no-unused-vars': 'off', - '@typescript-eslint/no-unused-vars': ['warn', { - 'argsIgnorePattern': '^_', - 'varsIgnorePattern': '^_', - 'caughtErrorsIgnorePattern': '^_' - }], - 'no-undef': 'warn' - }, - env: { - browser: true, - node: true, - es6: true, - webextensions: true - }, - parserOptions: { - ecmaVersion: 2020, - sourceType: 'module' - }, - globals: { - chrome: 'readonly', - GithubExtensionSettings: 'readonly', - enhanceRelativeTimes: 'readonly', - isEnhancing: 'writable', - enhancementComplete: 'writable', - enhanceContributors: 'readonly', - observeDomForElement: 'readonly', - debug: 'readonly', - formatDateTime: 'readonly' - } - };" > .eslintrc.js - echo "Created .eslintrc.js" - else - echo "ESLint config already exists" - fi - - - name: Run ESLint - run: npx eslint . --ext .js,.jsx,.ts,.tsx - - build-and-release: - needs: [version-check, lint] - runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - - steps: - - name: Checkout code - uses: actions/checkout@v3 - - - name: Read version from manifest - id: manifest - run: | - VERSION=$(grep '"version"' manifest.json | cut -d '"' -f 4) - echo "version=$VERSION" >> $GITHUB_OUTPUT - - - name: Package extension - run: | - zip -r github-enhancer-${{ steps.manifest.outputs.version }}.zip . -x "*.git*" "node_modules/*" "*.md" ".github/*" "package*.json" ".eslintrc.js" - - - name: Create Release - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh release create v${{ steps.manifest.outputs.version }} \ - --title "Release v${{ steps.manifest.outputs.version }}" \ - --notes "Release notes for version ${{ steps.manifest.outputs.version }}" \ - github-enhancer-${{ steps.manifest.outputs.version }}.zip \ No newline at end of file + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + - run: npm ci --ignore-scripts + - run: npm test + - run: npm run check + - run: npm run package + - uses: actions/upload-artifact@v4 + with: + name: github-enhancer + path: dist/*.zip diff --git a/.gitignore b/.gitignore index ddcd1b1..607533f 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,17 @@ output # Test files html.html + +# Local release and test artifacts +dist/ +coverage/ +.superpowers/ + +# Private development evidence; public research is explicitly allowlisted. +docs/screenshots/ +docs/qa-exports/ +docs/superpowers/ +docs/store-release-draft.md +docs/research/* +!docs/research/competitors.md +!docs/research/technical-audit.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..802d22f --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +## 3.0.0 +- Added source-linked code basket, multi-file Markdown export and mutable-link labels. +- Added named workspaces joining pages, snippets and private notes, with reopen and Markdown export. +- Added loaded-file PR review navigation, folder/type grouping, private file notes, resume and revision-aware local marks. +- Added loaded-comment search, author/saved filters, source jumps and important-comment bookmarks. +- Added private reply drafts, reusable templates, session recovery and explicit copy-only output. +- Expanded command search to workspace notes, code evidence and private PR notes. +- Fixed out-of-snapshot code selection, grouped review traversal and focus/selection retention. +- Upgraded local schema/backups to version 2 while retaining version 1 imports. +- Fixed wide layout so repository content expands alongside the sidebar's new position. + +- Add a device-local workspace for saved repositories, issues, PRs, discussions, commits, and code pages. +- Add private notes, text search, type filters, removal with Undo, and JSON backup merge. +- Add an isolated in-page workbench, redesigned toolbar popup, and settings page. +- Add contextual copy actions, repository shortcuts, and an Alt+Shift+K command search. +- Replace destructive date badges with reversible exact-date annotations, local/UTC formatting, and reading modes. +- Serialize storage mutations and validate URLs, settings, imports, and worker messages. +- Remove API token handling, API host access, scripting permission, animated themes, contributor replacements, and inaccurate API-dependent file sizes. +- Add repeatable tests, asset/syntax checks, least-privilege CI, and release packaging. diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..244fdd0 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,19 @@ +# GitHub Enhancer design system + +## Scene and direction +A developer moves between a bright office and an evening laptop session while researching code. Follow GitHub's selected color mode in-page and the OS in standalone extension pages. Preserve the existing GitHub-aligned blue identity. + +## Color +Restrained: canvas white / #0d1117, secondary surface #f6f8fa / #161b22, ink #1f2328 / #e6edf3, muted #59636e / #919ba6, border #d1d9e0 / #30363d, primary blue #0969da / #4493f8. Blue identifies actions, selected state, and focus. Success green only communicates completion. + +## Typography +System sans; 13px compact body, 14px input, 18px section headings, 24px workbench title. Monospace only for owner/repo identifiers and keyboard hints. No uppercase eyebrows. + +## Surfaces +Popup: 400px compact workbench, five task sections: contextual tools, code basket, workspaces, writing and saved pages. In-page workbench: isolated extension-origin frame, right aligned nonmodal 400px panel, bounded to viewport, no GitHub layout shift. Command palette: accessible overlay with keyboard focus and explicit close. Settings: readable two-column desktop layout, stacked narrow screens. + +## Components +Single 1px border, 8px control radius, 12px panel radius. Lists use separators, not nested cards. Icons use a consistent 16px stroke vocabulary. Labeled native inputs, buttons and selects. State feedback uses a live status region; destructive actions offer Undo. + +## Interaction +Short 150ms opacity/transform transitions; reduced-motion removes transitions. Arrow keys and Enter in the palette, Escape dismisses and restores focus. Notes save explicitly to avoid pretending persistence succeeded. All empty, loading, disconnected and storage-error states explain the next action. diff --git a/PRIVACY.md b/PRIVACY.md new file mode 100644 index 0000000..8ed7026 --- /dev/null +++ b/PRIVACY.md @@ -0,0 +1,27 @@ +# Privacy + +GitHub Enhancer 3 runs on your device. It has no backend and does not collect analytics. + +## Stored data + +When you choose Save page or Save note, the extension stores the GitHub URL, page title, repository name, page type, your note, and creation/update timestamps in `chrome.storage.local`. Code excerpts you explicitly collect include their text, line range, path, language and source URL. Workspaces store links to saved records and notes. PR review records contain private per-file notes, local marks, revision references when verified and the last visited file. Reply templates store the title and Markdown body you choose to save. Preferences are also stored locally. Unsaved page notes, workspace names/notes, excerpt ranges/annotations PR file notes, reply drafts and template edits are held in extension session storage for recovery after closing a popup or tab; session drafts clear when the browser session ends. It does not record browsing history or automatically save visited pages. + +The toolbar popup uses `activeTab` to identify the page you choose to save. A content script on github.com reads the current URL/title, timestamps and loaded code/diff/comment content to provide the workbench and reading tools. Notes are displayed in an extension-origin frame or extension page, so they are not inserted into GitHub's readable page DOM. GitHub can see that an extension frame exists, but same-origin browser protections prevent its page scripts from reading the frame's notes. + +## Network and authentication + +The extension does not call the GitHub API or any other server. It never asks for a personal access token, password, or sign-in. Following a link in the extension opens GitHub normally, using your existing browser session. GitHub's own privacy policy then applies. + +## Backups and deletion + +Export creates a local JSON file containing saved URLs, titles, excerpts, workspace collections, review notes/marks, reply templates, timestamps, and preferences. Markdown exports include the selected excerpts, source links and saved notes. Workspace export can explicitly include saved private file notes from linked PRs when you select that option. Private repository names and any sensitive information you put in notes are included. Export only to a location you trust. Import is local, validates the file, and merges entries by URL while retaining more recent local edits. + +Use Remove to delete a saved item; Undo restores the most recently removed item during that UI session. Uninstalling removes extension-local data. Chrome profile backups and exported files are outside the extension's control. Notes are protected by your browser profile, not encrypted with a separate extension password. + +## Updates from older versions + +Version 3 reads only the legacy date and locale preferences from Chrome sync storage once. It does not use legacy authentication tokens, API caches, or decorative settings. Legacy data is left untouched to avoid silently deleting user information. + +## Limited Use + +GitHub Enhancer's use of user data complies with the Chrome Web Store User Data Policy, including its Limited Use requirements. Data is used only to provide the user-facing features described here. The extension does not sell data, use it for advertising, or transfer it to third parties. Copying or exporting data is initiated by you; you control where that output goes. diff --git a/PRODUCT.md b/PRODUCT.md new file mode 100644 index 0000000..e596f64 --- /dev/null +++ b/PRODUCT.md @@ -0,0 +1,29 @@ +# GitHub Enhancer + +## Register +product + +## Users +Developers and maintainers browsing repositories, issues, and pull requests throughout the day. They switch between investigations and want to recover their own context quickly. + +## Product Purpose +A private GitHub investigation workbench: review loaded PR diffs, collect source-linked code excerpts and organize pages and notes into named workspaces. Saved pages and reading utilities support these core workflows. Works without accounts, tokens, or a server. + +## Brand Personality +Focused, capable, considered. English product language for a global developer audience; date locale can follow the browser or use English/Turkish. + +## Anti-references +The previous extension's floating orbs, cursor particles, continuous animation, and glass effects. Avoid duplicating GitHub's native file tree or pretending to replace its search. + +## Design Principles +- Keep the user's place, not a second copy of GitHub. +- Only ask for attention when the user invokes a tool. +- Local data and transparent controls build trust. +- Preserve GitHub's native workflows and semantics. +- Fast keyboard paths complement visible controls. + +## Accessibility & Inclusion +Keyboard operation, visible focus, clear labels, reduced motion, light/dark adaptation, with WCAG AA contrast as a design target; full conformance has not been audited. Never override native GitHub keyboard shortcuts. + +## Decision authority +The user explicitly delegated product/design decisions and authorized discussion with independent agents. These choices combine that brief with repository analysis and competitor research. diff --git a/README.md b/README.md index ff1009e..d77083f 100644 --- a/README.md +++ b/README.md @@ -1,158 +1,80 @@ -# ๐Ÿš€ GitHub Enhancer -[![Chrome Extension CI](https://github.com/adomorn/Github-Enhancer/actions/workflows/chrome-extension-ci.yml/badge.svg)](https://github.com/adomorn/Github-Enhancer/actions/workflows/chrome-extension-ci.yml) -![Version](https://img.shields.io/badge/version-2.0.0-blue.svg) -![License](https://img.shields.io/badge/license-MIT-green.svg) - -Transform your GitHub browsing experience with stunning visual enhancements, modern animations, and improved functionality! โœจ - -## ๐ŸŽฏ Features - -### ๐ŸŽจ **Theme Enhancements** -- **๐Ÿ”ข Binary Cursor Trail** - Interactive 1/0 particles that follow your cursor with random rotation -- **๐ŸŒŸ Enhanced Star Button Animations** - Magical glow effects with floating sparkles on hover/click -- **๐ŸŒŒ Dynamic Floating Orbs Background** - Smooth animated orbs and geometric particles -- **๐Ÿ’ซ Advanced 3D Hover Effects** - Glassmorphism with 3D transforms and perspective -- **โšก Micro-Interactions** - Enhanced file tree, code highlighting, and navigation animations - -### ๐Ÿ“Š **Data Enhancements** -- **๐Ÿ‘ฅ Enhanced Contributor Cards** - Detailed contributor information with modern styling -- **๐Ÿ“… Full Date/Time Display** - Complete timestamps instead of relative time -- **๐Ÿ“ File Size Display** - Show file sizes in repository browsers -- **๐ŸŽ›๏ธ Customizable Settings** - Fine-tune all features through popup interface - -### ๐Ÿ”ง **Technical Features** -- **๐Ÿš€ Modern Architecture** - Modular enhancer system with BaseEnhancer class -- **๐ŸŽฏ Performance Optimized** - Efficient DOM manipulation and event handling -- **๐ŸŒ™ Dark/Light Theme Support** - Automatic theme detection and adaptation -- **๐Ÿ“ฑ Responsive Design** - Works seamlessly across different screen sizes - -## ๐Ÿ› ๏ธ Installation - -### Method 1: Chrome Web Store (Coming Soon) -*Extension will be available on Chrome Web Store soon!* - -### Method 2: Developer Mode -1. **Clone the repository:** - ```bash - git clone https://github.com/adomorn/Github-Enhancer.git - cd Github-Enhancer - ``` - -2. **Load in Chrome:** - - Open Chrome and navigate to `chrome://extensions/` - - Enable "Developer mode" (top right toggle) - - Click "Load unpacked" and select the project folder - -3. **Enjoy!** ๐ŸŽ‰ - - Navigate to any GitHub page - - Extension will automatically enhance your experience - -## ๐ŸŽฎ Usage - -### ๐ŸŒŸ **Star Button Magic** -- **Hover** over any star button to see magical glow effects -- **Click** to trigger explosion animations with floating sparkles -- Position stays fixed while maintaining beautiful visual feedback - -### ๐Ÿ”ข **Binary Cursor Trail** -- Move your mouse to see subtle 1/0 particles following your cursor -- Each particle has random rotation (-45ยฐ to +45ยฐ) for dynamic feel -- Four different styles: zero (blue), one (green), matrix (green), cyber (pink) - -### ๐ŸŒŒ **Background Animations** -- Enjoy smooth floating orbs that drift across the background -- Geometric particles (squares, triangles, diamonds) with rotation effects -- All animations are performance-optimized and accessibility-friendly - -### โš™๏ธ **Settings Panel** -Click the extension icon to access: -- **Theme Enhancements** - Toggle modern animations and effects -- **Contributor Cards** - Customize contributor information display -- **Date/Time Format** - Choose your preferred time display format -- **File Size Display** - Show/hide file sizes in repository browsers - -## ๐ŸŽจ **Visual Showcase** +# GitHub Enhancer -``` -๐ŸŒŸ Star Button Effects: โœจ Magical glow + floating sparkles -๐Ÿ”ข Cursor Trail: 1 0 1 0 (rotating binary particles) -๐ŸŒŒ Background: Floating orbs + geometric shapes -๐Ÿ’ซ 3D Effects: Glassmorphism + perspective transforms -โšก Micro-interactions: Enhanced hover states everywhere -``` +Private tools for code investigation and PR review on GitHub. -## ๐Ÿ”ง **Configuration Options** +Save repositories, issues, pull requests, discussions, commits, and code pages with a note about why they matter. Find them again from any GitHub page. GitHub Enhancer works without a token, an account, or a backend. -| Setting | Description | Default | -|---------|-------------|---------| -| `enableThemeEnhancements` | Enable/disable all theme effects | `true` | -| `enableEnhancedContributors` | Show enhanced contributor cards | `true` | -| `enableDateTimeEnhancement` | Display full timestamps | `true` | -| `enableFileSizeDisplay` | Show file sizes | `true` | -| `contributorCardWidth` | Width of contributor cards | `300px` | -| `maxContributorCards` | Maximum cards to display | `10` | -| `locale` | Date/time formatting locale | `en-US` | +## What's inside -## ๐Ÿ—๏ธ **Architecture** +- **Code basket.** Open a code file, choose a line range and collect an excerpt with path, language, source link and a note. Combine excerpts from several files and copy or download Markdown. Full commit permalinks are distinguished from mutable branch/tag links. +- **Private PR review.** On Files changed, filter loaded files and group by folder or type. Navigate with j/k or arrow keys in the file list, jump to a diff, collapse diff bodies, keep file notes and resume the last file. Local marks are separate from GitHub Viewed and submitted reviews. A known revision change requires reconfirmation; unknown revisions are always labeled unverified. +- **Workspaces.** Group saved repositories, PRs, issues, comment links and code excerpts around one investigation. Add workspace notes, export the collection as Markdown (optionally including saved private file notes from linked PRs), and reopen up to ten page links at once. -``` -src/ -โ”œโ”€โ”€ ๐ŸŽฏ content/main.js # Main content script -โ”œโ”€โ”€ ๐Ÿ”ง enhancers/ # Modular enhancement system -โ”‚ โ”œโ”€โ”€ base-enhancer.js # Base class for all enhancers -โ”‚ โ”œโ”€โ”€ theme-enhancer.js # Visual effects and animations -โ”‚ โ”œโ”€โ”€ contributor-enhancer.js # Contributor card enhancements -โ”‚ โ”œโ”€โ”€ date-enhancer.js # Date/time improvements -โ”‚ โ””โ”€โ”€ file-size-enhancer.js # File size display -โ”œโ”€โ”€ ๐ŸŽจ styles/content.css # Global styles -โ”œโ”€โ”€ ๐Ÿ”ง utils/ # Utility functions -โ”œโ”€โ”€ ๐ŸŽ›๏ธ popup/ # Extension popup interface -โ””โ”€โ”€ ๐Ÿš€ background/ # Service worker -``` +- **Conversation navigator.** Search the loaded comments of an issue, PR or discussion by text/author, filter by author or saved status, jump to the original, and bookmark important comment permalinks for a workspace. Refresh after loading more comments. +- **Reply drafts and templates.** Prepare a local Markdown draft in Write, reuse your own templates, and copy when ready. Thread drafts recover within the current browser session. Applying a template is explicit; the extension never posts to GitHub. +- **Saved pages with private notes.** Search titles, repositories, and notes. Filter by page type. Remove a page with an Undo action. +- **A workbench on GitHub.** The compact `g+ Enhancer` button opens an overlay. Notes live in an extension-origin frame, isolated from GitHub's page scripts. The toolbar popup opens the same workspace. +- **Contextual actions.** Copy a page URL, Markdown link, or clone command. Jump to a repository's code, issues, pull requests, and releases. +- **Command search.** Press **Alt + Shift + K** on GitHub or choose Commands. Search commands, workspace notes, collected code and private PR notes. Use arrows and Enter; Escape returns focus. GitHub's own shortcuts stay available. Disable the shortcut in Settings if needed. +- **Reading preferences.** Exact local or UTC dates alongside GitHub's native timestamps, wider repository content, and an optional focus mode for the repository overview sidebar. Settings apply live. +- **Portable backups.** Export pages, code excerpts, workspaces, review notes/marks, reply templates and settings as version 2 JSON, or merge a version 1 or 2 backup. More recent local notes take priority. Data stays in this browser unless you export it. +- **Light and dark.** The in-page workbench follows GitHub; extension pages follow your device. You can choose a fixed appearance. -## ๐Ÿค **Contributing** +## Install locally -We welcome contributions! Here's how to get started: +1. Clone this repository, or unzip a release package into a permanent folder. +2. Open `chrome://extensions` in Chrome and enable **Developer mode**. +3. Choose **Load unpacked** and select the folder containing `manifest.json`. +4. Reload a GitHub tab. Click **g+ Enhancer** in the bottom-right corner. -1. **Fork** the repository -2. **Create** a feature branch: `git checkout -b feature/amazing-feature` -3. **Commit** your changes: `git commit -m 'โœจ Add amazing feature'` -4. **Push** to branch: `git push origin feature/amazing-feature` -5. **Open** a Pull Request +No build or dependency installation is needed to use the extension. After changing code, click **Reload** on the extension's card and reload GitHub. Minimum Chrome version: 120. Download packaged versions from [GitHub Releases](https://github.com/adomorn/Github-Enhancer/releases). Chrome Web Store submission is being prepared; this repository does not imply store approval or availability of version 3. -### ๐Ÿ› **Bug Reports** -Found a bug? Please open an issue with: -- Browser version and OS -- Steps to reproduce -- Expected vs actual behavior -- Screenshots if applicable +## A useful first minute -### ๐Ÿ’ก **Feature Requests** -Have an idea? We'd love to hear it! Open an issue with: -- Clear description of the feature -- Use case and benefits -- Any mockups or examples +Open a code file and choose **Code basket**. Select a line range, add a note, then save the excerpt. Visit another file to collect more evidence. In **Workspaces**, create an investigation and add the current page plus saved excerpts. Copy Markdown when you want to share your findings. -## ๐Ÿ“œ **License** +On a PR's Files changed page, **Tools** shows the loaded diff files. Add private notes, jump between files and mark progress locally. **Refresh page data** picks up more content after GitHub loads it. These tools never submit a GitHub review or comment. -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +Notes save explicitly. Saved-page notes, workspace names/notes, code-excerpt annotations/ranges PR file-note drafts, reply drafts and template edits recover during the same browser session after reopening the popup or panel. Save explicitly to keep them across browser restarts. Code text itself is collected only when saving an excerpt. Settings save immediately. No browsing history is collected automatically. -## ๐Ÿ™ **Acknowledgments** +## Privacy and permissions -- GitHub for providing an amazing platform to enhance -- The open-source community for inspiration and feedback -- All contributors who help make this extension better +Only `storage` and `activeTab` permissions are requested. A declarative content script runs on `https://github.com/*` to display the launcher and optional reading tools. The worker makes no network requests. No PAT, GitHub API token, analytics, remote code, external fonts, or sign-in flow is used. Read [PRIVACY.md](PRIVACY.md). -## ๐Ÿ“Š **Analytics** +Backups contain note text and URLs, including any private repository names you explicitly saved. Keep exported files somewhere you trust. Uninstalling the extension removes its local data; export a backup first if you want to retain it. -![Alt](https://repobeats.axiom.co/api/embed/f18cf543e0af776cea448efd11e221af3490e2d4.svg "Repobeats analytics image") +## Development ---- +```sh +npm ci --ignore-scripts +npm test +npm run check +npm run package +``` + +Node 22+ is needed for development checks. Runtime code has no npm dependencies; jsdom is a development-only DOM test dependency. Packaging produces `dist/github-enhancer-3.0.0.zip` from an allowlist of extension assets. + +```text +src/shared/ URL/data rules, extension UI and messaging client +src/background/ Serialized local persistence and worker message boundary +src/content/ One page lifecycle and reversible reading enhancements +src/panel/ Isolated extension-origin workbench +src/popup/ Browser toolbar workbench +src/options/ Settings and backups +tests/ Model, persistence, DOM, UI and settings regression tests +``` -
+## Scope and limitations -**โญ Star this repo if you find it useful! โญ** +- GitHub.com only; GitHub Enterprise domains are not currently supported. +- Up to 500 saved pages, 100 excerpts (20,000 characters each), 40 workspaces 50 PR review records and 40 reply templates. Notes allow 10,000 characters. +- Page tools use loaded GitHub content only. The file adapter reads at most 300,000 code characters; the review navigator lists at most 200 loaded files. Conversation snapshots hold at most 200 comments, 10,000 characters per comment and 300,000 characters in total. Hidden, paginated or unloaded content is not represented as a complete result. +- A full commit in the diff URL is a verified revision; aggregate PR pages may not expose one. In that case local marks remain explicitly unverified. +- Code lines from branch/tag URLs can change later. Use GitHub's permalink before collecting when an immutable reference matters. +- Reading utilities depend on GitHub markup. They make narrow, reversible changes; GitHub layout updates may require selector adjustments. +- Workspaces are device-local and do not sync between Chrome profiles or computers. +- The older animated theme, expanded contributor cards, and API-based file sizes were retired. They added background work, fragile page replacements, and API limits; this version focuses on preserving personal context. -Made with โค๏ธ for the GitHub community +See [CHANGELOG.md](CHANGELOG.md), [the research](docs/research/competitors.md), and [the technical audit](docs/research/technical-audit.md). -
+MIT licensed. Originally built by Arda Terekeci. diff --git a/assets/icons/128.png b/assets/icons/128.png index d695665..507fad5 100644 Binary files a/assets/icons/128.png and b/assets/icons/128.png differ diff --git a/assets/icons/16.png b/assets/icons/16.png index f8c224a..aeb1306 100644 Binary files a/assets/icons/16.png and b/assets/icons/16.png differ diff --git a/assets/icons/32.png b/assets/icons/32.png index c3e0ade..570a573 100644 Binary files a/assets/icons/32.png and b/assets/icons/32.png differ diff --git a/assets/icons/48.png b/assets/icons/48.png index 26d0334..b3ff2d4 100644 Binary files a/assets/icons/48.png and b/assets/icons/48.png differ diff --git a/assets/icons/icon.svg b/assets/icons/icon.svg index 4365f75..612ce0d 100644 --- a/assets/icons/icon.svg +++ b/assets/icons/icon.svg @@ -1,5 +1,7 @@ - - GD - + + + + + diff --git a/docs/research/competitors.md b/docs/research/competitors.md new file mode 100644 index 0000000..bc5e21d --- /dev/null +++ b/docs/research/competitors.md @@ -0,0 +1,58 @@ +# GitHub Enhancer v2: competitor research + +Research date: 2026-09-28. Sources are project maintainers' repositories, publisher-owned store listings, and GitHub documentation. Features below are documented claims, not hands-on validation. No adoption estimates are used. Product opportunities are hypotheses inferred from this comparison, not evidence of unmet market demand. + +## Recommendation + +Build a small personal workspace for daily GitHub users: save work, retain private context, and return to the right page quickly. The central promise should be **โ€œKeep your GitHub work and the reason you saved it together, on this device.โ€** Make the core useful without a token, account, background polling, or external service. + +This is a more coherent direction than competing on the number of interface tweaks or ornamental effects. Existing GitHub Enhancer foregrounds cursor particles, star animations, backgrounds, and hover effects; its useful supporting features are full timestamps and repository information. [Existing README](https://github.com/adomorn/Github-Enhancer) + +## Competitive comparison + +| Product | Documented strength | Access/model | Implication for v2 | +| --- | --- | --- | --- | +| Refined GitHub | Broad interface improvements spanning comments, files, PRs, notifications, and shortcuts. Most JavaScript features can be disabled. | Open-source, opinionated collection. Most functionality uses page DOM; some features require an API token. | Do not recreate a large miscellaneous tweak collection. Choose a few reliable utilities that support the main workflow. [README](https://github.com/refined-github/refined-github), [security documentation](https://github.com/refined-github/refined-github/wiki/Security) | +| Octotree | Repository tree and search; bookmarks for repositories, issues, PRs, and files. Pro adds review navigation, unlimited bookmarks, and other customization. | Proprietary free/Pro product. Publisher says tokens are needed for private repositories or API rate limits. Its public repository contains an older limited version. | A file tree or plain bookmark list is an established category. Context attached to saved work and a token-free core offer a clearer angle. [Store listing](https://chromewebstore.google.com/detail/octotree-github-code-tree/bkhaagjahfmjljalopjnoealnfndnagc), [repository notice](https://github.com/ovity/octotree) | +| Gitako | Free repository/PR tree, instant file search, keyboard navigation, snippet copying, submodules, code folding, and support for other Git hosts. | Open-source. Publisher says private repository access and API limits can require a token. | Avoid rebuilding tree navigation. Respect coexistence with another extension's sidebar and shortcuts. [README](https://github.com/EnixCoda/Gitako), [store listing](https://chromewebstore.google.com/detail/gitako-github-file-tree/giljefjcheohhamkjphiebfjnlphnokk) | +| Enhanced GitHub | Repository/file sizes, file download actions, clipboard utilities. | Open-source. Documentation requires a token for private repositories and describes API quota consumption. | File size enrichment is occupied territory and brings API dependence. Include simple copy actions only where they reduce a concrete repeated task. [README](https://github.com/softvar/enhanced-github) | +| PullMate | PR sidebar, viewed-file progress, filters, bot hiding, pending-review reminder, and checklists. Pro includes private inline notes and Markdown export. | Free/Pro extension; listing advertises in-app purchases. No token conclusion drawn from the listing. | Private notes and review progress are not novel by themselves. Keep v2's scope across repository, issue, and PR pages rather than becoming a second PR review UI. [Publisher listing](https://chromewebstore.google.com/detail/pullmate/omkmhaoladfdhnmdghjlakmlbfjgpjfg) | + +Exact Octotree pricing is omitted: its pricing URL returned only a loading shell on direct retrieval, although search indexing showed plan information. Pricing is not necessary to the scope decision. + +## Native GitHub overlap + +GitHub documents its own command palette for navigation, search, and contextual actions, including copying the current PR branch. It is a feature preview with configurable keyboard shortcuts and uses Ctrl/Cmd+K by default. A v2 launcher should focus on extension-owned saved work and actions, use a distinct configurable shortcut, and avoid a โ€œGitHub finally has a command paletteโ€ claim. [GitHub command palette](https://docs.github.com/en/get-started/accessibility/github-command-palette) + +GitHub's issues dashboard supports up to 25 saved views and can include PRs using `is:pr`. Generic saved searches should therefore be a convenience link to native functionality, not the main differentiator. [GitHub saved views](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/viewing-all-of-your-issues-and-pull-requests) + +## Workflows worth testing + +These are candidate opportunities suggested by the reviewed scope, not claims that no competing product supports them: + +1. **Resume interrupted work:** save a PR with โ€œcheck retry behavior after tests finish,โ€ then find it from the popup tomorrow. A plain bookmark preserves location; the note preserves intent. +2. **Keep private repository context without API setup:** attach a local note to a page the user can already view. Store only the title, canonical URL, and user-entered text needed for the feature. +3. **Move between investigation and communication:** copy an issue reference, Markdown link, repository clone command, or file permalink without manually reformatting it. Derive actions from visible page data or validated URLs. +4. **Read comfortably while retaining GitHub familiarity:** opt into exact timestamps or wider content, with immediate reversible toggles. This should support the workspace, not introduce a separate theme system. + +## Coherent launch scope + +| Priority | Feature | Useful completion criteria | +| --- | --- | --- | +| P0 | Save repositories, issues, and PRs | One action adds/removes the current page; popup searches by repository, title, and note; duplicate saves collapse to one item. | +| P0 | Private context notes | Autosave with a visible saved/error state; notes survive reload/navigation; editing never submits a GitHub comment. | +| P0 | Useful sharing/copy actions | Copy URL, Markdown link, and contextual repository/issue reference; report copy success or failure honestly. | +| P0 | Local data controls | Explicit local-device wording, JSON export/import with validation, per-item removal, and clear-all confirmation. No claim of encrypted or synchronized storage. | +| P1 | Extension workspace launcher | Search saved items and extension commands by keyboard; do not shadow GitHub's default palette shortcut. | +| P1 | Reading utilities | Exact timestamps and optional content width; preserve GitHub themes, keyboard access, reduced-motion preferences, and easy disable controls. | + +Defer full repository trees, API-based contributor enrichment/file sizes, AI summaries, notifications polling, diff annotation systems, time tracking, and decorative particles. Each would introduce a competing product direction or infrastructure cost before the central habit is proven. + +## Product and validation guardrails + +- A saved URL is a destination, not a live status feed. Do not show stale PR state as current without refreshing it from a reliable source. +- Canonical identity must preserve host, owner, repository, item type, and number; branch/file links must not be corrupted by naive path parsing. +- Local notes can contain confidential work context. Keep them in extension-local storage by default; export is a deliberate user action, and local means this browser profile rather than automatic cross-device sync. +- Prefer inline entry points that blend with GitHub. A popup is sufficient for the first workspace; another permanent sidebar is unnecessary for launch. +- Validate with a handful of daily GitHub users performing a real interruption-and-resume task. Measure whether they can retrieve saved intent and whether they voluntarily return over several days; avoid assuming feature count implies retention. +- Test GitHub's client-side navigation, two open tabs, storage failures, keyboard-only flows, narrow layouts, and coexistence with Refined GitHub/Gitako before claiming reliability. diff --git a/docs/research/technical-audit.md b/docs/research/technical-audit.md new file mode 100644 index 0000000..05010ac --- /dev/null +++ b/docs/research/technical-audit.md @@ -0,0 +1,71 @@ +# Technical audit and proposed foundation + +Audit date: 2026-09-28. Scope: the freshly cloned version 2.0.0, its manifest, content runtime, enhancement modules, utilities, popup, and CI. Findings below distinguish source-level evidence from browser-dependent risks. No browser was controlled and no production code was changed for this audit. + +## Recommendation + +Retain the GitHub Enhancer identity and the practical idea of readable timestamps. Replace the active content runtime rather than adding another feature to its current lifecycle. Build a local workspace for saved repositories and context notes, a keyboard-accessible action palette, safe copy/navigation actions, and reversible reading modes. These features can work with public and private pages the user already has open without requesting a personal access token or scraping extra account data. + +The existing code is predominantly decorative and has overlapping implementations. The four concrete module files alone contain about 3,900 lines; the dated badge module is over 1,200 lines. A simpler runtime will make the valuable behaviors easier to verify and maintain. + +## Defensible findings + +| Severity | Finding and source | Consequence | +| --- | --- | --- | +| High | `base-enhancer.js:70` calls `startObserving()` before `isInitialized` becomes true at line 74, while `shouldObserve()` at line 188 requires it to be true. | Normal enhancer observers never start during initialization. Dynamically loaded file rows and contributor regions are missed. A Node VM harness confirmed `{initialized:true, observations:0, observerCount:0}`. | +| High | `contributor-enhancer.js:846-868` extracts profile strings through `textContent`, but `enhanceCard()` at lines 881-908 interpolates them into `details.innerHTML`. | User-supplied profile text containing markup is reparsed as HTML. This is a real HTML injection sink. Do not assert privileged JavaScript execution without a browser/CSP reproduction; the safe fix is still to insert text nodes and separate `
` nodes. | +| High | `main.js:198-210` patches `history.pushState` and `replaceState` from the default isolated content-script world. | This cannot be relied upon to intercept GitHub's page-world history calls. Chrome documents isolated JavaScript environments. This is an architectural risk supported by the execution model, not a live SPA reproduction. | +| High | `date-enhancer.js:36-60` installs anonymous global listeners and an untracked body observer; `cleanup()` at 1212 does not remove them. Its timeouts also remain live. | Navigation and settings changes leave old instances active. A disabled timestamp feature can still call `enhance()` via these callbacks because `enhance()` itself does not gate on enabled state. | +| High | `theme-enhancer.js:873`, 936, 1029, 1054, 1066 add global event listeners; its body observer at 1117 is not retained. `cleanup()` at 1174 does not remove them or call `super.cleanup()`. | Cursor particles, click effects and DOM rescans survive cleanup and multiply across recreated instances. The stale scroll observer callback can later call `this.animationObserver.observe` after cleanup sets it to null. | +| High | `main.js:273-277` handles toggles for dates, contributors and sizes but omits `enableThemeEnhancements`. `BaseEnhancer.disable()` only disconnects observers. | The theme toggle does not apply immediately. Other toggles leave already modified DOM visible. Settings appear saved while the page continues showing the feature. | +| High | `date-enhancer.js:1050` replaces GitHub's original `relative-time` element. Cleanup at 1218 depends on `data-original-date`, which the active creation path never sets. | Original nodes/attributes and custom-element behavior are lost; cleanup cannot restore them. Locale changes also do not rerender the already replaced timestamps. | +| Medium | `file-size-enhancer.js:194` keys cache by owner/repo/path but not branch or commit. Line 169 assumes refs have no slash. `api-utils.js:265-275` falls back to `main` rather than parsing the shown route/ref. | Ref switches can show another ref's size. Branches like `feature/ui` are parsed as if `ui` were part of the file path. | +| Medium | `file-size-enhancer.js:239-242` and 274-277 convert 404 into zero. Directory summation at 264-272 counts direct files only but the UI calls it โ€œDirectory size.โ€ | Private/inaccessible/missing resources are misrepresented as empty; nested folders are excluded without disclosure. A Node VM harness confirmed a mocked 404 returns `0`. | +| Medium | Each visible file uses an individual contents request (`file-size-enhancer.js:228`); API calls are serialized with a delay (`api-utils.js:73-94`) and can await a rate-limit reset. Main awaits enhancers sequentially (`main.js:136-157`). | A file listing can create many requests, delays and rate-limit stalls; initialization of subsequent modules waits behind this work. A token-free redesign should not promise inferred API data. | +| Medium | All generic storage and cached API values use `chrome.storage.sync` (`storage.js:55-107`, 273-282). There is no enforced cache entry bound. | Cache churn consumes the same constrained sync quota as preferences and synchronizes data that should be disposable. Sync is approximately 100 KB total and 8 KB/item; local storage is the appropriate basis for a local workspace. | +| Medium | `contributor-enhancer.js:949-950` hides the original list; cleanup at 991 only resets flags/cache/observers. | Disabling/reinitializing the feature does not remove cards or restore the native contributor list. Its hovercard fetches also have no cancellation/timeout and add requests for every selected contributor. | +| Medium | `main.js:283-286` calls `initializeEnhancers()` for all enabled modules when any missing one becomes enabled; existing instances are overwritten in the map without cleanup. `handleNavigation()` has uncancelled 100 ms timers. | Settings and rapid navigation can overlap initialization and orphan existing instances. | +| Medium | Timestamps older than a week get opacity `0.45` (`date-enhancer.js:350-359`), tiny fixed-size uppercase badges (`395-425`), and clickable `div` controls without keyboard semantics. The shown format hardcodes `en-US` (`688` onward). | The feature makes older information harder to read, ignores the chosen locale for its primary display, truncates dates and excludes keyboard users from the detail action. | +| Low | `main.js:96` treats every two-segment path as a repository. `api-utils.js:246` uses any two path segments as owner/repo. | Routes such as `/settings/profile` and `/orgs/example` can acquire invalid repository context; explicit reserved-route handling and visible repository metadata are needed. | +| Low | Event names in `base-enhancer.js:18-20` disagree with `constants.js:88-92`; default settings are copied into several files. | Error/completion wiring is inconsistent and settings drift is easy. Prefer one schema and direct typed/validated messages. | + +Browser/platform claims are grounded in [Chrome's content-script execution model](https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts) and [Chrome's storage documentation](https://developer.chrome.com/docs/extensions/reference/api/storage). Source findings refer to the original checkout and line numbers can change after implementation. + +## What to keep, rewrite, and retire + +- **Keep as a product feature:** readable local/UTC timestamps with a precise ISO tooltip and retained relative context. Reimplement as a small reversible enhancement that preserves GitHub's native element and attributes. +- **Keep as implementation ideas:** explicit feature preferences, stable extension-prefixed markers, debouncing, small pure formatting helpers, Manifest V3 packaging, local CSS assets. +- **Replace:** inheritance-based enhancer lifecycle, duplicated settings, popup that only exposes toggles, broad page CSS, mutation/history workarounds, custom timestamp badges. +- **Remove from the active bundle:** cursor trails, full-page decorative orbs, star explosions, hovercard enrichment and per-file API size fetching. Keep upstream history in Git rather than retaining dead production modules. +- **Do not carry forward:** token storage or API host permission for a core product that needs neither. The source references an auth token but provides no coherent token management UI. + +## Proposed architecture + +Use plain JavaScript modules with a small build/bundle step if it improves isolation and testing, or a few deliberately ordered script files if zero build is a requirement. Framework adoption is unnecessary for this scope. Share pure context, schema and action definitions between the popup and content UI. + +1. **Core/context** derives `{kind, owner, repo, repositoryUrl, pageUrl, title}` from a validated `URL` and GitHub metadata. Reserve non-repository route prefixes. Treat path/ref parsing as ambiguous unless page metadata supplies an exact ref; do not guess branch segments. Repository keys should be normalized for matching while display spelling is retained. +2. **Core/store** owns a versioned `chrome.storage.local` schema for settings, saved items and plain-text notes. Store one record per repo/item or serialize mutations through the service worker to avoid stale whole-store writes from different tabs. Merge defaults on read, validate imports strictly, cap field lengths, show save failures, and expose explicit export/import/delete. Listen to `chrome.storage.onChanged` for cross-context updates. โ€œSavedโ€ should mean persistence succeeded. +3. **Background** handles only installation/migration, registered keyboard commands if needed, and serialized storage mutations if selected. No polling, network enrichment, analytics or permanent in-memory state assumptions. +4. **Content/controller** is the sole lifecycle owner. It creates one stable extension host, derives page context, and schedules idempotent reconciliation. Listen to available GitHub navigation events, `popstate` and a bounded/coalesced mutation observer fallback. Compare URL/context before expensive work. Avoid overwriting page methods. Maintain one `AbortController` for listeners and cancellable scheduled work; all features have a real dispose/restore path. +5. **Content/surface** uses a Shadow DOM host for palette and workspace UI so GitHub CSS cannot break it and extension CSS cannot restyle unrelated native controls. Shadow DOM is style isolation, not a promise of secrecy from the page; do not inject unrelated saved notes into GitHub DOM. The popup is an extension page and can safely display the whole local workspace. +6. **Feature adapters** are small: timestamps; focus mode; wide mode; contextual action buttons. They receive context/settings and return cleanup. Maintain original attributes/styles in a WeakMap or use extension-owned marker classes/siblings. Never remove or clone native controls merely to restyle them. +7. **Action registry** declares id, label, keywords, availability, icon and handler. Both palette and popup call the same actions: save current repo, open notes, copy HTTPS/SSH clone URL, copy `gh repo clone owner/repo`, copy clean repo URL, open issues/PRs/releases, toggle readable dates/focus/wide. All copied values derive from validated GitHub context. Browser navigation is a normal link; clipboard runs directly on user activation and has a visible fallback on failure. + +## UX contract + +The visible promise should be โ€œyour GitHub workspace stays with you,โ€ supported by local notes and saved work. A generic command palette is a useful entry point, not a defensible uniqueness claim. The market research agent reports that GitHub already has a native Ctrl/Cmd+K palette; use a distinct, configurable shortcut and expose it in the UI. Never capture ordinary typing or overwrite native shortcuts. + +Show only a small entry point on GitHub until requested. The palette must have dialog semantics, Escape dismissal, arrow-key selection, focus trapping, focus return, a selected-item announcement, and an empty state. Saved repository filtering should work offline in the popup. Notes need a clear local-only label, explicit persisted status, predictable save timing, and a way to export the workspace. Avoid silently persisting page content or browsing history. + +Focus/wide modes should be opt-in, immediately reversible and constrained to understood page types. Hide only known supplemental regions; never issue/PR controls, discussion text, security warnings or navigation needed to exit. If a GitHub selector is missing, leave native UI alone. + +## Verification priorities for implementation + +- Unit-test URL context against repo root, blob/tree URLs, slash-containing refs, issues/PRs, encoded names, reserved GitHub routes and non-GitHub URLs. +- Unit-test schema migration, import rejection, action URL/command construction, local/UTC date formatting and preservation of line anchors in copied page links. +- Integration-test cross-tab saved-state updates, concurrent notes/settings edits, failed storage writes, corrupted records and undo/delete behavior. +- DOM-test repeated initialization, toggle on/off/on, cleanup after navigation, late-arriving timestamps, changed datetime attributes, duplicate-host prevention and restoration of the actual original nodes. +- Browser-test signed-out public pages plus any available authenticated context, repo-to-repo SPA navigation, browser back/forward, extension reload, light/dark GitHub themes, reduced motion, keyboard-only use, narrow viewport, and empty local workspace. +- Verify the active bundle makes zero feature-driven network requests and permission declarations match actual use. Inspect live console output rather than treating syntax checks or lint as runtime evidence. + +Original automated verification is sparse: there is no checked-in test suite/package manifest. CI dynamically installs a linter but does not exercise extension behavior. The current release job also depends on a version-check job that only runs for a special pull-request branch, making release execution worth revisiting separately with GitHub Actions semantics. diff --git a/manifest.json b/manifest.json index c71de04..8418f6d 100644 --- a/manifest.json +++ b/manifest.json @@ -1,49 +1,36 @@ { "manifest_version": 3, "name": "GitHub Enhancer", - "version": "2.0.0", - "description": "GitHub sayfalarฤฑnฤฑ geliลŸtiren Chrome uzantฤฑsฤฑ - dosya boyutlarฤฑ, katkฤฑda bulunanlar ve tarih bilgileri", - + "version": "3.0.0", + "minimum_chrome_version": "120", + "description": "Private PR review tools, source-linked code excerpts and workspaces for GitHub. Local storage. No tokens required.", "permissions": [ - "activeTab", "storage", - "scripting" + "activeTab" ], - - "host_permissions": [ - "https://github.com/*", - "https://api.github.com/*" - ], - "background": { "service_worker": "src/background/service-worker.js" }, - "content_scripts": [ { - "matches": ["https://github.com/*"], + "matches": [ + "https://github.com/*" + ], "js": [ - "src/utils/constants.js", - "src/utils/logger.js", - "src/utils/storage.js", - "src/utils/dom-utils.js", - "src/utils/date-utils.js", - "src/utils/api-utils.js", - "src/enhancers/base-enhancer.js", - "src/enhancers/date-enhancer.js", - "src/enhancers/contributor-enhancer.js", - "src/enhancers/file-size-enhancer.js", - "src/enhancers/theme-enhancer.js", + "src/shared/model.js", + "src/content/reading.js", + "src/content/code-tools.js", + "src/content/review-tools.js", + "src/content/conversation-tools.js", + "src/content/page-tools.js", "src/content/main.js" ], - "css": ["src/styles/content.css"], - "run_at": "document_end" + "run_at": "document_idle" } ], - "action": { "default_popup": "src/popup/popup.html", - "default_title": "GitHub Enhancer", + "default_title": "GitHub Enhancer \u2014 your saved work", "default_icon": { "16": "assets/icons/16.png", "32": "assets/icons/32.png", @@ -51,18 +38,40 @@ "128": "assets/icons/128.png" } }, - + "options_page": "src/options/options.html", "icons": { "16": "assets/icons/16.png", "32": "assets/icons/32.png", "48": "assets/icons/48.png", "128": "assets/icons/128.png" }, - "web_accessible_resources": [ { - "resources": ["src/styles/*.css"], - "matches": ["https://github.com/*"] + "resources": [ + "src/panel/panel.html", + "src/panel/panel.js", + "src/panel/panel.css", + "src/shared/model.js", + "src/shared/client.js", + "src/shared/ui.js", + "src/shared/ui.css", + "src/shared/basket.js", + "src/shared/basket.css", + "src/shared/review.js", + "src/shared/review.css", + "src/shared/workspaces.js", + "src/shared/workspaces.css", + "src/shared/conversation.js", + "src/shared/conversation.css", + "src/shared/composer.js", + "src/shared/composer.css" + ], + "matches": [ + "https://github.com/*" + ] } - ] -} \ No newline at end of file + ], + "content_security_policy": { + "extension_pages": "script-src 'self'; object-src 'none'; frame-ancestors https://github.com 'self';" + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..fb14bc4 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,548 @@ +{ + "name": "github-enhancer", + "version": "3.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "github-enhancer", + "version": "3.0.0", + "devDependencies": { + "jsdom": "^26.1.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..93d44e9 --- /dev/null +++ b/package.json @@ -0,0 +1,15 @@ +{ + "name": "github-enhancer", + "version": "3.0.0", + "private": true, + "description": "A private, token-free workbench for GitHub.", + "scripts": { + "test": "node --test tests/*.test.cjs", + "check": "node scripts/check.cjs", + "package": "node scripts/package.cjs" + }, + "devDependencies": { + "jsdom": "^26.1.0" + }, + "engines": { "node": ">=22" } +} diff --git a/scripts/check.cjs b/scripts/check.cjs new file mode 100644 index 0000000..c520061 --- /dev/null +++ b/scripts/check.cjs @@ -0,0 +1,10 @@ +const fs=require('node:fs'),path=require('node:path'),cp=require('node:child_process'),assert=require('node:assert/strict'); +const manifest=JSON.parse(fs.readFileSync('manifest.json','utf8')); +const walk=dir=>fs.readdirSync(dir,{withFileTypes:true}).flatMap(e=>e.isDirectory()?walk(path.join(dir,e.name)):[path.join(dir,e.name)]); +const files=walk('src'); +for(const file of files.filter(f=>f.endsWith('.js')))cp.execFileSync(process.execPath,['--check',file],{stdio:'pipe'}); +const refs=[manifest.background.service_worker,manifest.action.default_popup,manifest.options_page,...Object.values(manifest.icons),...manifest.content_scripts.flatMap(c=>[...c.js,...(c.css||[])]),...manifest.web_accessible_resources.flatMap(r=>r.resources)]; +for(const file of refs)assert.ok(fs.existsSync(file),`Missing manifest asset: ${file}`); +for(const file of files.filter(f=>f.endsWith('.html'))){const text=fs.readFileSync(file,'utf8');for(const match of text.matchAll(/(?:src|href)="([^"#]+)"/g)){if(/^(https?:|data:)/.test(match[1]))continue;assert.ok(fs.existsSync(path.resolve(path.dirname(file),match[1])),`Missing HTML asset: ${file} -> ${match[1]}`);}} +assert.deepEqual([...manifest.permissions].sort(),['activeTab','storage']);assert.equal(manifest.host_permissions,undefined);assert.equal(manifest.version,JSON.parse(fs.readFileSync('package.json','utf8')).version); +console.log(`Checked ${files.filter(f=>f.endsWith('.js')).length} JavaScript files, manifest paths, HTML assets, version and minimal permissions.`); diff --git a/scripts/package.cjs b/scripts/package.cjs new file mode 100644 index 0000000..a4e56e1 --- /dev/null +++ b/scripts/package.cjs @@ -0,0 +1,7 @@ +const fs=require('node:fs'),path=require('node:path'),cp=require('node:child_process'); +cp.execFileSync(process.execPath,['scripts/check.cjs'],{stdio:'inherit'}); +const version=JSON.parse(fs.readFileSync('manifest.json','utf8')).version; +const walk=dir=>fs.readdirSync(dir,{withFileTypes:true}).flatMap(e=>e.isDirectory()?walk(path.join(dir,e.name)):[path.join(dir,e.name)]); +const files=['manifest.json',...walk('src'),...walk('assets/icons')].filter(f=>!path.basename(f).startsWith('.')).sort(); +fs.mkdirSync('dist',{recursive:true});const out=`dist/github-enhancer-${version}.zip`;if(fs.existsSync(out))fs.unlinkSync(out); +cp.execFileSync('zip',['-q','-X',out,...files]);console.log(`Packaged ${files.length} files โ†’ ${out} (${fs.statSync(out).size} bytes)`); diff --git a/src/background/service-worker.js b/src/background/service-worker.js index 09fc17e..6a7b535 100644 --- a/src/background/service-worker.js +++ b/src/background/service-worker.js @@ -1,157 +1,18 @@ -/** - * GitHub Enhancer Service Worker - * Simplified version for Chrome Extension - */ +/* No network access: this worker only owns local workspace mutations. */ +importScripts('../shared/model.js','store.js'); -console.log('GitHub Enhancer service worker starting...'); +const workspaceStore = GHE.createStore(chrome.storage.local,chrome.storage.sync); +const allowedMessages = new Set(GHE.MESSAGE_TYPES); -// Default settings -const DEFAULT_SETTINGS = { - enhanceContributors: true, - enhanceDateTimes: true, - enhanceFileSizes: true, - enableThemeEnhancements: true, - showCommitInfo: true, - showTeamInfo: true, - showOrgInfo: true, - cardWidth: 250, - maxCards: 10, - locale: 'en-US', - theme: 'auto', - animationsEnabled: true, - debugMode: false -}; - -/** - * Extension installation/update handler - */ -chrome.runtime.onInstalled.addListener(async (details) => { - console.log('GitHub Enhancer installed:', details.reason); - - try { - if (details.reason === 'install') { - // First time installation - await chrome.storage.sync.set({ - github_enhancer_settings: DEFAULT_SETTINGS - }); - console.log('Default settings initialized'); - } - } catch (error) { - console.error('Installation error:', error); - } +chrome.runtime.onInstalled.addListener(() => { + workspaceStore.dispatch({type:'GET_STATE'}).catch(error=>console.error('Workspace initialization failed:',error.message)); }); -/** - * Message handler - */ -chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { - console.log('Service worker received message:', message.type); - - switch (message.type) { - case 'GET_SETTINGS': - handleGetSettings(sendResponse); - return true; // Keep message channel open - - case 'SAVE_SETTINGS': - handleSaveSettings(message.payload, sendResponse); - return true; - - case 'GET_STORAGE_USAGE': - handleGetStorageUsage(sendResponse); - return true; - - case 'CLEAR_CACHE': - handleClearCache(sendResponse); - return true; - - case 'LOG_ERROR': - console.error('Content script error:', message.payload); - break; - - default: - console.warn('Unknown message type:', message.type); - } +chrome.runtime.onMessage.addListener((message,sender,sendResponse) => { + if (sender.id !== chrome.runtime.id || !allowedMessages.has(message?.type)) return false; + workspaceStore.dispatch(message).then( + state=>sendResponse({ok:true,state}), + error=>sendResponse({ok:false,error:error.message || 'The workspace could not be saved.'}) + ); + return true; }); - -/** - * Get settings from storage - */ -async function handleGetSettings(sendResponse) { - try { - const result = await chrome.storage.sync.get('github_enhancer_settings'); - const settings = result.github_enhancer_settings || DEFAULT_SETTINGS; - sendResponse({ success: true, settings }); - } catch (error) { - console.error('Failed to get settings:', error); - sendResponse({ success: false, error: error.message }); - } -} - -/** - * Save settings to storage - */ -async function handleSaveSettings(settings, sendResponse) { - try { - await chrome.storage.sync.set({ - github_enhancer_settings: settings - }); - - // Notify content scripts - try { - const tabs = await chrome.tabs.query({ url: 'https://github.com/*' }); - for (const tab of tabs) { - try { - await chrome.tabs.sendMessage(tab.id, { - type: 'SETTINGS_UPDATED', - payload: settings - }); - } catch (e) { - // Tab might not have content script, ignore - } - } - } catch (e) { - // Ignore tab messaging errors - } - - sendResponse({ success: true }); - } catch (error) { - console.error('Failed to save settings:', error); - sendResponse({ success: false, error: error.message }); - } -} - -/** - * Get storage usage - */ -async function handleGetStorageUsage(sendResponse) { - try { - const bytesInUse = await chrome.storage.sync.getBytesInUse(); - sendResponse({ success: true, bytesInUse }); - } catch (error) { - console.error('Failed to get storage usage:', error); - sendResponse({ success: false, error: error.message }); - } -} - -/** - * Clear cache - */ -async function handleClearCache(sendResponse) { - try { - const allData = await chrome.storage.sync.get(); - const cacheKeys = Object.keys(allData).filter(key => - key.startsWith('github_enhancer_cache_') - ); - - if (cacheKeys.length > 0) { - await chrome.storage.sync.remove(cacheKeys); - } - - sendResponse({ success: true, clearedCount: cacheKeys.length }); - } catch (error) { - console.error('Failed to clear cache:', error); - sendResponse({ success: false, error: error.message }); - } -} - -console.log('GitHub Enhancer service worker loaded successfully'); \ No newline at end of file diff --git a/src/background/store.js b/src/background/store.js new file mode 100644 index 0000000..b0aa376 --- /dev/null +++ b/src/background/store.js @@ -0,0 +1,188 @@ +/* Every operation is serialized by the worker; state is read from durable storage. */ +(() => { + 'use strict'; + const G = globalThis.GHE; + const {LIMITS,parseContext,normalizeSettings,validateSettingsPatch,validateItem,validateImport,validateSnippet,validateWorkspace,validateReview,validateTemplate,validateId,validateRevision,validatePath,canonicalPrUrl} = G; + const STORAGE = Object.freeze({version:'ghe:schemaVersion',settings:'ghe:settings',itemPrefix:'ghe:item:',snippetPrefix:'ghe:snippet:',workspacePrefix:'ghe:workspace:',reviewPrefix:'ghe:review:',templatePrefix:'ghe:template:'}); + const COLLECTIONS = { + items:{prefix:STORAGE.itemPrefix,id:'url',validate:validateItem}, + snippets:{prefix:STORAGE.snippetPrefix,id:'id',validate:validateSnippet}, + workspaces:{prefix:STORAGE.workspacePrefix,id:'id',validate:validateWorkspace}, + reviews:{prefix:STORAGE.reviewPrefix,id:'prUrl',validate:validateReview}, + templates:{prefix:STORAGE.templatePrefix,id:'id',validate:validateTemplate} + }; + const MESSAGE_TYPES = Object.freeze(['GET_STATE','SAVE_ITEM','UPDATE_ITEM','REMOVE_ITEM','RESTORE_ITEM','SET_SETTINGS','IMPORT_ITEMS','SAVE_SNIPPET','UPDATE_SNIPPET','REMOVE_SNIPPET','RESTORE_SNIPPET','CREATE_WORKSPACE','UPDATE_WORKSPACE','LINK_WORKSPACE_ITEM','UNLINK_WORKSPACE_ITEM','LINK_WORKSPACE_SNIPPET','UNLINK_WORKSPACE_SNIPPET','REMOVE_WORKSPACE','RESTORE_WORKSPACE','UPDATE_REVIEW_FILE','SET_REVIEW_LAST_FILE','REMOVE_REVIEW','RESTORE_REVIEW','CREATE_TEMPLATE','UPDATE_TEMPLATE','REMOVE_TEMPLATE','RESTORE_TEMPLATE']); + const keyFor = (collection,id) => COLLECTIONS[collection].prefix + encodeURIComponent(id); + const timestamp = record => Math.max(Date.now(),(record?.updatedAt ?? -1)+1); + const sorted = records => records.sort((a,b)=>b.updatedAt-a.updatedAt); + + function createStore(localArea, syncArea) { + let queue = Promise.resolve(); + + async function readState() { + let data = await localArea.get(null); + if (data[STORAGE.version] !== 2) { + if(data[STORAGE.version]!==undefined && data[STORAGE.version]!==1)throw new Error('This workspace was saved by an unsupported extension version.'); + const legacy = data[STORAGE.version]===undefined && syncArea ? (await syncArea.get('github_enhancer_settings')).github_enhancer_settings : undefined; + const settings = normalizeSettings(data[STORAGE.settings],legacy); + await localArea.set({[STORAGE.settings]:settings,[STORAGE.version]:2}); + data = {...data,[STORAGE.settings]:settings,[STORAGE.version]:2}; + } + const state={settings:normalizeSettings(data[STORAGE.settings]),items:[],snippets:[],workspaces:[],reviews:[],templates:[]}; + for (const [key,value] of Object.entries(data)) { + for(const [name,collection] of Object.entries(COLLECTIONS)) { + if(!key.startsWith(collection.prefix))continue; + try { + const record=collection.validate(value); + if(key===keyFor(name,record[collection.id]))state[name].push(record); + } catch { /* Damaged records must not prevent access to the rest of the workspace. */ } + break; + } + } + for(const name of Object.keys(COLLECTIONS))sorted(state[name]); + return state; + } + + function contextFrom(input) { + const context = parseContext(input?.url,input?.title); + if (!context) throw new Error('Choose a supported GitHub repository or work item.'); + return context; + } + function noteFrom(note) { + if (typeof note !== 'string' || note.length > LIMITS.note) throw new Error(`Notes must be at most ${LIMITS.note} characters.`); + return note; + } + function assertCapacity(name,records) { + if (records.length > LIMITS[name]) throw new Error(`Your workspace can contain at most ${LIMITS[name]} ${name}.`); + } + function find(state,name,id) { + const record=state[name].find(record=>record[COLLECTIONS[name].id]===id); + if(!record)throw new Error('This saved record was not found.'); + return record; + } + function patchFrom(input,fields) { + if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(key=>!fields.includes(key)))throw new Error('Invalid record patch field.'); + return {...input}; + } + async function write(state,name,value) { + const record=COLLECTIONS[name].validate(value),id=record[COLLECTIONS[name].id]; + if(!state[name].some(item=>item[COLLECTIONS[name].id]===id))assertCapacity(name,[...state[name],record]); + await localArea.set({[keyFor(name,id)]:record}); + } + async function restore(state,name,value) { + const record=COLLECTIONS[name].validate(value); + if(!state[name].some(item=>item[COLLECTIONS[name].id]===record[COLLECTIONS[name].id]))await write(state,name,record); + } + function mergeReview(local,imported) { + const files=new Map(local.files.map(file=>[file.path,file])); + for(const file of imported.files)if(!files.has(file.path)||file.updatedAt>files.get(file.path).updatedAt)files.set(file.path,file); + const latest=imported.updatedAt>local.updatedAt?imported:local; + return validateReview({...latest,files:[...files.values()],createdAt:Math.min(local.createdAt,imported.createdAt),updatedAt:Math.max(local.updatedAt,imported.updatedAt)}); + } + + async function handle(message) { + if (!message || !MESSAGE_TYPES.includes(message.type)) throw new Error('Unsupported workspace message.'); + const state = await readState(); + if (message.type === 'GET_STATE') return state; + switch(message.type) { + case 'SET_SETTINGS': + await localArea.set({[STORAGE.settings]:{...state.settings,...validateSettingsPatch(message.patch)}}); + break; + case 'SAVE_ITEM': { + const context=contextFrom(message.context),existing=state.items.find(item=>item.url===context.url),now=timestamp(existing); + await write(state,'items',{...context,note:message.note===undefined?existing?.note||'':noteFrom(message.note),createdAt:existing?.createdAt??now,updatedAt:now}); + break; + } + case 'UPDATE_ITEM': { + const {url}=contextFrom({url:message.url}),existing=find(state,'items',url); + await write(state,'items',{...existing,note:noteFrom(message.note),updatedAt:timestamp(existing)}); + break; + } + case 'REMOVE_ITEM': await localArea.remove(keyFor('items',contextFrom({url:message.url}).url));break; + case 'RESTORE_ITEM': await restore(state,'items',message.item);break; + case 'SAVE_SNIPPET': { + const input=message.snippet; + if(!input||typeof input!=='object'||Array.isArray(input))throw new Error('A snippet must be an object.'); + const id=input.id===undefined?globalThis.crypto.randomUUID():validateId(input.id); + if(state.snippets.some(item=>item.id===id))throw new Error('This snippet already exists. Edit its title or note instead.'); + const now=Date.now(); + await write(state,'snippets',{...input,id,title:input.title??'',note:input.note??'',path:input.path??'',language:input.language??'',lineStart:input.lineStart??null,lineEnd:input.lineEnd??null,revision:input.revision??null,createdAt:now,updatedAt:now}); + break; + } + case 'UPDATE_SNIPPET': { + const existing=find(state,'snippets',validateId(message.id)); + await write(state,'snippets',{...existing,...patchFrom(message.patch,['title','note']),updatedAt:timestamp(existing)}); + break; + } + case 'REMOVE_SNIPPET': await localArea.remove(keyFor('snippets',validateId(message.id)));break; + case 'RESTORE_SNIPPET': await restore(state,'snippets',message.snippet);break; + case 'CREATE_WORKSPACE': { + const now=Date.now(); + await write(state,'workspaces',{id:globalThis.crypto.randomUUID(),title:message.title,note:message.note??'',itemUrls:[],snippetIds:[],createdAt:now,updatedAt:now}); + break; + } + case 'UPDATE_WORKSPACE': { + const existing=find(state,'workspaces',validateId(message.id)); + await write(state,'workspaces',{...existing,...patchFrom(message.patch,['title','note']),updatedAt:timestamp(existing)}); + break; + } + case 'LINK_WORKSPACE_ITEM': case 'UNLINK_WORKSPACE_ITEM': case 'LINK_WORKSPACE_SNIPPET': case 'UNLINK_WORKSPACE_SNIPPET': { + const workspace=find(state,'workspaces',validateId(message.id)),isItem=message.type.endsWith('_ITEM'),link=message.type.startsWith('LINK_'); + const field=isItem?'itemUrls':'snippetIds',id=isItem?contextFrom({url:message.url}).url:validateId(message.snippetId); + if(link)find(state,isItem?'items':'snippets',id); + const references=link?[...new Set([...workspace[field],id])]:workspace[field].filter(value=>value!==id); + await write(state,'workspaces',{...workspace,[field]:references,updatedAt:timestamp(workspace)}); + break; + } + case 'REMOVE_WORKSPACE': await localArea.remove(keyFor('workspaces',validateId(message.id)));break; + case 'RESTORE_WORKSPACE': await restore(state,'workspaces',message.workspace);break; + case 'UPDATE_REVIEW_FILE': case 'SET_REVIEW_LAST_FILE': { + const prUrl=canonicalPrUrl(message.prUrl),path=validatePath(message.path),existing=state.reviews.find(item=>item.prUrl===prUrl),now=timestamp(existing); + const review=existing||{prUrl,files:[],lastFile:null,createdAt:now,updatedAt:now}; + if(message.type==='SET_REVIEW_LAST_FILE')await write(state,'reviews',{...review,lastFile:path,updatedAt:now}); + else { + const patch=patchFrom(message.patch,['note','reviewed']),revision=validateRevision(message.revision); + const current=review.files.find(file=>file.path===path)||{path,note:'',reviewed:false,reviewedRevision:null,reviewedAt:null,updatedAt:now}; + const file={...current,...patch,updatedAt:now}; + if(Object.hasOwn(patch,'reviewed')){if(typeof patch.reviewed!=='boolean')throw new Error('Reviewed must be a boolean.');file.reviewedRevision=patch.reviewed?revision:null;file.reviewedAt=patch.reviewed?now:null;} + await write(state,'reviews',{...review,files:[...review.files.filter(value=>value.path!==path),file],updatedAt:now}); + } + break; + } + case 'REMOVE_REVIEW': await localArea.remove(keyFor('reviews',canonicalPrUrl(message.prUrl)));break; + case 'RESTORE_REVIEW': await restore(state,'reviews',message.review);break; + case 'CREATE_TEMPLATE': { + const now=Date.now(); + await write(state,'templates',{id:globalThis.crypto.randomUUID(),title:message.title,body:message.body,createdAt:now,updatedAt:now}); + break; + } + case 'UPDATE_TEMPLATE': { + const existing=find(state,'templates',validateId(message.id)); + await write(state,'templates',{...existing,...patchFrom(message.patch,['title','body']),updatedAt:timestamp(existing)}); + break; + } + case 'REMOVE_TEMPLATE': await localArea.remove(keyFor('templates',validateId(message.id)));break; + case 'RESTORE_TEMPLATE': await restore(state,'templates',message.template);break; + case 'IMPORT_ITEMS': { + const imported=validateImport(message.text),writes={}; + for(const [name,collection] of Object.entries(COLLECTIONS)){ + const merged=new Map(state[name].map(record=>[record[collection.id],record])); + for(const record of imported[name]){ + const id=record[collection.id],existing=merged.get(id); + if(existing&&name==='reviews'){ + const next=mergeReview(existing,record);merged.set(id,next);writes[keyFor(name,id)]=next; + } else if(!existing||record.updatedAt>existing.updatedAt){merged.set(id,record);writes[keyFor(name,id)]=record;} + } + assertCapacity(name,[...merged.values()]); + } + if(imported.settings)writes[STORAGE.settings]={...state.settings,...imported.settings}; + if(Object.keys(writes).length)await localArea.set(writes); + break; + } + } + return readState(); + } + return {dispatch(message){const operation=queue.then(()=>handle(message));queue=operation.catch(()=>{});return operation;}}; + } + globalThis.GHE = {...globalThis.GHE,createStore,STORAGE,MESSAGE_TYPES}; +})(); diff --git a/src/content/code-tools.js b/src/content/code-tools.js new file mode 100644 index 0000000..f6178b8 --- /dev/null +++ b/src/content/code-tools.js @@ -0,0 +1,30 @@ +/* Read only the source GitHub has already rendered. Never fetch private code. */ +(() => { + const G=globalThis.GHE=globalThis.GHE||{}; + const languages={js:'javascript',jsx:'jsx',ts:'typescript',tsx:'tsx',py:'python',rb:'ruby',go:'go',rs:'rust',java:'java',kt:'kotlin',swift:'swift',cs:'csharp',cpp:'cpp',c:'c',h:'c',html:'html',css:'css',scss:'scss',json:'json',yaml:'yaml',yml:'yaml',md:'markdown',sh:'bash',sql:'sql',vue:'vue',svelte:'svelte',toml:'toml',xml:'xml'}; + function sourcePage(document){return /^\/[^/]+\/[^/]+\/blob\//.test(document.location.pathname);} + function collectCode(document){ + if(!sourcePage(document))return null; + const area=document.querySelector('#read-only-cursor-text-area'); + const legacy=[...document.querySelectorAll('td.blob-code')]; + if(!area&&!legacy.length)return null; + const full=area?area.value:legacy.map(n=>n.textContent).join('\n'); + const text=full.slice(0,300000),lines=text.split('\n'),truncated=full.length>text.length; + const completeLineCount=truncated?lines.length-1:lines.length; + const crumbs=[...document.querySelectorAll('#repos-header-breadcrumb--wide a')].slice(1).map(a=>a.textContent.trim()); + const filename=document.querySelector('#file-name-id-wide')?.textContent.trim()||decodeURIComponent(document.location.pathname.split('/').pop()); + const path=[...crumbs,filename].join('/'); + const match=document.location.hash.match(/^#L(\d+)(?:-L?(\d+))?$/); + let start=match?Number(match[1]):1,end=match?Number(match[2]||match[1]):Math.max(1,Math.min(12,completeLineCount)); + if(!match&&area&&area.selectionEnd>area.selectionStart){start=full.slice(0,area.selectionStart).split('\n').length;end=full.slice(0,area.selectionEnd).replace(/\n$/,'').split('\n').length;} + const validSelection=Number.isSafeInteger(start)&&Number.isSafeInteger(end)&&start>=1&&end>=start&&end<=completeLineCount; + const selectionError=validSelection?null:(completeLineCount?`Selected lines are not fully available in this loaded snapshot. Choose lines 1 to ${completeLineCount.toLocaleString()} or use GitHubโ€™s native source view for this range.`:'No complete source lines are available in this loaded snapshot. Use GitHubโ€™s native source view.'); + return {path,text,language:languages[filename.split('.').pop().toLowerCase()]||'',lineCount:completeLineCount,bytes:new TextEncoder().encode(full).length,truncated,selection:{start,end},selectionError,url:document.location.href.split('#')[0]}; + } + function codeAction(document,action){ + if(!sourcePage(document)||action.type!=='code-jump'||!Number.isInteger(action.line)||action.line<1||action.line>1000000)return false; + const target=document.querySelector(`[data-line-number="${action.line}"],#L${action.line}`);if(!target)return false; + document.location.hash=`L${action.line}`;target.scrollIntoView?.({block:'center',behavior:'auto'});return true; + } + Object.assign(G,{collectCode,codeAction}); +})(); diff --git a/src/content/conversation-tools.js b/src/content/conversation-tools.js new file mode 100644 index 0000000..eda2ca5 --- /dev/null +++ b/src/content/conversation-tools.js @@ -0,0 +1,105 @@ +/* Read only rendered, anchored conversation text. No requests or posting. */ +(() => { + 'use strict'; + const G = globalThis.GHE = globalThis.GHE || {}; + const IDS = '[id^="issue-"], [id^="issuecomment-"], [id^="discussion_r"], [id^="discussioncomment-"]'; + const VALID_ID = /^(?:issue-|issuecomment-|discussion_r|discussioncomment-)\d+$/; + const BODY = '[data-testid="markdown-body"], .js-comment-body, .comment-body'; + const EXCLUDED = '[data-ghe-host], [data-ghe-date], [hidden], [aria-hidden="true"], .d-none, form, .js-preview-body, script, style, textarea, input, [contenteditable="true"]'; + const MAX_COMMENTS = 200, MAX_BODY = 10000, MAX_TOTAL = 300000; + + function route(value) { + try { + const url = new URL(value); + if (url.origin !== 'https://github.com' || url.username || url.password || !/^\/[^/]+\/[^/]+\/(issues|pull|discussions)\/\d+\/?$/.test(url.pathname)) return null; + return url.origin + url.pathname.replace(/\/$/, ''); + } catch { return null; } + } + function excluded(element) { + if (!element || element.closest(EXCLUDED)) return true; + for (let e = element; e; e = e.parentElement) { + if (e.tagName === 'DETAILS' && !e.hasAttribute('open')) return true; + const style = e.style; + if (style?.display === 'none' || style?.visibility === 'hidden') return true; + } + return false; + } + function identify(anchor, base) { + if (!VALID_ID.test(anchor.id) || excluded(anchor) || anchor.closest('.markdown-body')) return null; + // React issues put the anchor on their header, not the body wrapper. + const scope = anchor.matches('[data-testid="comment-header"]') ? anchor.closest('.react-issue-comment') : anchor; + if (!scope) return null; + const body = [...scope.querySelectorAll(BODY)].find(candidate => { + if (excluded(candidate) || candidate.classList.contains('js-preview-body')) return false; + if (scope !== anchor) return candidate.closest('.react-issue-comment') === scope; + let owner = candidate.parentElement; + while (owner && owner !== anchor) { + if (VALID_ID.test(owner.id)) return false; + owner = owner.parentElement; + } + return owner === anchor; + }); + if (!body) return null; + // Require the page's own permalink outside user-authored Markdown. + const permalink = [...scope.querySelectorAll('a[href]')].find(link => { + if (link.closest('.markdown-body') || excluded(link)) return false; + try { const url = new URL(link.getAttribute('href'), base); return route(url.href) === base && url.hash === '#' + anchor.id; } + catch { return false; } + }); + if (!permalink) return null; + const authorNode = scope.querySelector('[data-testid="avatar-link"], .timeline-comment-header .author, .author'); + const author = (authorNode?.textContent || '').trim().slice(0, 100); + const kind = anchor.id.startsWith('issue-') ? 'description' : anchor.id.startsWith('discussion_r') ? 'review' : anchor.id.startsWith('discussioncomment-') ? 'discussion' : 'comment'; + return { anchor, body, id: anchor.id, url: base + '#' + anchor.id, author, kind }; + } + function bodyText(body, limit) { + const walker = body.ownerDocument.createTreeWalker(body, 4); + let text = '', previousBlock = null; + for (let leaf = walker.nextNode(); leaf; leaf = walker.nextNode()) { + if (excluded(leaf.parentElement)) continue; + const block = leaf.parentElement.closest('p, pre, li, blockquote, h1, h2, h3, h4, h5, h6, tr'); + if (block && previousBlock && block !== previousBlock && !text.endsWith('\n')) text += '\n'; + text += (leaf.nodeValue || '').slice(0, Math.max(0, limit + 1 - text.length)); + if (block) previousBlock = block; + if (text.length > limit) return { text: text.slice(0, limit).trim(), truncated: true }; + } + return { text: text.trim(), truncated: false }; + } + function scan(document, base) { + const comments = [], ids = new Set(), bodies = new Set(); + let length = 0, truncated = false; + for (const anchor of document.querySelectorAll(IDS)) { + const item = identify(anchor, base); + if (!item || ids.has(item.id) || bodies.has(item.body)) continue; + if (comments.length === MAX_COMMENTS || length >= MAX_TOTAL) { truncated = true; break; } + const result = bodyText(item.body, Math.min(MAX_BODY, MAX_TOTAL - length)); + truncated ||= result.truncated; + if (!result.text) continue; + ids.add(item.id); bodies.add(item.body); length += result.text.length; + comments.push({ id: item.id, url: item.url, author: item.author, body: result.text, kind: item.kind }); + } + return { comments, loadedOnly: true, truncated }; + } + function collectConversation(document, context) { + if (!context || !['issue', 'pull', 'discussion'].includes(context.type)) return null; + const base = route(context.url || document.location.href); + if (!base || base !== route(document.location.href)) return null; + return scan(document, base); + } + function conversationAction(document, action) { + const base = route(document.location.href); + if (!base || action?.type !== 'conversation-jump' || !VALID_ID.test(action.id || '')) return false; + // The action is limited to this bounded snapshot, not arbitrary page IDs. + if (!scan(document, base).comments.some(comment => comment.id === action.id)) return false; + const anchor = document.getElementById(action.id); + if (!anchor || !identify(anchor, base)) return false; + const previous = anchor.getAttribute('tabindex'); + try { + if (previous === null) anchor.setAttribute('tabindex', '-1'); + anchor.scrollIntoView({ block: 'start', behavior: 'auto' }); anchor.focus({ preventScroll: true }); + return true; + } catch { return false; } + finally { if (previous === null) anchor.removeAttribute('tabindex'); } + } + Object.assign(G, { collectConversation, conversationAction }); +})(); diff --git a/src/content/main.js b/src/content/main.js index 0610a54..c21f05e 100644 --- a/src/content/main.js +++ b/src/content/main.js @@ -1,411 +1,76 @@ -/** - * Main Content Script for GitHub Enhancer - * Coordinates all enhancement modules and handles initialization - */ - -const GitHubEnhancerMain = (() => { - const { Logger, Storage, DOMUtils } = window; - const { EVENT_TYPES, SELECTORS } = window.GITHUB_ENHANCER_CONSTANTS; - - // State management - const state = { - initialized: false, - enhancers: new Map(), - settings: null, - pageType: null, - lastURL: null - }; - - /** - * Initialize the main extension - */ - async function initialize() { - if (state.initialized) { - Logger.debug('GitHub Enhancer already initialized'); - return; - } - - try { - Logger.info('Initializing GitHub Enhancer'); - - // Load settings - await loadSettings(); - - // Set up logging level based on settings - if (state.settings.debugMode) { - Logger.setLogLevel(Logger.LOG_LEVELS.DEBUG); - } - - // Detect page type - detectPageType(); - - // Initialize enhancers based on settings - await initializeEnhancers(); - - // Set up global event listeners - setupEventListeners(); - - // Set up URL change detection for SPA navigation - setupNavigationHandling(); - - state.initialized = true; - Logger.info('GitHub Enhancer initialized successfully'); - - // Dispatch initialization event - dispatchEvent(EVENT_TYPES.ENHANCEMENT_COMPLETE, { - action: 'initialized', - pageType: state.pageType - }); - - } catch (error) { - Logger.logError(error, { context: 'Main initialization' }); - } - } - - /** - * Load settings from storage - */ - async function loadSettings() { - try { - state.settings = await Storage.settings.load(); - Logger.debug('Settings loaded:', state.settings); - } catch (error) { - Logger.logError(error, { context: 'Loading settings' }); - state.settings = window.GITHUB_ENHANCER_CONSTANTS.DEFAULT_SETTINGS; - } - } - - /** - * Detect the current GitHub page type - */ - function detectPageType() { - const path = window.location.pathname; - - if (path === '/' || path === '') { - state.pageType = 'home'; - } else if (path.includes('/settings')) { - state.pageType = 'settings'; - } else if (path.includes('/pull/')) { - state.pageType = 'pull_request'; - } else if (path.includes('/issues/')) { - state.pageType = 'issue'; - } else if (path.includes('/commit/')) { - state.pageType = 'commit'; - } else if (path.includes('/tree/') || path.includes('/blob/')) { - state.pageType = 'file_browser'; - } else if (path.match(/^\/[^\/]+\/[^\/]+\/?$/)) { - state.pageType = 'repository'; - } else { - state.pageType = 'other'; - } - - Logger.debug(`Detected page type: ${state.pageType}`); - } - - /** - * Initialize enhancer modules - */ - async function initializeEnhancers() { - const enhancerConfigs = [ - { - name: 'DateEnhancer', - enabled: state.settings.enhanceDateTimes, - module: window.DateEnhancer, - supportedPages: ['repository', 'file_browser', 'commit', 'pull_request', 'issue'] - }, - { - name: 'ContributorEnhancer', - enabled: state.settings.enhanceContributors, - module: window.ContributorEnhancer, - supportedPages: ['repository'] - }, - { - name: 'FileSizeEnhancer', - enabled: state.settings.enhanceFileSizes, - module: window.FileSizeEnhancer, - supportedPages: ['repository', 'file_browser'] - }, - { - name: 'ThemeEnhancer', - enabled: state.settings.enableThemeEnhancements, - module: window.ThemeEnhancer, - supportedPages: ['repository', 'file_browser', 'commit', 'pull_request', 'issue', 'home', 'other'] - } - ]; - - for (const config of enhancerConfigs) { - try { - if (!config.enabled) { - Logger.debug(`${config.name} disabled by settings`); - continue; - } - - if (!config.supportedPages.includes(state.pageType)) { - Logger.debug(`${config.name} not supported on ${state.pageType} pages`); - continue; - } - - if (!config.module) { - Logger.warn(`${config.name} module not loaded`); - continue; - } - - // Create and initialize enhancer instance - const enhancer = new config.module(config.name); - await enhancer.initialize(); - - state.enhancers.set(config.name, enhancer); - Logger.info(`${config.name} initialized successfully`); - - } catch (error) { - Logger.logError(error, { context: `Initializing ${config.name}` }); - } - } - } - - /** - * Set up global event listeners - */ - function setupEventListeners() { - // Listen for settings changes from popup - chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { - if (message.type === 'SETTINGS_UPDATED') { - handleSettingsUpdate(message.payload); - } else if (message.type === 'PING') { - sendResponse({ status: 'active' }); - } - }); - - // Listen for custom events from enhancers - document.addEventListener(EVENT_TYPES.ERROR_OCCURRED, handleEnhancerError); - document.addEventListener(EVENT_TYPES.ENHANCEMENT_COMPLETE, handleEnhancementComplete); - - // Handle visibility changes - document.addEventListener('visibilitychange', () => { - if (!document.hidden) { - Logger.debug('Page became visible, refreshing enhancers'); - refreshEnhancers(); - } - }); - - Logger.debug('Global event listeners set up'); - } - - /** - * Set up navigation handling for SPA - */ - function setupNavigationHandling() { - // Override pushState and replaceState to detect navigation - const originalPushState = history.pushState; - const originalReplaceState = history.replaceState; - - history.pushState = function(...args) { - originalPushState.apply(this, args); - handleNavigation(); - }; - - history.replaceState = function(...args) { - originalReplaceState.apply(this, args); - handleNavigation(); - }; - - // Handle popstate events - window.addEventListener('popstate', handleNavigation); - - Logger.debug('Navigation handling set up'); - } - - /** - * Handle navigation changes - */ - function handleNavigation() { - const currentURL = window.location.href; - - if (currentURL !== state.lastURL) { - Logger.debug(`Navigation detected: ${state.lastURL} -> ${currentURL}`); - state.lastURL = currentURL; - - // Small delay to let DOM update - setTimeout(() => { - detectPageType(); - reinitializeForNewPage(); - }, 100); - } - } - - /** - * Reinitialize enhancers for new page - */ - async function reinitializeForNewPage() { - try { - Logger.debug(`Reinitializing for page type: ${state.pageType}`); - - // Clean up existing enhancers - for (const [name, enhancer] of state.enhancers) { - enhancer.cleanup(); - } - state.enhancers.clear(); - - // Reinitialize enhancers for new page - await initializeEnhancers(); - - } catch (error) { - Logger.logError(error, { context: 'Page reinitialization' }); - } - } - - /** - * Handle settings updates from popup - */ - async function handleSettingsUpdate(newSettings) { - try { - Logger.info('Received settings update:', newSettings); - - const oldSettings = state.settings; - state.settings = newSettings; - - // Update logging level - if (newSettings.debugMode !== oldSettings.debugMode) { - Logger.setLogLevel(newSettings.debugMode ? Logger.LOG_LEVELS.DEBUG : Logger.LOG_LEVELS.INFO); - } - - // Check which enhancers need to be enabled/disabled - const enhancerStateChanges = [ - { name: 'DateEnhancer', old: oldSettings.enhanceDateTimes, new: newSettings.enhanceDateTimes }, - { name: 'ContributorEnhancer', old: oldSettings.enhanceContributors, new: newSettings.enhanceContributors }, - { name: 'FileSizeEnhancer', old: oldSettings.enhanceFileSizes, new: newSettings.enhanceFileSizes } - ]; - - for (const change of enhancerStateChanges) { - if (change.old !== change.new) { - const enhancer = state.enhancers.get(change.name); - - if (change.new && !enhancer) { - // Need to initialize this enhancer - await initializeEnhancers(); - break; // Re-initialize all to be safe - } else if (!change.new && enhancer) { - // Need to disable this enhancer - enhancer.disable(); - } else if (change.new && enhancer) { - // Enable existing enhancer - enhancer.enable(); - } - } - } - - // Update settings for all active enhancers - for (const [name, enhancer] of state.enhancers) { - if (enhancer.loadSettings) { - await enhancer.loadSettings(); - } - } - - Logger.info('Settings update handled successfully'); - - } catch (error) { - Logger.logError(error, { context: 'Handling settings update' }); - } - } - - /** - * Handle enhancer errors - */ - function handleEnhancerError(event) { - const { enhancer, error, context } = event.detail; - Logger.warn(`Enhancer error from ${enhancer}: ${error} (${context})`); - - // Could implement error recovery logic here - } - - /** - * Handle enhancement completion - */ - function handleEnhancementComplete(event) { - const { enhancer, action } = event.detail; - Logger.debug(`Enhancement complete: ${enhancer} - ${action}`); - - // Could implement analytics or performance tracking here - } - - /** - * Refresh all enhancers - */ - async function refreshEnhancers() { - try { - for (const [name, enhancer] of state.enhancers) { - if (enhancer.isEnabled && enhancer.enhance) { - await enhancer.enhance(); - } - } - } catch (error) { - Logger.logError(error, { context: 'Refreshing enhancers' }); - } - } - - /** - * Dispatch custom events - */ - function dispatchEvent(type, detail = {}) { - const event = new CustomEvent(type, { - detail: { - timestamp: Date.now(), - ...detail - } - }); - - document.dispatchEvent(event); +/* One lifecycle owner in the isolated content-script world. */ +(() => { + const G=globalThis.GHE; + if(G.runtime)return; + G.runtime=true; + const reading=G.createReadingEnhancer(document); + const host=document.createElement('div');host.dataset.gheHost='';host.id='ghe-workbench-host'; + host.dataset.gheBuild='hello-v2';host.dataset.gheConnection='awaiting-hello';host.dataset.gheEvent='create';host.dataset.gheFrameLoads='0'; + const shadow=host.attachShadow({mode:'open'}); + const style=document.createElement('style');style.textContent=` + :host{all:initial;position:fixed;right:20px;bottom:20px;z-index:80;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color-scheme:light dark} + :host([hidden]){display:none!important}button{font:600 12px -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#1f6feb;color:white;border:1px solid #388bfd;border-radius:8px;padding:10px 13px;cursor:pointer;display:flex;align-items:center;gap:9px;box-shadow:0 2px 6px #0003}button:hover{background:#1158c7}button:focus-visible{outline:3px solid #79c0ff;outline-offset:3px}button span:first-child{font-size:16px;letter-spacing:-1px}iframe{position:absolute;right:0;bottom:48px;width:400px;height:min(690px,calc(100dvh - 96px));border:1px solid #59636e;border-radius:12px;background:#0d1117;display:block;color-scheme:normal}iframe[hidden]{display:none}button[aria-expanded="true"]{background:#30363d;border-color:#59636e} + @media(max-width:480px){:host{right:12px;bottom:12px}iframe{width:calc(100vw - 24px);height:calc(100dvh - 84px)}} + @media(print){:host{display:none}} + .panel-status{position:absolute;right:0;bottom:48px;box-sizing:border-box;width:400px;min-height:180px;padding:28px;border:1px solid #30363d;border-radius:12px;background:#0d1117;color:#f0f6fc;box-shadow:0 8px 32px #0003;font-size:13px;line-height:1.6}.panel-status[hidden]{display:none}.panel-status strong{display:block;font-size:15px;margin-bottom:8px}.panel-status p{margin:0;color:#9198a1}:host([data-theme="light"]) .panel-status{background:#fff;color:#1f2328;border-color:#d1d9e0}:host([data-theme="light"]) .panel-status p{color:#59636e}@media(max-width:480px){.panel-status{width:calc(100vw - 24px)}} + `; + const launcher=document.createElement('button');launcher.type='button';launcher.setAttribute('aria-label','Open GitHub Enhancer');launcher.setAttribute('aria-expanded','false');launcher.title='GitHub Enhancer ยท Alt+Shift+K'; + const symbol=document.createElement('span');symbol.textContent='g+';symbol.setAttribute('aria-hidden','true');const label=document.createElement('span');label.textContent='Enhancer';launcher.append(symbol,label);shadow.append(style,launcher); + const panelStatus=document.createElement('section');panelStatus.className='panel-status';panelStatus.dataset.ghePanelStatus='';panelStatus.hidden=true;panelStatus.setAttribute('role','status');panelStatus.setAttribute('aria-live','polite'); + const statusTitle=document.createElement('strong'),statusDetail=document.createElement('p');panelStatus.append(statusTitle,statusDetail);shadow.append(panelStatus); + let settings=null,context=null,iframe=null,open=false,timer=null,lastContext='',pendingCommands=false,disposed=false,loadingTimer=null,requestId='',requestSequence=0,connected=false,frameURL='',frameObserver=null; + function theme(){const html=document.documentElement;const mode=html.dataset.colorMode;if(mode==='light')return'light';if(mode==='dark')return'dark';return matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';} + function pageContext(){return G.parseContext(location.href,document.title);} + function eligibleFrame(){return iframe?.isConnected&&!iframe.hasAttribute('srcdoc')&&iframe.src===frameURL;} + function trace(stage){host.dataset.gheEvent=stage;host.dataset.gheConnection=connected?'connected':'awaiting-hello';host.dataset.gheFrameConnected=String(Boolean(iframe?.isConnected));host.dataset.gheSrcEqual=String(Boolean(iframe&&iframe.src===frameURL));host.dataset.gheHasSrcdoc=String(Boolean(iframe?.hasAttribute('srcdoc')));host.dataset.gheRequestId=requestId;} + function post(message){if(connected&&eligibleFrame()){if(message.type==='PING')trace('probe');iframe.contentWindow?.postMessage(message,`chrome-extension://${chrome.runtime.id}`);}} + function pageSnapshot(){const current=pageContext();return {context:current,pageData:G.collectPageData?.(document,current)||{}};} + function sendContext(){if(!connected||!eligibleFrame())return;post({source:'ghe-host',type:'CONTEXT',url:context?.url||location.href,title:context?.title||document.title,theme:theme(),pageData:pageSnapshot().pageData});} + function close(){open=false;clearTimeout(loadingTimer);loadingTimer=null;requestId='';pendingCommands=false;panelStatus.hidden=true;if(iframe)iframe.hidden=true;launcher.setAttribute('aria-expanded','false');launcher.setAttribute('aria-label','Open GitHub Enhancer');launcher.focus();trace('closed');} + function beginLoading(){ + if(!open||!iframe)return; + clearTimeout(loadingTimer);iframe.hidden=true;panelStatus.hidden=false;panelStatus.dataset.state='loading';statusTitle.textContent='Opening your workspace';statusDetail.textContent='Connecting to GitHub Enhancerโ€ฆ'; + requestId=String(++requestSequence); + loadingTimer=setTimeout(()=>{ + loadingTimer=null;if(!open)return;requestId='';panelStatus.dataset.state='error';statusTitle.textContent='Panel could not load.';statusDetail.textContent='Reload this GitHub page or open GitHub Enhancer from the Chrome toolbar.';trace('timeout'); + },8000); + post({source:'ghe-host',type:'PING',requestId}); } - - /** - * Cleanup function - */ - function cleanup() { - try { - // Clean up all enhancers - for (const [name, enhancer] of state.enhancers) { - enhancer.cleanup(); - } - state.enhancers.clear(); - - // Remove event listeners - document.removeEventListener(EVENT_TYPES.ERROR_OCCURRED, handleEnhancerError); - document.removeEventListener(EVENT_TYPES.ENHANCEMENT_COMPLETE, handleEnhancementComplete); - - state.initialized = false; - Logger.info('GitHub Enhancer cleaned up'); - - } catch (error) { - Logger.logError(error, { context: 'Cleanup' }); + function show(commands=false){if(!settings?.enabled)return;let panelURL;try{if(!chrome.runtime.id)throw new Error('Stale extension context');panelURL=chrome.runtime.getURL('src/panel/panel.html');}catch{open=true;connected=false;requestId='';clearTimeout(loadingTimer);loadingTimer=null;if(iframe)iframe.hidden=true;panelStatus.hidden=false;panelStatus.dataset.state='error';statusTitle.textContent='Reload this GitHub page';statusDetail.textContent='GitHub Enhancer was updated. Reload the page to connect to the new version.';launcher.setAttribute('aria-expanded','true');launcher.setAttribute('aria-label','Close GitHub Enhancer');return;}open=true;pendingCommands=commands;launcher.setAttribute('aria-expanded','true');launcher.setAttribute('aria-label','Close GitHub Enhancer');trace('open'); + if(!iframe){ + iframe=document.createElement('iframe');iframe.hidden=true;iframe.title='GitHub Enhancer workspace';iframe.setAttribute('allow','clipboard-write'); + const invalidate=event=>{connected=false;requestId='';const reason=event?.type==='load'?'load':event?.[0]?.attributeName||'src-change';host.dataset.gheInvalidatedBy=reason;if(reason==='load')host.dataset.gheFrameLoads=String(Number(host.dataset.gheFrameLoads)+1);trace(reason==='load'?'load':'src-change');host.dataset.gheConnection='disconnected';if(open&&panelStatus.dataset.state!=='error')beginLoading();}; + iframe.addEventListener('load',invalidate); + const params=new URLSearchParams({url:context?.url||location.href,title:context?.title||document.title,theme:theme()});frameURL=panelURL+'?'+params;iframe.src=frameURL; + frameObserver=new MutationObserver(invalidate);frameObserver.observe(iframe,{attributes:true,attributeFilter:['src','srcdoc','sandbox']}); + shadow.append(iframe); } + beginLoading(); } - - /** - * Public API - */ - return { - initialize, - cleanup, - getStatus: () => ({ - initialized: state.initialized, - pageType: state.pageType, - enhancerCount: state.enhancers.size, - settings: state.settings - }), - getEnhancers: () => Array.from(state.enhancers.keys()), - refreshEnhancers - }; + launcher.addEventListener('click',()=>open?close():show()); + function update(){timer=null;if(disposed||!settings)return;const reattached=!host.isConnected;if(reattached){connected=false;document.documentElement.append(host);host.dataset.gheInvalidatedBy='reattach';trace('reattach');host.dataset.gheConnection='disconnected';}context=pageContext();host.hidden=!settings.enabled;host.dataset.theme=settings.theme==='auto'?theme():settings.theme;reading.apply(settings,context);const next=JSON.stringify([context?.url,context?.title,theme()]);if(next!==lastContext){G.resetReviewTools?.(document);lastContext=next;sendContext();}if(!settings.enabled){G.resetReviewTools?.(document);if(open)close();}else if(reattached&&open)beginLoading();} + function schedule(){if(!timer)timer=setTimeout(update,40);} + const observer=new MutationObserver(records=>{if(records.some(record=>!host.contains(record.target)&&(record.type==='attributes'||![...record.addedNodes,...record.removedNodes].every(n=>n.nodeType===1&&n.hasAttribute?.('data-ghe-date')))))schedule();}); + observer.observe(document.documentElement,{childList:true,subtree:true,attributes:true,attributeFilter:['datetime','data-color-mode','data-dark-theme','data-light-theme']}); + for(const event of ['turbo:load','turbo:render','pjax:end'])document.addEventListener(event,schedule); + for(const event of ['popstate','hashchange','pageshow'])window.addEventListener(event,schedule); + document.addEventListener('visibilitychange',()=>{if(!document.hidden)schedule();}); + window.addEventListener('keydown',event=>{ + if(settings?.enabled&&settings.shortcut&&event.altKey&&event.shiftKey&&!event.ctrlKey&&!event.metaKey&&event.code==='KeyK'){event.preventDefault();show(true);} + else if(event.key==='Escape'&&open){close();} + }); + window.addEventListener('message',event=>{ + if(event.data?.source==='ghe-panel'&&['HELLO','READY','CLOSE'].includes(event.data.type)){host.dataset.gheLastReceived=event.data.type;host.dataset.gheRejected=!eligibleFrame()?'eligible':event.source!==iframe.contentWindow?'source':event.origin!==`chrome-extension://${chrome.runtime.id}`?'origin':event.data.type==='READY'&&event.data.requestId!==requestId?'request':'';} + if(!eligibleFrame()||event.source!==iframe.contentWindow||event.origin!==`chrome-extension://${chrome.runtime.id}`||event.data?.source!=='ghe-panel')return; + if(event.data.type==='HELLO'){connected=true;trace('hello');if(open&&requestId)post({source:'ghe-host',type:'PING',requestId});} + else if(event.data.type==='REQUEST_CONTEXT')sendContext(); + else if(event.data.type==='PAGE_ACTION'&&connected){const ok=G.applyPageAction?.(document,event.data.action)||false;post({source:'ghe-host',type:'ACTION_RESULT',requestId:event.data.requestId,ok});} + else if(event.data.type==='CLOSE')close();else if(event.data.type==='READY'&&connected&&open&&requestId&&event.data.requestId===requestId){clearTimeout(loadingTimer);loadingTimer=null;requestId='';panelStatus.hidden=true;panelStatus.dataset.state='ready';iframe.hidden=false;sendContext();if(pendingCommands){post({source:'ghe-host',type:'COMMANDS'});pendingCommands=false;}iframe.focus();trace('ready');} + }); + let generation=0; + async function load(){const current=++generation;try{const response=await chrome.runtime.sendMessage({type:'GET_STATE'});if(response?.ok&¤t===generation){settings=response.state.settings;update();}}catch{if(iframe)close();host.hidden=true;reading.destroy();}} + chrome.storage.onChanged.addListener((_changes,area)=>{if(area==='local')load();}); + chrome.runtime.onMessage.addListener((message,sender,respond)=>{if(sender.id&&sender.id!==chrome.runtime.id)return;if(message.type==='GET_CONTEXT')respond(pageSnapshot());else if(message.type==='PAGE_ACTION')respond({ok:settings?.enabled&&(G.applyPageAction?.(document,message.action)||false)});}); + window.addEventListener('pagehide',event=>{if(!event.persisted){disposed=true;G.resetReviewTools?.(document);observer.disconnect();frameObserver?.disconnect();clearTimeout(timer);clearTimeout(loadingTimer);}}); + document.documentElement.append(host);load(); })(); - -// Initialize when DOM is ready -if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', GitHubEnhancerMain.initialize); -} else { - GitHubEnhancerMain.initialize(); -} - -// Clean up on page unload -window.addEventListener('beforeunload', GitHubEnhancerMain.cleanup); - -// Global access for debugging -window.GitHubEnhancerMain = GitHubEnhancerMain; \ No newline at end of file diff --git a/src/content/page-tools.js b/src/content/page-tools.js new file mode 100644 index 0000000..fcb968f --- /dev/null +++ b/src/content/page-tools.js @@ -0,0 +1,12 @@ +/* One bounded snapshot per explicit request or page-context change. */ +(() => { + const G=globalThis.GHE; + G.collectPageData=(document,context)=>({code:G.collectCode?.(document,context)||null,review:G.collectReview?.(document,context)||null,conversation:G.collectConversation?.(document,context)||null}); + G.applyPageAction=(document,action)=>{ + if(!action||typeof action.type!=='string')return false; + if(action.type==='conversation-jump')return G.conversationAction?.(document,action)||false; + if(action.type==='code-jump')return G.codeAction?.(document,action)||false; + if(action.type.startsWith('review-'))return G.reviewAction?.(document,action)||false; + return false; + }; +})(); diff --git a/src/content/reading.js b/src/content/reading.js new file mode 100644 index 0000000..b00bc39 --- /dev/null +++ b/src/content/reading.js @@ -0,0 +1,175 @@ +(function () { + 'use strict'; + + const GHE = globalThis.GHE = globalThis.GHE || {}; + const DATE_SELECTOR = 'relative-time[datetime], time-ago[datetime]'; + // Modern GitHub caps both the outer layout and its main content column. + // Match the observed component boundary, never the adjacent pane or README. + const CONTENT_SELECTOR = [ + '.repository-content', + '.repository-content .container-xl', + '[data-testid="repos-split-pane-content"]', + '.repository-content [data-component="SplitPageLayout.Content"]', + '.repository-content [data-component="SplitPageLayout.Content"] > [class*="prc-PageLayout-Content-"]' + ].join(', '); + + GHE.createReadingEnhancer = function createReadingEnhancer(document) { + const dates = new Map(); + const wideNodes = new Set(); + const focusNodes = new Set(); + const focusLayouts = new Set(); + let style; + + function clearDates() { + for (const span of dates.values()) span.remove(); + dates.clear(); + } + + function reconcileClass(owned, desired, className) { + for (const node of owned) { + if (!desired.has(node)) { + node.classList.remove(className); + owned.delete(node); + } + } + for (const node of desired) { + if (!node.classList.contains(className)) { + node.classList.add(className); + owned.add(node); + } + } + } + + function destroy() { + clearDates(); + reconcileClass(wideNodes, new Set(), 'ghe-wide'); + reconcileClass(focusNodes, new Set(), 'ghe-focus-sidebar'); + reconcileClass(focusLayouts, new Set(), 'ghe-focus-layout'); + if (style) style.remove(); + style = undefined; + } + + function apply(settings, context) { + if (!settings || !settings.enabled) { + destroy(); + return; + } + + if (!style || !style.isConnected) { + style = document.createElement('style'); + style.setAttribute('data-ghe-reading', ''); + style.textContent = ` + [data-ghe-date] { + margin-inline-start: .35em; + color: inherit; + font-size: .875em; + font-weight: normal; + white-space: normal; + } + [data-ghe-date][data-ghe-compact] { + display: block; + margin-inline-start: 0; + margin-top: 2px; + font-size: 11px; + line-height: 16px; + white-space: nowrap; + } + td:has([data-ghe-date][data-ghe-compact]) { + min-width: 100px; + } + .repository-content.ghe-wide, + .repository-content .container-xl.ghe-wide, + [data-testid="repos-split-pane-content"].ghe-wide, + .repository-content [data-component="SplitPageLayout.Content"].ghe-wide, + .repository-content [data-component="SplitPageLayout.Content"] > [class*="prc-PageLayout-Content-"].ghe-wide { + max-width: none !important; + width: 100% !important; + } + .repository-content .Layout-sidebar.ghe-focus-sidebar, + .repository-content [class*="prc-PageLayout-PaneWrapper-"].ghe-focus-sidebar { + display: none !important; + } + .repository-content .ghe-focus-layout { + display: block !important; + } + .repository-content .ghe-focus-layout > [data-component="SplitPageLayout.Content"] { + width: 100% !important; + max-width: none !important; + } + `; + (document.head || document.documentElement).append(style); + } + + const outsideExtension = node => !node.closest('[data-ghe-host]'); + reconcileClass(wideNodes, new Set(settings.wide + ? [...document.querySelectorAll(CONTENT_SELECTOR)].filter(outsideExtension) : []), 'ghe-wide'); + // The shared context also labels repository subpages (issues lists, settings) + // as repositories. Only the two-segment overview URL owns the About sidebar. + let isOverview = false; + try { + const url = new URL(context?.url || document.location.href); + isOverview = context?.type === 'repository' && /^\/[^/]+\/[^/]+\/?$/.test(url.pathname); + } catch { /* Unknown locations must not hide page content. */ } + const sidebars = new Set(); + const layouts = new Set(); + if (settings.focus && isOverview) { + for (const sidebar of document.querySelectorAll('.repository-content .Layout-sidebar')) { + if (outsideExtension(sidebar)) sidebars.add(sidebar); + } + for (const pane of document.querySelectorAll('.repository-content [class*="prc-PageLayout-PaneWrapper-"][data-position="end"]')) { + if (!outsideExtension(pane) || !pane.querySelector('[data-component="SplitPageLayout.Pane"] [class*="SidebarAbout-module__aboutHeading__"]')) continue; + sidebars.add(pane); + const layout = pane.parentElement; + if (layout?.matches('[class*="prc-PageLayout-PageLayoutContent-"]') && layout.querySelector(':scope > [data-component="SplitPageLayout.Content"]')) layouts.add(layout); + } + } + reconcileClass(focusNodes, sidebars, 'ghe-focus-sidebar'); + reconcileClass(focusLayouts, layouts, 'ghe-focus-layout'); + + if (!settings.exactDates) { + clearDates(); + return; + } + + const current = new Set(); + for (const time of document.querySelectorAll(DATE_SELECTOR)) { + if (!outsideExtension(time)) continue; + const value = time.getAttribute('datetime'); + if (!value || !Number.isFinite(new Date(value).getTime())) continue; + const formatted = GHE.formatDate(value, { locale: settings.locale, timeZone: settings.timeZone }); + if (!formatted) continue; + current.add(time); + let span = dates.get(time); + if (!span) { + span = document.createElement('span'); + span.setAttribute('data-ghe-date', ''); + dates.set(time, span); + } + const cell = time.closest('td'); + const compact = Boolean(cell && cell.closest('table')); + const text = compact + ? new Intl.DateTimeFormat(settings.locale === 'auto' ? undefined : settings.locale, { + year: 'numeric', month: 'short', day: 'numeric', + ...(settings.timeZone === 'UTC' ? { timeZone: 'UTC' } : {}) + }).format(new Date(value)) + : `(${formatted})`; + const zone = settings.timeZone === 'UTC' ? 'UTC' : 'local time'; + const title = `Exact date (${zone}): ${formatted}. Original timestamp: ${value}`; + // Avoid writing unchanged values: the content runtime observes page mutations. + if (span.hasAttribute('data-ghe-compact') !== compact) span.toggleAttribute('data-ghe-compact', compact); + if (span.textContent !== text) span.textContent = text; + if (span.title !== title) span.title = title; + if (time.nextSibling !== span) time.after(span); + } + + for (const [time, span] of dates) { + if (!current.has(time)) { + span.remove(); + dates.delete(time); + } + } + } + + return { apply, destroy }; + }; +})(); diff --git a/src/content/review-tools.js b/src/content/review-tools.js new file mode 100644 index 0000000..36ffbb7 --- /dev/null +++ b/src/content/review-tools.js @@ -0,0 +1,150 @@ +/* Read loaded GitHub diffs; native review state remains authoritative. */ +(() => { + 'use strict'; + const G = globalThis.GHE = globalThis.GHE || {}; + const SELECTOR = '[role="region"][id^="diff-"], .file[id^="diff-"]'; + const MAX_FILES = 200; + const collapsedDocuments = new WeakMap(); + + function resetReviewTools(document) { + const owned = collapsedDocuments.get(document); + if (!owned) return; + for (const table of owned.nodes) table.classList.remove('ghe-review-collapsed-body'); + owned.style.remove(); + collapsedDocuments.delete(document); + } + + function reviewRoute(value) { + try { + const url = new URL(value); + if (url.origin !== 'https://github.com' || url.username || url.password) return null; + const pr = url.pathname.match(/^\/[^/]+\/[^/]+\/pull\/\d+\/(?:files|changes)(?:\/([a-f0-9]{7,40}))?\/?$/i); + const commit = url.pathname.match(/^\/[^/]+\/[^/]+\/commit\/([a-f0-9]{6,40})\/?$/i); + if (!pr && !commit) return null; + const revision = pr?.[1] || commit?.[1] || ''; + // A short hash cannot be compared safely with persisted full revisions. + // Aggregate views expose no authoritative head marker in the observed DOM. + return { revision: /^[a-f0-9]{40}$/i.test(revision) ? revision.toLowerCase() : null }; + } catch { return null; } + } + + function cleanPath(value) { + if (typeof value !== 'string') return ''; + const text = value.replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '').trim(); + return text.length && text.length <= 4096 && !/[\u0000-\u001f\u007f]/.test(text) ? text : ''; + } + + function groupPath(path) { + const lower = path.toLowerCase(); + const name = lower.split('/').pop(); + const folder = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''; + const extension = name.includes('.') && !name.startsWith('.') ? '.' + name.split('.').pop() : ''; + const lockfile = /^(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|cargo\.lock|poetry\.lock|pipfile\.lock|gemfile\.lock|composer\.lock|go\.sum)$/.test(name); + const generated = /(^|\/)(dist|build|coverage|vendor|generated|__generated__)(\/|$)/.test(lower) || /\.(min\.[^./]+|generated\.[^./]+|map)$/.test(name); + let group = 'source'; + if (/(^|\/)(__tests__|tests?|specs?|e2e|cypress)(\/|$)/.test(lower) || /\.(test|spec)\.[^./]+$/.test(name)) group = 'tests'; + else if (/(^|\/)(docs?|documentation)(\/|$)/.test(lower) || /\.(md|mdx|rst|adoc)$/.test(name) || /^(readme|license|changelog|contributing)(\.|$)/.test(name)) group = 'docs'; + else if (lockfile || lower.startsWith('.github/') || /\.(json|ya?ml|toml|ini|cfg)$/.test(name) || /(^\.|\.config\.|^dockerfile$|^makefile$|^gemfile$|^go\.mod$)/.test(name)) group = 'config'; + return { group, folder, extension, lockfile, generated }; + } + + function describe(container) { + if (!/^diff-[a-z0-9_-]{1,128}$/i.test(container.id) || container.closest('[data-ghe-host], [hidden], [aria-hidden="true"], .markdown-body')) return null; + const header = container.querySelector('[data-diff-header-wrapper], .file-header'); + if (!header) return null; + const code = header.querySelector('h3 a code'); + let path = cleanPath(header.getAttribute('data-path') || header.querySelector('[data-file-path]')?.getAttribute('data-file-path')); + if (!path && code) { + const renameArrow = code.querySelector('span[aria-hidden="true"] svg.octicon-arrow-right'); + if (renameArrow) { + let destination = ''; + for (let node = renameArrow.nextSibling; node; node = node.nextSibling) destination += node.textContent || ''; + path = cleanPath(destination); + } else path = cleanPath(code.textContent); + } + if (!path) return null; + const nativeButton = header.querySelector('[class*="MarkAsViewedButton-"][aria-pressed]'); + const nativeCheckbox = header.querySelector('input.js-reviewed-checkbox[type="checkbox"]'); + const viewedKnown = Boolean(nativeButton || nativeCheckbox); + const viewed = nativeButton ? nativeButton.getAttribute('aria-pressed') === 'true' : Boolean(nativeCheckbox?.checked); + const stats = {}; + for (const label of header.querySelectorAll('.sr-only')) { + const match = label.textContent.match(/^Lines changed:\s*([\d,]+) additions?\s*&\s*([\d,]+) deletions?$/); + if (match) { + const additions = Number(match[1].replaceAll(',', '')); + const deletions = Number(match[2].replaceAll(',', '')); + if (Number.isSafeInteger(additions) && Number.isSafeInteger(deletions)) Object.assign(stats, { additions, deletions }); + break; + } + } + return { id: container.id, path, ...groupPath(path), viewed, viewedKnown, ...stats, + ...(container.querySelector('.ghe-review-collapsed-body') ? { collapsed: true } : {}) }; + } + + function collectReview(document, context) { + if (!context || !['pull', 'commit'].includes(context.type)) return null; + const route = reviewRoute(context.url || document.location.href); + if (!route) return null; + const files = []; + const ids = new Set(); + let truncated = false; + for (const container of document.querySelectorAll(SELECTOR)) { + const file = describe(container); + if (!file || ids.has(file.id)) continue; + if (files.length === MAX_FILES) { truncated = true; break; } + ids.add(file.id); + files.push(file); + } + return files.length ? { files, loadedOnly: true, revision: route.revision, truncated } : null; + } + + function reviewAction(document, action) { + if (!['review-jump', 'review-collapse'].includes(action?.type) || typeof action.id !== 'string' || !reviewRoute(document.location.href)) return false; + const container = document.getElementById(action.id); + if (!container?.matches(SELECTOR) || !describe(container)) return false; + if (action.type === 'review-collapse') { + if (typeof action.collapsed !== 'boolean') return false; + // Modern rendered diffs use tables; deferred/deleted diffs use a + // HiddenDiffPatch placeholder tied to this exact diff anchor. Neither + // selector includes the header or arbitrary sibling comment panels. + const bodies = [...container.querySelectorAll('table, .diff-table')]; + for (const placeholder of container.querySelectorAll('div[data-diff-anchor]')) { + if (placeholder.getAttribute('data-diff-anchor') === container.id && + placeholder.querySelector(':scope > [class*="HiddenDiffPatch-module__"]')) bodies.push(placeholder); + } + const tables = bodies.filter(table => + !table.closest('[data-diff-header-wrapper], .file-header, .markdown-body, [data-ghe-host]')); + if (!tables.length) return false; + let owned = collapsedDocuments.get(document); + if (!owned && action.collapsed) { + const style = document.createElement('style'); + style.setAttribute('data-ghe-review-style', ''); + style.textContent = '.ghe-review-collapsed-body{display:none !important}'; + (document.head || document.documentElement).append(style); + owned = { nodes: new Set(), style }; + collapsedDocuments.set(document, owned); + } + for (const table of tables) { + if (action.collapsed && !table.classList.contains('ghe-review-collapsed-body')) { + table.classList.add('ghe-review-collapsed-body'); owned.nodes.add(table); + } else if (!action.collapsed && owned?.nodes.has(table)) { + table.classList.remove('ghe-review-collapsed-body'); owned.nodes.delete(table); + } + } + if (owned && !owned.nodes.size) resetReviewTools(document); + return true; + } + const previousTabIndex = container.getAttribute('tabindex'); + try { + if (previousTabIndex === null) container.setAttribute('tabindex', '-1'); + container.scrollIntoView({ block: 'start', behavior: 'auto' }); + container.focus({ preventScroll: true }); + return true; + } catch { return false; } + finally { + if (previousTabIndex === null) container.removeAttribute('tabindex'); + } + } + + Object.assign(G, { collectReview, reviewAction, resetReviewTools }); +})(); diff --git a/src/enhancers/base-enhancer.js b/src/enhancers/base-enhancer.js deleted file mode 100644 index 4ed9b9b..0000000 --- a/src/enhancers/base-enhancer.js +++ /dev/null @@ -1,362 +0,0 @@ -/** - * Base Enhancer class for GitHub Enhancer - * Provides common functionality for all enhancement modules - */ - -const BaseEnhancer = (() => { - const Logger = window.Logger || console; - const Storage = window.Storage; - const DOMUtils = window.DOMUtils; - - // Define constants locally - const ERROR_TYPES = { - ENHANCEMENT: 'ENHANCEMENT_ERROR', - NETWORK: 'NETWORK_ERROR', - STORAGE: 'STORAGE_ERROR' - }; - - const EVENT_TYPES = { - ERROR_OCCURRED: 'github-enhancer:error', - ENHANCEMENT_COMPLETE: 'github-enhancer:complete' - }; - - /** - * Base class for all enhancers - */ - class EnhancerBase { - constructor(name, options = {}) { - this.name = name; - this.isInitialized = false; - this.isEnabled = true; - this.observers = new Set(); - this.settings = null; - this.performanceMetrics = new Map(); - - // Configuration - this.config = { - debounceDelay: 250, - retryAttempts: 3, - retryDelay: 1000, - batchSize: 10, - ...options - }; - - // Bind methods to maintain context - this.enhance = this.enhance.bind(this); - this.handleMutation = this.handleMutation.bind(this); - this.handleError = this.handleError.bind(this); - } - - /** - * Initialize the enhancer - */ - async initialize() { - if (this.isInitialized) { - Logger.debug(`${this.name} already initialized`); - return; - } - - try { - Logger.info(`Initializing ${this.name} enhancer`); - - // Load settings - await this.loadSettings(); - - // Run initial setup - await this.setup(); - - // Start observing if enabled - if (this.isEnabled) { - this.startObserving(); - await this.runInitialEnhancement(); - } - - this.isInitialized = true; - Logger.info(`${this.name} enhancer initialized successfully`); - } catch (error) { - Logger.logError(error, { context: `${this.name} initialization` }); - throw error; - } - } - - /** - * Setup method to be overridden by child classes - */ - async setup() { - // Override in child classes - } - - /** - * Load settings from storage - */ - async loadSettings() { - try { - this.settings = await Storage.settings.load(); - Logger.debug(`Settings loaded for ${this.name}:`, this.settings); - } catch (error) { - Logger.logError(error, { context: `${this.name} settings loading` }); - this.settings = { - enhanceContributors: true, - enhanceDateTimes: true, - enhanceFileSizes: true, - showCommitInfo: true, - showTeamInfo: true, - showOrgInfo: true, - cardWidth: 250, - maxCards: 10, - locale: 'en-US', - theme: 'auto', - animationsEnabled: true, - debugMode: false - }; - } - } - - /** - * Start observing DOM changes - */ - startObserving() { - if (!this.shouldObserve()) { - return; - } - - const debouncedHandler = DOMUtils.debounce( - this.handleMutation, - this.config.debounceDelay - ); - - const observer = new MutationObserver(debouncedHandler); - - observer.observe(document.body, { - childList: true, - subtree: true, - attributes: false, - attributeOldValue: false - }); - - this.observers.add(observer); - Logger.debug(`${this.name} DOM observer started`); - } - - /** - * Stop observing DOM changes - */ - stopObserving() { - this.observers.forEach(observer => observer.disconnect()); - this.observers.clear(); - Logger.debug(`${this.name} DOM observers stopped`); - } - - /** - * Handle DOM mutations - */ - async handleMutation(mutations) { - if (!this.isEnabled || !this.shouldEnhance(mutations)) { - return; - } - - try { - await this.enhance(); - } catch (error) { - this.handleError(error, 'DOM mutation handling'); - } - } - - /** - * Main enhancement method to be overridden - */ - async enhance() { - throw new Error(`${this.name} must implement enhance() method`); - } - - /** - * Run initial enhancement - */ - async runInitialEnhancement() { - try { - Logger.debug(`Running initial enhancement for ${this.name}`); - await this.enhance(); - } catch (error) { - this.handleError(error, 'Initial enhancement'); - } - } - - /** - * Check if should observe DOM changes - */ - shouldObserve() { - return this.isEnabled && this.isInitialized; - } - - /** - * Check if should enhance based on mutations - */ - shouldEnhance(mutations) { - return mutations.some(mutation => - mutation.type === 'childList' && - mutation.addedNodes.length > 0 - ); - } - - /** - * Error handling - */ - handleError(error, context = 'Unknown') { - Logger.logError(error, { - context: `${this.name} - ${context}`, - enhancer: this.name - }); - - // Dispatch error event - this.dispatchEvent(EVENT_TYPES.ERROR_OCCURRED, { - enhancer: this.name, - error: error.message, - context - }); - } - - /** - * Performance monitoring - */ - startPerformanceTimer(label) { - this.performanceMetrics.set(label, performance.now()); - } - - endPerformanceTimer(label) { - const startTime = this.performanceMetrics.get(label); - if (startTime) { - const duration = performance.now() - startTime; - this.performanceMetrics.delete(label); - Logger.debug(`${this.name} - ${label}: ${duration.toFixed(2)}ms`); - return duration; - } - return null; - } - - /** - * Batch processing utility - */ - async processBatch(items, processor, batchSize = this.config.batchSize) { - const batches = []; - for (let i = 0; i < items.length; i += batchSize) { - batches.push(items.slice(i, i + batchSize)); - } - - for (const batch of batches) { - await Promise.all(batch.map(processor)); - - // Small delay between batches to prevent blocking - if (batches.length > 1) { - await new Promise(resolve => setTimeout(resolve, 10)); - } - } - } - - /** - * Retry wrapper for operations - */ - async withRetry(operation, attempts = this.config.retryAttempts) { - let lastError; - - for (let i = 0; i < attempts; i++) { - try { - return await operation(); - } catch (error) { - lastError = error; - - if (i < attempts - 1) { - const delay = this.config.retryDelay * Math.pow(2, i); - Logger.debug(`${this.name} retry ${i + 1}/${attempts} in ${delay}ms`); - await new Promise(resolve => setTimeout(resolve, delay)); - } - } - } - - throw lastError; - } - - /** - * Dispatch custom events - */ - dispatchEvent(type, detail = {}) { - const event = new CustomEvent(type, { - detail: { - enhancer: this.name, - timestamp: Date.now(), - ...detail - } - }); - - document.dispatchEvent(event); - } - - /** - * Enable the enhancer - */ - enable() { - this.isEnabled = true; - Logger.info(`${this.name} enhancer enabled`); - - if (this.isInitialized) { - this.startObserving(); - this.runInitialEnhancement(); - } - } - - /** - * Disable the enhancer - */ - disable() { - this.isEnabled = false; - this.stopObserving(); - Logger.info(`${this.name} enhancer disabled`); - } - - /** - * Cleanup resources - */ - cleanup() { - this.stopObserving(); - this.performanceMetrics.clear(); - this.isInitialized = false; - Logger.debug(`${this.name} enhancer cleaned up`); - } - - /** - * Get enhancer status - */ - getStatus() { - return { - name: this.name, - isInitialized: this.isInitialized, - isEnabled: this.isEnabled, - observerCount: this.observers.size, - hasSettings: !!this.settings - }; - } - } - - // Static utilities - EnhancerBase.createError = (message, type = ERROR_TYPES.GENERAL) => { - const error = new Error(message); - error.type = type; - return error; - }; - - EnhancerBase.isElementEnhanced = (element, enhancerName) => { - return element.hasAttribute(`data-${enhancerName}-enhanced`); - }; - - EnhancerBase.markElementEnhanced = (element, enhancerName) => { - element.setAttribute(`data-${enhancerName}-enhanced`, 'true'); - }; - - EnhancerBase.unmarkElementEnhanced = (element, enhancerName) => { - element.removeAttribute(`data-${enhancerName}-enhanced`); - }; - - return EnhancerBase; -})(); - -// Global availability -window.BaseEnhancer = BaseEnhancer; \ No newline at end of file diff --git a/src/enhancers/contributor-enhancer.js b/src/enhancers/contributor-enhancer.js deleted file mode 100644 index b5cad45..0000000 --- a/src/enhancers/contributor-enhancer.js +++ /dev/null @@ -1,1001 +0,0 @@ -/** - * Contributor Enhancer for GitHub Enhancer - * Uses GitHub's internal hovercard API for better performance and no rate limiting - */ - -const ContributorEnhancer = (() => { - const { BaseEnhancer } = window; - const Logger = window.Logger || console; - const DOMUtils = window.DOMUtils; - const Storage = window.Storage; - - class ContributorEnhancerClass extends BaseEnhancer { - constructor(name = 'ContributorEnhancer') { - super(name, { - debounceDelay: 500, - batchSize: 5 - }); - - this.enhancementInProgress = false; - this.cache = new Map(); - this.cacheExpiry = 5 * 60 * 1000; // 5 minutes - } - - async setup() { - Logger.debug(`Setting up ${this.name}`); - this.insertContributorStyles(); - } - - shouldEnhance(mutations) { - if (!window.location.pathname.match(/^\/[^\/]+\/[^\/]+\/?$/)) { - return false; - } - - return mutations.some(mutation => { - if (mutation.type !== 'childList') return false; - - for (const node of mutation.addedNodes) { - if (node.nodeType === Node.ELEMENT_NODE) { - if (node.querySelector && node.textContent.includes('Contributors')) { - return true; - } - } - } - return false; - }); - } - - async enhance() { - if (this.enhancementInProgress) { - Logger.debug('Enhancement already in progress, skipping'); - return; - } - - try { - this.enhancementInProgress = true; - - const contributorsSection = this.findContributorsSection(); - if (!contributorsSection) { - Logger.debug('Contributors section not found'); - return; - } - - // Check if already enhanced - if (contributorsSection.querySelector('.github-enhancer-contributors')) { - Logger.debug('Contributors section already enhanced'); - return; - } - - const contributorItems = Array.from(contributorsSection.querySelectorAll('li')); - if (contributorItems.length === 0) { - Logger.debug('No contributor items found'); - return; - } - - Logger.info(`Found ${contributorItems.length} contributors to enhance`); - - // Create enhanced container - const enhancedContainer = this.createEnhancedContainer(); - - // Process contributors in batches - const maxCards = this.settings.maxCards || 10; - const itemsToProcess = contributorItems.slice(0, maxCards); - - for (let i = 0; i < itemsToProcess.length; i += 3) { - const batch = itemsToProcess.slice(i, i + 3); - await Promise.all(batch.map(item => this.processContributor(item, enhancedContainer))); - } - - // Insert enhanced section - if (enhancedContainer.children.length === 0) { - Logger.debug('No contributor cards created, skipping insertion'); - return; - } - - // Try multiple insertion strategies - let inserted = false; - - // Strategy 1: Look for original list (ul) - const originalList = contributorsSection.querySelector('ul'); - if (originalList) { - Logger.debug('Found original ul list, inserting after it'); - originalList.parentNode.insertBefore(enhancedContainer, originalList.nextSibling); - this.addToggleFunctionality(originalList, enhancedContainer); - inserted = true; - } - - // Strategy 2: Look for other common container patterns - if (!inserted) { - const containerSelectors = [ - '.BorderGrid-cell', - '.Box-body', - '.repository-content', - '[data-testid="contributors"]' - ]; - - for (const selector of containerSelectors) { - const container = contributorsSection.querySelector(selector); - if (container) { - Logger.debug(`Found container with selector ${selector}, appending enhanced section`); - container.appendChild(enhancedContainer); - inserted = true; - break; - } - } - } - - // Strategy 3: Direct append to contributors section - if (!inserted) { - Logger.debug('Using fallback: appending directly to contributors section'); - contributorsSection.appendChild(enhancedContainer); - inserted = true; - } - - if (inserted) { - Logger.info(`Successfully enhanced ${enhancedContainer.children.length} contributors`); - } else { - Logger.warn('Failed to insert enhanced section after all strategies'); - } - - } catch (error) { - this.handleError(error, 'Contributor enhancement'); - } finally { - this.enhancementInProgress = false; - } - } - - findContributorsSection() { - // Try multiple strategies to find contributors section - - // Strategy 1: Look for BorderGrid-row with Contributors text - const borderGridRows = document.querySelectorAll('.BorderGrid-row'); - for (const row of borderGridRows) { - const text = row.textContent || ''; - if (text.includes('Contributors') || text.includes('contributors')) { - return row; - } - } - - // Strategy 2: Look for specific contributor selectors - const contributorSelectors = [ - '[data-testid="contributors"]', - '.js-contributors-graph', - '#contributors', - '.contributor-grid', - '.contributors-section' - ]; - - for (const selector of contributorSelectors) { - const element = document.querySelector(selector); - if (element) { - return element; - } - } - - // Strategy 3: Look for headings containing "Contributors" - const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); - for (const heading of headings) { - const text = heading.textContent || ''; - if (text.includes('Contributors') || text.includes('contributors')) { - // Return the parent section - return heading.closest('.BorderGrid-row') || - heading.closest('.Box') || - heading.parentElement; - } - } - - // Strategy 4: Look for any element with contributor-related text - const allElements = document.querySelectorAll('*'); - for (const element of allElements) { - if (element.children.length > 0) continue; // Skip parent elements - const text = element.textContent || ''; - if (text.trim().toLowerCase() === 'contributors') { - return element.closest('.BorderGrid-row') || - element.closest('.Box') || - element.parentElement; - } - } - - Logger.debug('Contributors section not found with any strategy'); - return null; - } - - createEnhancedContainer() { - const container = document.createElement('div'); - container.className = 'github-enhancer-contributors'; - container.style.cssText = ` - margin-top: 16px; - display: flex; - flex-wrap: wrap; - gap: 16px; - justify-content: flex-start; - align-items: flex-start; - `; - - return container; - } - - async processContributor(item, container) { - try { - // Try multiple selectors to find the link - let link = item.querySelector('a'); - - // If no direct link, maybe the item itself is a link - if (!link && item.tagName === 'A') { - link = item; - } - - // Try to find link in parent or child elements - if (!link) { - link = item.closest('a') || item.parentElement?.querySelector('a'); - } - - if (!link) { - Logger.debug('No link found in contributor item, skipping'); - return; - } - - const href = link.getAttribute('href'); - if (!href) { - Logger.debug('No href found in contributor link, skipping'); - return; - } - - // Extract username from href - const username = href.split('/').filter(part => part).pop(); - if (!username) { - Logger.debug('Could not extract username from href:', href); - return; - } - - const avatar = item.querySelector('img') || link.querySelector('img'); - - Logger.debug(`Processing contributor: ${username}`); - - // Create card immediately with basic info - const card = this.createContributorCard(username, avatar?.src); - - if (!card) { - Logger.warn('Failed to create card for', username); - return; - } - - Logger.debug(`Created card for ${username}, appending to container`); - container.appendChild(card); - - Logger.debug(`Container now has ${container.children.length} children`); - - // Fetch additional data using hovercard API - try { - const hovercardData = await this.fetchHovercardData(username); - this.enhanceCard(card, hovercardData); - } catch (hovercardError) { - Logger.debug(`Failed to fetch hovercard data for ${username}:`, hovercardError); - // Card is still displayed with basic info - } - - } catch (error) { - Logger.warn(`Failed to process contributor: ${error.message}`, error); - } - } - - createContributorCard(username, avatarSrc) { - // Detect dark theme - const isDarkTheme = document.documentElement.getAttribute('data-color-mode') === 'dark' || - document.documentElement.getAttribute('data-dark-theme') === 'dark' || - document.body.classList.contains('dark') || - getComputedStyle(document.body).backgroundColor === 'rgb(13, 17, 23)'; - - const card = document.createElement('div'); - card.className = 'github-enhancer-contributor-card'; - - const cardStyles = isDarkTheme ? { - background: 'linear-gradient(145deg, #161b22 0%, #0d1117 100%)', - border: '1px solid #30363d', - boxShadow: '0 4px 12px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.05)', - hoverShadow: '0 8px 25px rgba(88, 166, 255, 0.15), 0 4px 12px rgba(0, 0, 0, 0.6)', - textColor: '#f0f6fc', - secondaryColor: '#8b949e', - accentColor: '#58a6ff' - } : { - background: 'linear-gradient(145deg, #ffffff 0%, #f6f8fa 100%)', - border: '1px solid #d0d7de', - boxShadow: '0 4px 12px rgba(0, 0, 0, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.8)', - hoverShadow: '0 8px 25px rgba(9, 105, 218, 0.12), 0 4px 12px rgba(0, 0, 0, 0.1)', - textColor: '#24292f', - secondaryColor: '#656d76', - accentColor: '#0969da' - }; - - card.style.cssText = ` - width: 300px; - min-width: 300px; - background: ${cardStyles.background}; - border: ${cardStyles.border}; - border-radius: 12px; - padding: 20px; - box-shadow: ${cardStyles.boxShadow}; - cursor: pointer; - transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); - position: relative; - display: block; - visibility: visible; - overflow: hidden; - `; - - // Store theme info for hover effects - card._isDarkTheme = isDarkTheme; - card._cardStyles = cardStyles; - - // Add background elements first - this.addBackgroundEffects(card, isDarkTheme); - - // Header with avatar and glassmorphism effect - const header = document.createElement('div'); - header.style.cssText = ` - display: flex; - align-items: center; - margin-bottom: 16px; - position: relative; - z-index: 10; - `; - - // Avatar with modern styling - if (avatarSrc) { - const avatarContainer = document.createElement('div'); - avatarContainer.style.cssText = ` - position: relative; - margin-right: 12px; - `; - - const avatar = document.createElement('img'); - avatar.src = avatarSrc; - avatar.alt = `${username} avatar`; - avatar.style.cssText = ` - width: 52px; - height: 52px; - border-radius: 50%; - border: 3px solid ${isDarkTheme ? 'rgba(88, 166, 255, 0.3)' : 'rgba(9, 105, 218, 0.3)'}; - box-shadow: 0 4px 12px rgba(0, 0, 0, ${isDarkTheme ? '0.3' : '0.1'}); - transition: all 0.3s ease; - background: ${isDarkTheme ? '#21262d' : '#ffffff'}; - padding: 2px; - `; - - // Glowing ring effect - const ring = document.createElement('div'); - ring.style.cssText = ` - position: absolute; - top: -3px; - left: -3px; - right: -3px; - bottom: -3px; - border-radius: 50%; - background: ${isDarkTheme ? - 'linear-gradient(45deg, #58a6ff, #bc8cff, #58a6ff)' : - 'linear-gradient(45deg, #0969da, #7c3aed, #0969da)'}; - opacity: 0; - transition: all 0.3s ease; - z-index: -1; - filter: blur(2px); - `; - - avatarContainer.appendChild(ring); - avatarContainer.appendChild(avatar); - header.appendChild(avatarContainer); - - card._avatar = avatar; - card._ring = ring; - } - - // User info section - const userInfo = document.createElement('div'); - userInfo.style.cssText = ` - flex: 1; - min-width: 0; - `; - - // Username with style - const usernameEl = document.createElement('div'); - usernameEl.textContent = `@${username}`; - usernameEl.style.cssText = ` - font-size: 16px; - font-weight: 700; - color: ${cardStyles.textColor}; - margin-bottom: 4px; - transition: all 0.3s ease; - background: ${isDarkTheme ? - 'linear-gradient(90deg, #f0f6fc, #58a6ff)' : - 'linear-gradient(90deg, #24292f, #0969da)'}; - -webkit-background-clip: text; - -webkit-text-fill-color: transparent; - background-clip: text; - `; - - // Modern badge - const badge = document.createElement('span'); - badge.textContent = 'Contributor'; - badge.style.cssText = ` - display: inline-block; - background: ${isDarkTheme ? - 'linear-gradient(135deg, #238636, #2ea043)' : - 'linear-gradient(135deg, #0969da, #0550ae)'}; - color: white; - font-size: 10px; - font-weight: 600; - padding: 4px 8px; - border-radius: 12px; - text-transform: uppercase; - letter-spacing: 0.5px; - box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); - position: relative; - overflow: hidden; - `; - - // Badge shine effect - const shine = document.createElement('div'); - shine.style.cssText = ` - position: absolute; - top: 0; - left: -100%; - width: 100%; - height: 100%; - background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent); - transition: left 0.5s ease; - `; - badge.appendChild(shine); - - userInfo.appendChild(usernameEl); - userInfo.appendChild(badge); - header.appendChild(userInfo); - card.appendChild(header); - - card._badge = badge; - card._shine = shine; - - - // Details container with glassmorphism - const details = document.createElement('div'); - details.className = 'contributor-details'; - details.style.cssText = ` - background: ${isDarkTheme ? - 'rgba(48, 54, 61, 0.3)' : - 'rgba(255, 255, 255, 0.7)'}; - backdrop-filter: blur(10px); - border: 1px solid ${isDarkTheme ? - 'rgba(240, 246, 252, 0.1)' : - 'rgba(0, 0, 0, 0.1)'}; - border-radius: 8px; - padding: 12px; - font-size: 12px; - color: ${cardStyles.secondaryColor}; - line-height: 1.5; - margin-top: 8px; - transition: all 0.3s ease; - position: relative; - z-index: 10; - `; - card.appendChild(details); - - // Click to visit profile - card.addEventListener('click', (e) => { - e.preventDefault(); - e.stopPropagation(); - window.open(`https://github.com/${username}`, '_blank'); - }); - - // Modern hover efektleri - const handleMouseEnter = () => { - try { - // Ana kart efektleri - card.style.transform = 'translateY(-8px) scale(1.02)'; - card.style.boxShadow = card._cardStyles.hoverShadow; - card.style.borderColor = cardStyles.accentColor; - - // Avatar efektleri - if (card._avatar) { - card._avatar.style.transform = 'scale(1.1)'; - card._avatar.style.borderColor = cardStyles.accentColor; - } - - // Ring glow efekti - if (card._ring) { - card._ring.style.opacity = '1'; - } - - // Badge shine efekti - if (card._shine) { - card._shine.style.left = '100%'; - } - - // Details glassmorphism gรผรงlendirme - const details = card.querySelector('.contributor-details'); - if (details) { - details.style.background = isDarkTheme ? - 'rgba(88, 166, 255, 0.1)' : - 'rgba(9, 105, 218, 0.05)'; - details.style.borderColor = cardStyles.accentColor; - } - - // Background pattern efektleri - if (card._bgPattern) { - card._bgPattern.style.opacity = '1'; - card._bgPattern.style.transform = 'scale(1.08)'; - } - - if (card._meshOverlay) { - card._meshOverlay.style.opacity = '1'; - card._meshOverlay.style.filter = 'brightness(1.2) contrast(1.1)'; - } - - } catch (error) { - Logger.warn('Hover enter error:', error); - } - }; - - const handleMouseLeave = () => { - try { - // Ana kart normal hale - card.style.transform = 'translateY(0) scale(1)'; - card.style.boxShadow = card._cardStyles.boxShadow; - card.style.borderColor = cardStyles.border.split(' ')[2]; - - // Avatar normal hale - if (card._avatar) { - card._avatar.style.transform = 'scale(1)'; - card._avatar.style.borderColor = isDarkTheme ? 'rgba(88, 166, 255, 0.3)' : 'rgba(9, 105, 218, 0.3)'; - } - - // Ring gizle - if (card._ring) { - card._ring.style.opacity = '0'; - } - - // Shine reset - if (card._shine) { - setTimeout(() => { - card._shine.style.left = '-100%'; - }, 200); - } - - // Details normal hale - const details = card.querySelector('.contributor-details'); - if (details) { - details.style.background = isDarkTheme ? - 'rgba(48, 54, 61, 0.3)' : - 'rgba(255, 255, 255, 0.7)'; - details.style.borderColor = isDarkTheme ? - 'rgba(240, 246, 252, 0.1)' : - 'rgba(0, 0, 0, 0.1)'; - } - - // Background pattern normal hale - if (card._bgPattern) { - card._bgPattern.style.opacity = '0.8'; - card._bgPattern.style.transform = 'scale(1)'; - } - - if (card._meshOverlay) { - card._meshOverlay.style.opacity = '1'; - card._meshOverlay.style.filter = 'brightness(1) contrast(1)'; - } - - } catch (error) { - Logger.warn('Hover leave error:', error); - } - }; - - card.addEventListener('mouseenter', handleMouseEnter); - card.addEventListener('mouseleave', handleMouseLeave); - - return card; - } - - addBackgroundEffects(card, isDarkTheme) { - // Animated background patterns - const bgPattern = document.createElement('div'); - bgPattern.style.cssText = ` - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - opacity: 0.9; - pointer-events: none; - z-index: 1; - overflow: hidden; - border-radius: 12px; - transition: all 0.3s ease; - animation: patternPulse 8s ease-in-out infinite; - `; - - // Floating orbs - daha fazla ve daha dinamik - for (let i = 0; i < 5; i++) { - const orb = document.createElement('div'); - const size = 15 + Math.random() * 35; - const delay = Math.random() * 6; - const duration = 5 + Math.random() * 8; - - orb.style.cssText = ` - position: absolute; - width: ${size}px; - height: ${size}px; - border-radius: 50%; - background: ${isDarkTheme ? - `radial-gradient(circle, rgba(88, 166, 255, ${0.7 + Math.random() * 0.3}), rgba(188, 140, 255, ${0.3 + Math.random() * 0.3}))` : - `radial-gradient(circle, rgba(9, 105, 218, ${0.5 + Math.random() * 0.3}), rgba(124, 58, 237, ${0.2 + Math.random() * 0.2}))`}; - top: ${Math.random() * 100}%; - left: ${Math.random() * 100}%; - animation: float-${i % 3} ${duration}s ease-in-out infinite, orbGlow ${3 + Math.random() * 4}s ease-in-out infinite; - animation-delay: ${delay}s, ${delay + 1}s; - filter: blur(${0.5 + Math.random()}px); - box-shadow: 0 0 ${size/2}px ${isDarkTheme ? 'rgba(88, 166, 255, 0.4)' : 'rgba(9, 105, 218, 0.3)'}; - `; - - bgPattern.appendChild(orb); - } - - // Geometric shapes - const triangle = document.createElement('div'); - triangle.style.cssText = ` - position: absolute; - top: 10%; - right: 15%; - width: 0; - height: 0; - border-left: 8px solid transparent; - border-right: 8px solid transparent; - border-bottom: 14px solid ${isDarkTheme ? - 'rgba(88, 166, 255, 0.4)' : - 'rgba(9, 105, 218, 0.35)'}; - animation: rotate 8s linear infinite; - transform-origin: center; - `; - - const circle = document.createElement('div'); - circle.style.cssText = ` - position: absolute; - bottom: 20%; - left: 10%; - width: 12px; - height: 12px; - border: 2px solid ${isDarkTheme ? - 'rgba(188, 140, 255, 0.5)' : - 'rgba(124, 58, 237, 0.45)'}; - border-radius: 50%; - animation: pulse 3s ease-in-out infinite; - `; - - bgPattern.appendChild(triangle); - bgPattern.appendChild(circle); - - // Gradient mesh overlay - const meshOverlay = document.createElement('div'); - meshOverlay.style.cssText = ` - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - background: ${isDarkTheme ? ` - radial-gradient(circle at 20% 30%, rgba(88, 166, 255, 0.04) 0%, transparent 50%), - radial-gradient(circle at 80% 70%, rgba(188, 140, 255, 0.04) 0%, transparent 50%), - radial-gradient(circle at 40% 80%, rgba(46, 160, 67, 0.03) 0%, transparent 50%) - ` : ` - radial-gradient(circle at 20% 30%, rgba(9, 105, 218, 0.03) 0%, transparent 50%), - radial-gradient(circle at 80% 70%, rgba(124, 58, 237, 0.03) 0%, transparent 50%), - radial-gradient(circle at 40% 80%, rgba(40, 167, 69, 0.02) 0%, transparent 50%) - `}; - pointer-events: none; - z-index: 0; - border-radius: 12px; - animation: meshMove 12s ease-in-out infinite, meshGlow 6s ease-in-out infinite; - transition: opacity 0.3s ease; - opacity: 1; - `; - - // Add background elements to card - card.appendChild(meshOverlay); - card.appendChild(bgPattern); - - // CSS animations - const style = document.createElement('style'); - style.textContent = ` - @keyframes float-0 { - 0%, 100% { transform: translate(0, 0) rotate(0deg) scale(1); } - 33% { transform: translate(15px, -12px) rotate(120deg) scale(1.1); } - 66% { transform: translate(-8px, 8px) rotate(240deg) scale(0.9); } - } - @keyframes float-1 { - 0%, 100% { transform: translate(0, 0) rotate(0deg) scale(1); } - 25% { transform: translate(-12px, -8px) rotate(90deg) scale(1.2); } - 50% { transform: translate(-15px, -20px) rotate(180deg) scale(0.8); } - 75% { transform: translate(5px, -10px) rotate(270deg) scale(1.1); } - } - @keyframes float-2 { - 0%, 100% { transform: translate(0, 0) rotate(0deg) scale(1); } - 20% { transform: translate(18px, 12px) rotate(72deg) scale(1.3); } - 40% { transform: translate(-10px, 20px) rotate(144deg) scale(0.7); } - 60% { transform: translate(8px, -15px) rotate(216deg) scale(1.1); } - 80% { transform: translate(-12px, -8px) rotate(288deg) scale(0.9); } - } - @keyframes rotate { - from { transform: rotate(0deg) scale(1); } - 50% { transform: rotate(180deg) scale(1.1); } - to { transform: rotate(360deg) scale(1); } - } - @keyframes pulse { - 0%, 100% { transform: scale(1); opacity: 0.7; } - 25% { transform: scale(1.3); opacity: 0.9; } - 50% { transform: scale(1.5); opacity: 1; } - 75% { transform: scale(1.2); opacity: 0.8; } - } - @keyframes meshMove { - 0%, 100% { transform: translate(0, 0) rotate(0deg); } - 25% { transform: translate(3px, -3px) rotate(1deg); } - 50% { transform: translate(-2px, 4px) rotate(-1deg); } - 75% { transform: translate(2px, -2px) rotate(0.5deg); } - } - @keyframes patternPulse { - 0%, 100% { opacity: 0.9; transform: scale(1); } - 50% { opacity: 1; transform: scale(1.03); } - } - @keyframes meshGlow { - 0%, 100% { filter: brightness(1) contrast(1); } - 33% { filter: brightness(1.1) contrast(1.05); } - 66% { filter: brightness(0.95) contrast(0.98); } - } - @keyframes orbGlow { - 0%, 100% { - opacity: 1; - filter: blur(0.5px) brightness(1.1); - transform: scale(1); - } - 25% { - opacity: 1; - filter: blur(1px) brightness(1.3); - transform: scale(1.1); - } - 50% { - opacity: 1; - filter: blur(1.5px) brightness(1.5); - transform: scale(1.2); - } - 75% { - opacity: 1; - filter: blur(1px) brightness(1.2); - transform: scale(1.05); - } - } - `; - - if (!document.head.querySelector('#contributor-card-animations')) { - style.id = 'contributor-card-animations'; - document.head.appendChild(style); - } - - card._bgPattern = bgPattern; - card._meshOverlay = meshOverlay; - } - - async fetchHovercardData(username) { - const cacheKey = `hovercard_${username}`; - - // Check cache first - const cached = this.cache.get(cacheKey); - if (cached && Date.now() - cached.timestamp < this.cacheExpiry) { - return cached.data; - } - - try { - // Get repository ID from meta tag - const repositoryId = this.getRepositoryId(); - if (!repositoryId) { - throw new Error('Repository ID not found'); - } - - const hovercardUrl = `https://github.com/users/${username}/hovercard`; - const params = new URLSearchParams({ - subject: `repository:${repositoryId}`, - current_path: window.location.pathname - }); - - const response = await fetch(`${hovercardUrl}?${params}`, { - headers: { - 'Accept': '*/*', - 'Accept-Language': 'en-US,en;q=0.9', - 'X-Requested-With': 'XMLHttpRequest' - }, - credentials: 'include' - }); - - if (!response.ok) { - throw new Error(`HTTP ${response.status}`); - } - - const html = await response.text(); - const data = this.parseHovercardResponse(html); - - // Cache the result - this.cache.set(cacheKey, { - data, - timestamp: Date.now() - }); - - return data; - - } catch (error) { - Logger.warn(`Failed to fetch hovercard for ${username}: ${error.message}`); - return null; - } - } - - getRepositoryId() { - const metaTag = document.querySelector('meta[name="hovercard-subject-tag"]'); - if (!metaTag) return null; - - const content = metaTag.getAttribute('content'); - const match = content.match(/repository:(\d+)/); - return match ? match[1] : null; - } - - parseHovercardResponse(html) { - const parser = new DOMParser(); - const doc = parser.parseFromString(html, 'text/html'); - - return { - name: this.extractName(doc), - commitInfo: this.extractInfo(doc, 'git-commit'), - teamInfo: this.extractInfo(doc, 'people'), - orgInfo: this.extractInfo(doc, 'organization'), - company: this.extractCompany(doc), - location: this.extractLocation(doc) - }; - } - - extractName(doc) { - const nameElement = doc.querySelector('.Truncate-text--expandable a.Link--secondary'); - return nameElement?.textContent.trim() || ''; - } - - extractInfo(doc, iconName) { - return doc.querySelector(`.octicon-${iconName}`) - ?.closest('.d-flex') - ?.textContent.trim() || ''; - } - - extractCompany(doc) { - const companyEl = doc.querySelector('[data-test-selector="profile-hovercard-company"]'); - return companyEl?.textContent.trim() || ''; - } - - extractLocation(doc) { - const locationEl = doc.querySelector('[data-test-selector="profile-hovercard-location"]'); - return locationEl?.textContent.trim() || ''; - } - - enhanceCard(card, hovercardData) { - if (!hovercardData) return; - - const details = card.querySelector('.contributor-details'); - if (!details) return; - - const cardStyles = card._cardStyles; - const infoItems = []; - - // Add real name - if (hovercardData.name) { - infoItems.push(`๐Ÿ‘ค ${hovercardData.name}`); - } - - // Add company - if (hovercardData.company && this.settings.showOrgInfo) { - infoItems.push(`๐Ÿข ${hovercardData.company}`); - } - - // Add location - if (hovercardData.location) { - infoItems.push(`๐Ÿ“ ${hovercardData.location}`); - } - - // Add commit info - if (hovercardData.commitInfo && this.settings.showCommitInfo) { - infoItems.push(`๐Ÿ’ป ${hovercardData.commitInfo}`); - } - - // Display all info items - if (infoItems.length > 0) { - details.innerHTML = infoItems.join('
'); - } - } - - - - hexToRgb(hex) { - const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); - return result ? - `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : - '9, 105, 218'; - } - - addToggleFunctionality(originalList, enhancedContainer) { - // Find or create toggle button - const contributorsSection = originalList.closest('.BorderGrid-row'); - if (!contributorsSection) return; - - let toggleButton = contributorsSection.querySelector('.github-enhancer-toggle'); - - if (!toggleButton) { - toggleButton = document.createElement('button'); - toggleButton.className = 'github-enhancer-toggle'; - toggleButton.textContent = 'Show Enhanced'; - toggleButton.style.cssText = ` - background: #0969da; - color: white; - border: none; - border-radius: 4px; - padding: 4px 8px; - font-size: 12px; - cursor: pointer; - margin-left: 8px; - `; - - const header = contributorsSection.querySelector('h2, .f5'); - if (header) { - header.appendChild(toggleButton); - } - } - - let showingEnhanced = true; - originalList.style.display = 'none'; - - toggleButton.addEventListener('click', () => { - if (showingEnhanced) { - enhancedContainer.style.display = 'none'; - originalList.style.display = ''; - toggleButton.textContent = 'Show Enhanced'; - } else { - enhancedContainer.style.display = ''; - originalList.style.display = 'none'; - toggleButton.textContent = 'Show Original'; - } - showingEnhanced = !showingEnhanced; - }); - } - - insertContributorStyles() { - if (document.getElementById('github-enhancer-contributor-styles')) return; - - const style = document.createElement('style'); - style.id = 'github-enhancer-contributor-styles'; - style.textContent = ` - .github-enhancer-contributor-card:hover { - transform: translateY(-2px) !important; - box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important; - } - - .github-enhancer-toggle:hover { - background: #0860ca !important; - } - - @media (prefers-color-scheme: dark) { - .github-enhancer-contributor-card { - background: #21262d !important; - border-color: #30363d !important; - } - } - `; - document.head.appendChild(style); - } - - cleanup() { - this.enhancementInProgress = false; - this.cache.clear(); - this.stopObserving(); - } - } - - return ContributorEnhancerClass; -})(); - -window.ContributorEnhancer = ContributorEnhancer; \ No newline at end of file diff --git a/src/enhancers/date-enhancer.js b/src/enhancers/date-enhancer.js deleted file mode 100644 index 0ce8105..0000000 --- a/src/enhancers/date-enhancer.js +++ /dev/null @@ -1,1246 +0,0 @@ -/** - * Date Enhancer for GitHub Enhancer - * Enhances relative time elements with full date/time display - */ - -const DateEnhancer = (() => { - const { BaseEnhancer } = window; - const { Logger, DOMUtils, DateUtils } = window; - const { SELECTORS } = window.GITHUB_ENHANCER_CONSTANTS; - - class DateEnhancerClass extends BaseEnhancer { - constructor(name = 'DateEnhancer') { - super(name, { - debounceDelay: 100, - batchSize: 20 - }); - } - - /** - * Setup date enhancer - */ - async setup() { - Logger.debug(`Setting up ${this.name}`); - this.insertDateEnhancerStyles(); - - // ฤฐlk enhancement - await this.enhance(); - - // GitHub'ฤฑn SPA navigation'ฤฑ iรงin ekstra listener'lar - this.setupNavigationListeners(); - } - - /** - * Setup listeners for GitHub's SPA navigation - */ - setupNavigationListeners() { - // GitHub'ฤฑn turbo navigation'ฤฑ iรงin - document.addEventListener('turbo:load', () => { - setTimeout(() => this.enhance(), 500); - }); - - // Popstate events iรงin - window.addEventListener('popstate', () => { - setTimeout(() => this.enhance(), 500); - }); - - // URL deฤŸiลŸikliklerini dinle - let currentUrl = window.location.href; - const urlObserver = new MutationObserver(() => { - if (window.location.href !== currentUrl) { - currentUrl = window.location.href; - setTimeout(() => this.enhance(), 1000); - } - }); - - urlObserver.observe(document.body, { - childList: true, - subtree: true - }); - } - - /** - * Insert CSS styles for date enhancer - */ - insertDateEnhancerStyles() { - const existingStyle = document.getElementById('github-enhancer-date-styles'); - if (existingStyle) return; - - const style = document.createElement('style'); - style.id = 'github-enhancer-date-styles'; - style.textContent = ` - /* Date Enhancer Animations */ - @keyframes slideIn { - from { - opacity: 0; - transform: translateY(-10px); - } - to { - opacity: 1; - transform: translateY(0); - } - } - - @keyframes pulse { - 0%, 100% { - opacity: 1; - } - 50% { - opacity: 0.7; - } - } - - @keyframes glow { - 0%, 100% { - box-shadow: 0 0 5px rgba(88, 166, 255, 0.3); - } - 50% { - box-shadow: 0 0 20px rgba(88, 166, 255, 0.6); - } - } - - @keyframes ripple { - 0% { - transform: scale(0); - opacity: 1; - } - 100% { - transform: scale(2); - opacity: 0; - } - } - - @keyframes float { - 0%, 100% { - transform: translateY(0); - } - 50% { - transform: translateY(-1px); - } - } - - /* Enhanced Date Elements */ - .github-enhancer-date-enhanced { - position: relative !important; - z-index: 1 !important; - } - - .github-enhancer-date-enhanced:hover .github-enhancer-modern-tooltip { - opacity: 1 !important; - visibility: visible !important; - } - - /* Ultra modern date badges - perfect alignment */ - .modern-date-badge { - animation: float 6s ease-in-out infinite; - will-change: transform; - display: inline-flex !important; - vertical-align: baseline !important; - } - - .modern-date-badge:hover { - animation-play-state: paused; - } - - .ultra-modern-icon { - animation: iconPulse 2s ease-in-out infinite; - } - - @keyframes iconPulse { - 0%, 100% { - transform: scale(1); - opacity: 1; - } - 50% { - transform: scale(1.1); - opacity: 0.8; - } - } - - /* Performance optimizations */ - .modern-date-badge * { - will-change: transform, opacity; - } - - /* Detail popup styling */ - .github-enhancer-date-detail { - animation: slideIn 0.2s ease !important; - } - - /* Responsive design for mobile */ - @media (max-width: 768px) { - .github-enhancer-date-enhanced { - font-size: 0.8rem !important; - padding: 3px 6px !important; - } - - .github-enhancer-date-tooltip { - font-size: 11px !important; - padding: 6px 8px !important; - } - } - - /* High contrast mode support */ - @media (prefers-contrast: high) { - .github-enhancer-date-enhanced { - border-width: 2px !important; - font-weight: 600 !important; - } - } - - /* Reduced motion support */ - @media (prefers-reduced-motion: reduce) { - .github-enhancer-date-enhanced, - .github-enhancer-date-enhanced *, - .github-enhancer-date-detail { - animation: none !important; - transition: none !important; - } - } - `; - - document.head.appendChild(style); - Logger.debug('Date enhancer styles inserted'); - } - - /** - * Check if should enhance based on mutations - */ - shouldEnhance(mutations) { - return mutations.some(mutation => { - if (mutation.type !== 'childList') return false; - - // Check if any added nodes contain relative-time elements - for (const node of mutation.addedNodes) { - if (node.nodeType === Node.ELEMENT_NODE) { - if (node.matches && node.matches('relative-time')) return true; - if (node.querySelector && node.querySelector('relative-time')) return true; - } - } - return false; - }); - } - - /** - * Main enhancement method - */ - async enhance() { - try { - this.startPerformanceTimer('dateEnhancement'); - - // GitHub'ฤฑn AJAX navigation'ฤฑ iรงin ekstra bekleme - await this.waitForPageLoad(); - - // Find all relative-time elements that haven't been enhanced - const relativeTimeElements = DOMUtils.safeQueryAll(SELECTORS.RELATIVE_TIME) - .filter(element => !BaseEnhancer.isElementEnhanced(element, this.name)); - - if (relativeTimeElements.length === 0) { - Logger.debug('No new relative-time elements found'); - // Retry mechanism with backoff - if (!this.retryCount) this.retryCount = 0; - if (this.retryCount < 3) { - this.retryCount++; - setTimeout(() => this.enhance(), 1000 * this.retryCount); - } else { - this.retryCount = 0; // Reset for next page - } - return; - } - - Logger.debug(`Found ${relativeTimeElements.length} relative-time elements to enhance`); - - // Process elements in batches - await this.processBatch(relativeTimeElements, this.enhanceElement.bind(this)); - - Logger.debug(`Enhanced ${relativeTimeElements.length} relative-time elements`); - - // Reset retry count on success - this.retryCount = 0; - - this.endPerformanceTimer('dateEnhancement'); - - // Dispatch completion event - this.dispatchEvent(window.GITHUB_ENHANCER_CONSTANTS.EVENT_TYPES.ENHANCEMENT_COMPLETE, { - action: 'date_enhancement', - count: relativeTimeElements.length - }); - - } catch (error) { - this.handleError(error, 'Date enhancement'); - } - } - - /** - * Wait for page to be fully loaded - */ - async waitForPageLoad() { - return new Promise((resolve) => { - if (document.readyState === 'complete') { - resolve(); - } else { - window.addEventListener('load', resolve, { once: true }); - } - }); - } - - /** - * Enhance a single relative-time element - */ - async enhanceElement(element) { - try { - // Skip if already enhanced - if (BaseEnhancer.isElementEnhanced(element, this.name)) { - return; - } - - // Get the datetime attribute - const dateTimeAttr = element.getAttribute('datetime'); - if (!dateTimeAttr) { - Logger.warn('relative-time element missing datetime attribute', element); - return; - } - - // Parse the date - const date = DateUtils.parseGitHubDateTime(dateTimeAttr); - const now = new Date(); - - // Calculate time difference - const timeDiff = now - date; - const isRecent = timeDiff < 24 * 60 * 60 * 1000; // Less than 24 hours - const isVeryRecent = timeDiff < 60 * 60 * 1000; // Less than 1 hour - - // Format the date according to user locale - const locale = this.settings.locale || 'en-US'; - const formattedDate = DateUtils.formatDateTime(date, locale); - const relativeTime = this.getRelativeTimeString(date); - - // Detect theme - const isDarkTheme = this.detectDarkTheme(); - - // Create enhanced date element - sadece text olarak - const enhancedElement = this.createSimpleEnhancedDate( - element, - date, - formattedDate, - isRecent, - isVeryRecent, - isDarkTheme - ); - - // Replace the original element with smooth transition - this.replaceWithAnimation(element, enhancedElement); - - // Mark as enhanced - BaseEnhancer.markElementEnhanced(enhancedElement, this.name); - - Logger.debug(`Enhanced date element: ${dateTimeAttr} -> ${formattedDate}`); - - } catch (error) { - Logger.logError(error, { - context: `Enhancing date element`, - element: element.outerHTML - }); - } - } - - /** - * Calculate age-based opacity for fading effect - */ - getAgeOpacity(date) { - const now = new Date(); - const diffInMinutes = Math.floor((now - date) / (1000 * 60)); - - // Test iรงin dakika bazฤฑnda hesapla (daha kolay test edilebilir) - if (diffInMinutes < 30) return 1.0; // %100 - Son 30 dakika - if (diffInMinutes < 120) return 0.9; // %90 - Son 2 saat - if (diffInMinutes < 1440) return 0.75; // %75 - Son 24 saat - if (diffInMinutes < 10080) return 0.6; // %60 - Son hafta - return 0.45; // %45 - Daha eski - } - - /** - * Create modern enhanced date element with beautiful design - */ - createSimpleEnhancedDate(originalElement, date, formattedDate, isRecent, isVeryRecent, isDarkTheme) { - const container = document.createElement('div'); - container.className = 'github-enhancer-date-enhanced modern-date-badge'; - - // Tarih ve saati gรถster - const dateText = this.formatSimpleDate(date); - - // ฤฐkon ekle - const icon = this.createModernIcon(date, isRecent, isVeryRecent, isDarkTheme); - const textSpan = document.createElement('span'); - textSpan.textContent = dateText; - textSpan.className = 'date-text'; - textSpan.style.cssText = ` - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - flex: 1; - min-width: 0; - `; - - if (icon) container.appendChild(icon); - container.appendChild(textSpan); - - // Ultra modern design - sabit boyutlar - const colors = this.getUltraModernColors(isDarkTheme, isRecent, isVeryRecent, date); - const ageOpacity = this.getAgeOpacity(date); - - // Debug: opacity deฤŸerini console'a yazdฤฑr - console.log(`Date: ${date.toISOString()}, Age Opacity: ${ageOpacity}`); - - container.style.cssText = ` - display: inline-flex; - align-items: center; - justify-content: flex-start; - gap: 6px; - padding: 4px 8px; - height: 24px; - max-width: 120px; - min-width: 80px; - border-radius: 12px; - background: ${colors.background}; - border: none; - box-shadow: ${colors.shadow}; - cursor: pointer; - font-weight: 600; - font-size: 0.65rem; - line-height: 1; - color: ${colors.text}; - transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94); - position: relative; - overflow: hidden; - white-space: nowrap; - text-transform: uppercase; - letter-spacing: 0.2px; - vertical-align: baseline; - margin: 0 1px; - top: 0; - transform: translateY(0); - box-sizing: border-box; - text-overflow: ellipsis; - `; - - // BaลŸlangฤฑรง opacity'sini ayarla - CSS'ten sonra - container.style.setProperty('opacity', ageOpacity, 'important'); - - // Ekstra gรผvenlik iรงin attribute olarak da ekle - container.setAttribute('data-age-opacity', ageOpacity); - - // Animated shine effect - const gradientOverlay = document.createElement('div'); - gradientOverlay.className = 'shine-overlay'; - gradientOverlay.style.cssText = ` - position: absolute; - top: -50%; - left: -50%; - width: 200%; - height: 200%; - background: linear-gradient(45deg, transparent 30%, rgba(255, 255, 255, 0.3) 50%, transparent 70%); - opacity: 0; - transition: all 0.6s cubic-bezier(0.25, 0.46, 0.45, 0.94); - transform: translateX(-100%) rotate(45deg); - z-index: 1; - pointer-events: none; - `; - container.appendChild(gradientOverlay); - - // Opacity deฤŸerlerini saklayalฤฑm - const baseOpacity = ageOpacity; - const hoverOpacity = Math.min(ageOpacity + 0.2, 1.0); - - // Minimal hover effects - container iรงinde kalฤฑr - container.addEventListener('mouseenter', () => { - container.style.transform = 'translateY(-1px) scale(1.02)'; - container.style.boxShadow = colors.hoverShadow; - container.style.background = colors.hoverGradient; - container.style.setProperty('opacity', hoverOpacity, 'important'); // Hover'da biraz daha parlak - gradientOverlay.style.opacity = '0.15'; - gradientOverlay.style.transform = 'translateX(0) rotate(45deg)'; - tooltip.style.opacity = '1'; - tooltip.style.visibility = 'visible'; - tooltip.style.transform = 'translateX(-50%) translateY(-3px)'; - }); - - container.addEventListener('mouseleave', () => { - container.style.transform = 'translateY(0) scale(1)'; - container.style.boxShadow = colors.shadow; - container.style.background = colors.background; - container.style.setProperty('opacity', baseOpacity, 'important'); // Normal opacity'ye geri dรถn - gradientOverlay.style.opacity = '0'; - gradientOverlay.style.transform = 'translateX(-100%) rotate(45deg)'; - tooltip.style.opacity = '0'; - tooltip.style.visibility = 'hidden'; - tooltip.style.transform = 'translateX(-50%) translateY(0)'; - }); - - // Opacity'yi zorla ayarla - baลŸka CSS kurallarฤฑ override etmesin diye - setTimeout(() => { - container.style.setProperty('opacity', ageOpacity, 'important'); - }, 50); - - // Modern tooltip - const tooltip = this.createModernTooltip(date, formattedDate, isDarkTheme); - container.appendChild(tooltip); - - // Click handler with ripple effect - container.addEventListener('click', (e) => { - e.preventDefault(); - this.createRippleEffect(e, container); - setTimeout(() => { - this.showDateDetails(date, formattedDate, container); - }, 150); - }); - - return container; - } - - /** - * Get ultra modern color scheme - maviden griye yumuลŸak geรงiลŸ - */ - getUltraModernColors(isDarkTheme, isRecent, isVeryRecent, date) { - // YaลŸ bazlฤฑ renk geรงiลŸi hesapla - const ageColors = this.calculateAgeBasedColors(date, isDarkTheme); - - if (isDarkTheme) { - if (isVeryRecent) { - // ร‡ok yeni - Parlak yeลŸil - return { - background: 'linear-gradient(145deg, #00ff88, #00cc6a)', - text: '#000000', - shadow: '0 8px 32px rgba(0, 255, 136, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.3)', - hoverShadow: '0 12px 48px rgba(0, 255, 136, 0.8), inset 0 1px 0 rgba(255, 255, 255, 0.4)', - hoverGradient: 'linear-gradient(145deg, #00ff88, #00e673)' - }; - } else { - // YaลŸ bazlฤฑ mavi-gri geรงiลŸ - return { - background: `linear-gradient(145deg, ${ageColors.primary}, ${ageColors.secondary})`, - text: ageColors.text, - shadow: `0 8px 32px ${ageColors.shadowColor}, inset 0 1px 0 ${ageColors.insetColor}`, - hoverShadow: `0 12px 48px ${ageColors.hoverShadowColor}, inset 0 1px 0 ${ageColors.hoverInsetColor}`, - hoverGradient: `linear-gradient(145deg, ${ageColors.hoverPrimary}, ${ageColors.hoverSecondary})` - }; - } - } else { - if (isVeryRecent) { - // ร‡ok yeni - Parlak yeลŸil - return { - background: 'linear-gradient(145deg, #00ff88, #00cc6a)', - text: '#000000', - shadow: '0 8px 32px rgba(0, 255, 136, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.6)', - hoverShadow: '0 12px 48px rgba(0, 255, 136, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.8)', - hoverGradient: 'linear-gradient(145deg, #00ff88, #00e673)' - }; - } else { - // YaลŸ bazlฤฑ mavi-gri geรงiลŸ - return { - background: `linear-gradient(145deg, ${ageColors.primary}, ${ageColors.secondary})`, - text: ageColors.text, - shadow: `0 8px 32px ${ageColors.shadowColor}, inset 0 1px 0 ${ageColors.insetColor}`, - hoverShadow: `0 12px 48px ${ageColors.hoverShadowColor}, inset 0 1px 0 ${ageColors.hoverInsetColor}`, - hoverGradient: `linear-gradient(145deg, ${ageColors.hoverPrimary}, ${ageColors.hoverSecondary})` - }; - } - } - } - - /** - * YaลŸ bazlฤฑ renk geรงiลŸi hesapla - maviden griye - */ - calculateAgeBasedColors(date, isDarkTheme) { - const now = new Date(); - const diffInMinutes = Math.floor((now - date) / (1000 * 60)); - - // Renk geรงiลŸ noktalarฤฑ - let blueToGrayRatio; - if (diffInMinutes < 30) blueToGrayRatio = 0.0; // %100 mavi - else if (diffInMinutes < 120) blueToGrayRatio = 0.2; // %80 mavi, %20 gri - else if (diffInMinutes < 1440) blueToGrayRatio = 0.5; // %50 mavi, %50 gri - else if (diffInMinutes < 10080) blueToGrayRatio = 0.8; // %20 mavi, %80 gri - else blueToGrayRatio = 1.0; // %100 gri - - if (isDarkTheme) { - // Dark theme renk geรงiลŸi - const blueColor = { r: 0, g: 153, b: 255 }; // #0099ff - const grayColor = { r: 64, g: 64, b: 64 }; // #404040 - - const blueColorSecondary = { r: 0, g: 119, b: 204 }; // #0077cc - const grayColorSecondary = { r: 42, g: 42, b: 42 }; // #2a2a2a - - // Renk interpolasyonu - const primary = this.interpolateColor(blueColor, grayColor, blueToGrayRatio); - const secondary = this.interpolateColor(blueColorSecondary, grayColorSecondary, blueToGrayRatio); - - return { - primary: `rgb(${primary.r}, ${primary.g}, ${primary.b})`, - secondary: `rgb(${secondary.r}, ${secondary.g}, ${secondary.b})`, - text: blueToGrayRatio > 0.5 ? '#cccccc' : '#ffffff', - shadowColor: `rgba(${primary.r}, ${primary.g}, ${primary.b}, ${0.5 * (1 - blueToGrayRatio * 0.5)})`, - insetColor: `rgba(255, 255, 255, ${0.25 * (1 - blueToGrayRatio * 0.5)})`, - hoverShadowColor: `rgba(${primary.r}, ${primary.g}, ${primary.b}, ${0.7 * (1 - blueToGrayRatio * 0.5)})`, - hoverInsetColor: `rgba(255, 255, 255, ${0.35 * (1 - blueToGrayRatio * 0.5)})`, - hoverPrimary: `rgb(${Math.min(255, primary.r + 10)}, ${Math.min(255, primary.g + 10)}, ${Math.min(255, primary.b + 10)})`, - hoverSecondary: `rgb(${Math.min(255, secondary.r + 15)}, ${Math.min(255, secondary.g + 15)}, ${Math.min(255, secondary.b + 15)})` - }; - } else { - // Light theme renk geรงiลŸi - const blueColor = { r: 0, g: 153, b: 255 }; // #0099ff - const grayColor = { r: 245, g: 245, b: 245 }; // #f5f5f5 - - const blueColorSecondary = { r: 0, g: 119, b: 204 }; // #0077cc - const grayColorSecondary = { r: 224, g: 224, b: 224 }; // #e0e0e0 - - // Renk interpolasyonu - const primary = this.interpolateColor(blueColor, grayColor, blueToGrayRatio); - const secondary = this.interpolateColor(blueColorSecondary, grayColorSecondary, blueToGrayRatio); - - return { - primary: `rgb(${primary.r}, ${primary.g}, ${primary.b})`, - secondary: `rgb(${secondary.r}, ${secondary.g}, ${secondary.b})`, - text: blueToGrayRatio > 0.5 ? '#888888' : '#ffffff', - shadowColor: `rgba(${primary.r}, ${primary.g}, ${primary.b}, ${0.35 * (1 - blueToGrayRatio * 0.5)})`, - insetColor: `rgba(255, 255, 255, ${0.5 + blueToGrayRatio * 0.4})`, - hoverShadowColor: `rgba(${primary.r}, ${primary.g}, ${primary.b}, ${0.5 * (1 - blueToGrayRatio * 0.5)})`, - hoverInsetColor: `rgba(255, 255, 255, ${0.7 + blueToGrayRatio * 0.3})`, - hoverPrimary: `rgb(${Math.max(0, primary.r - 10)}, ${Math.max(0, primary.g - 10)}, ${Math.max(0, primary.b - 10)})`, - hoverSecondary: `rgb(${Math.max(0, secondary.r - 15)}, ${Math.max(0, secondary.g - 15)}, ${Math.max(0, secondary.b - 15)})` - }; - } - } - - /** - * ฤฐki renk arasฤฑnda interpolasyon - */ - interpolateColor(color1, color2, ratio) { - return { - r: Math.round(color1.r + (color2.r - color1.r) * ratio), - g: Math.round(color1.g + (color2.g - color1.g) * ratio), - b: Math.round(color1.b + (color2.b - color1.b) * ratio) - }; - } - - /** - * Create ultra modern icon - geometrik ลŸekiller - */ - createModernIcon(date, isRecent, isVeryRecent, isDarkTheme) { - const now = new Date(); - const timeDiff = now - date; - const hours = Math.floor(timeDiff / (1000 * 60 * 60)); - const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24)); - - const icon = document.createElement('div'); - icon.className = 'ultra-modern-icon'; - - let shape = ''; - let bgColor = 'rgba(255, 255, 255, 0.2)'; - - if (hours < 1) { - // ร‡ok yeni - parlayan diamond - shape = 'โ—†'; - bgColor = 'rgba(255, 255, 255, 0.4)'; - } else if (hours < 24) { - // Yeni - triangle - shape = 'โ–ฒ'; - bgColor = 'rgba(255, 255, 255, 0.3)'; - } else if (days < 7) { - // Bu hafta - circle - shape = 'โ—'; - bgColor = 'rgba(255, 255, 255, 0.2)'; - } else if (days < 30) { - // Bu ay - square - shape = 'โ– '; - bgColor = 'rgba(255, 255, 255, 0.15)'; - } else { - // Eski - small circle - shape = 'โ—‹'; - bgColor = 'rgba(255, 255, 255, 0.1)'; - } - - icon.style.cssText = ` - width: 14px; - height: 14px; - display: flex; - align-items: center; - justify-content: center; - font-size: 7px; - border-radius: 50%; - background: ${bgColor}; - color: currentColor; - flex-shrink: 0; - transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94); - backdrop-filter: blur(4px); - border: 1px solid rgba(255, 255, 255, 0.2); - font-weight: bold; - line-height: 1; - `; - - icon.textContent = shape; - return icon; - } - - /** - * Format date as simple readable format - */ - formatSimpleDate(date) { - const now = new Date(); - const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); - const dateOnly = new Date(date.getFullYear(), date.getMonth(), date.getDate()); - - const diffInDays = Math.floor((today - dateOnly) / (1000 * 60 * 60 * 24)); - - if (diffInDays === 0) { - // Bugรผn - sadece saat gรถster - return date.toLocaleTimeString('en-US', { - hour: '2-digit', - minute: '2-digit', - hour12: false - }); - } else if (diffInDays === 1) { - // Dรผn - kฤฑsa format - return `Ytd ${date.toLocaleTimeString('en-US', { - hour: '2-digit', - minute: '2-digit', - hour12: false - })}`; - } else if (diffInDays < 7) { - // Bu hafta - gรผn ismi + saat - return `${date.toLocaleDateString('en-US', { weekday: 'short' })} ${date.toLocaleTimeString('en-US', { - hour: '2-digit', - minute: '2-digit', - hour12: false - })}`; - } else if (diffInDays < 30) { - // Bu ay - kฤฑsa format - return `${date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} ${date.toLocaleTimeString('en-US', { - hour: '2-digit', - minute: '2-digit', - hour12: false - })}`; - } else { - // Daha eski - sadece tarih - return date.toLocaleDateString('en-US', { - month: 'short', - day: 'numeric', - year: diffInDays > 365 ? '2-digit' : undefined - }); - } - } - - /** - * Create modern tooltip with glassmorphism - */ - createModernTooltip(date, formattedDate, isDarkTheme) { - const tooltip = document.createElement('div'); - tooltip.className = 'github-enhancer-modern-tooltip'; - - const colors = isDarkTheme ? { - background: 'rgba(22, 27, 34, 0.95)', - border: 'rgba(88, 166, 255, 0.3)', - text: '#f0f6fc', - accent: '#58a6ff' - } : { - background: 'rgba(255, 255, 255, 0.95)', - border: 'rgba(9, 105, 218, 0.3)', - text: '#24292f', - accent: '#0969da' - }; - - tooltip.style.cssText = ` - position: absolute; - bottom: calc(100% + 8px); - left: 50%; - transform: translateX(-50%); - background: ${colors.background}; - color: ${colors.text}; - padding: 12px 16px; - border-radius: 12px; - border: 1px solid ${colors.border}; - font-size: 13px; - font-weight: 500; - white-space: nowrap; - opacity: 0; - visibility: hidden; - transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); - z-index: 99999; - box-shadow: 0 8px 32px rgba(0, 0, 0, ${isDarkTheme ? '0.4' : '0.15'}), - 0 0 0 1px rgba(255, 255, 255, ${isDarkTheme ? '0.05' : '0.1'}); - backdrop-filter: blur(12px); - pointer-events: none; - min-width: 200px; - max-width: 300px; - text-align: center; - `; - - // Tooltip content with icon - const content = document.createElement('div'); - content.innerHTML = ` -
- ๐Ÿ“… - Full Date & Time -
-
${formattedDate}
-
${this.getTimeZoneInfo(date)}
- `; - tooltip.appendChild(content); - - // Arrow - const arrow = document.createElement('div'); - arrow.style.cssText = ` - position: absolute; - top: 100%; - left: 50%; - transform: translateX(-50%); - width: 0; - height: 0; - border-left: 8px solid transparent; - border-right: 8px solid transparent; - border-top: 8px solid ${colors.background}; - filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1)); - `; - tooltip.appendChild(arrow); - - return tooltip; - } - - /** - * Create ripple effect on click - */ - createRippleEffect(event, container) { - const ripple = document.createElement('div'); - const rect = container.getBoundingClientRect(); - const size = Math.max(rect.width, rect.height); - const x = event.clientX - rect.left - size / 2; - const y = event.clientY - rect.top - size / 2; - - ripple.style.cssText = ` - position: absolute; - width: ${size}px; - height: ${size}px; - left: ${x}px; - top: ${y}px; - background: radial-gradient(circle, rgba(255, 255, 255, 0.6) 0%, transparent 70%); - border-radius: 50%; - transform: scale(0); - animation: ripple 0.6s ease-out; - pointer-events: none; - z-index: 1; - `; - - container.appendChild(ripple); - - // Remove ripple after animation - setTimeout(() => { - ripple.remove(); - }, 600); - } - - /** - * OLD METHOD - artฤฑk kullanฤฑlmฤฑyor - */ - createEnhancedDateElement(originalElement, date, formattedDate, relativeTime, isRecent, isVeryRecent, isDarkTheme) { - const container = document.createElement('span'); - container.className = 'github-enhancer-date-enhanced'; - - // Theme-based colors - const colors = isDarkTheme ? { - primary: '#f0f6fc', - secondary: '#8b949e', - accent: '#58a6ff', - recentGlow: 'rgba(88, 166, 255, 0.3)', - veryRecentGlow: 'rgba(46, 160, 67, 0.4)', - background: 'rgba(22, 27, 34, 0.8)', - border: 'rgba(240, 246, 252, 0.1)' - } : { - primary: '#24292f', - secondary: '#656d76', - accent: '#0969da', - recentGlow: 'rgba(9, 105, 218, 0.2)', - veryRecentGlow: 'rgba(26, 127, 55, 0.3)', - background: 'rgba(255, 255, 255, 0.9)', - border: 'rgba(0, 0, 0, 0.1)' - }; - - // Create the main display element - const mainDisplay = document.createElement('span'); - mainDisplay.className = 'github-enhancer-date-main'; - mainDisplay.textContent = relativeTime; - - // Base styling - daha minimal ve tutarlฤฑ - container.style.cssText = ` - position: relative; - display: inline-flex; - align-items: center; - gap: 4px; - padding: 2px 6px; - border-radius: 4px; - background: ${isDarkTheme ? 'rgba(22, 27, 34, 0.6)' : 'rgba(255, 255, 255, 0.8)'}; - border: 1px solid ${isDarkTheme ? 'rgba(88, 166, 255, 0.2)' : 'rgba(9, 105, 218, 0.2)'}; - transition: all 0.2s ease; - cursor: pointer; - font-weight: 500; - font-size: inherit; - color: ${colors.primary}; - box-shadow: none; - z-index: 1; - min-width: fit-content; - white-space: nowrap; - `; - - // Add subtle indicators for recent dates - if (isVeryRecent) { - container.style.borderColor = isDarkTheme ? '#2ea043' : '#1a7f37'; - container.style.backgroundColor = isDarkTheme ? 'rgba(46, 160, 67, 0.1)' : 'rgba(26, 127, 55, 0.05)'; - } else if (isRecent) { - container.style.borderColor = isDarkTheme ? '#58a6ff' : '#0969da'; - container.style.backgroundColor = isDarkTheme ? 'rgba(88, 166, 255, 0.1)' : 'rgba(9, 105, 218, 0.05)'; - } - - // Add icon based on time period - const icon = this.createTimeIcon(date, isDarkTheme); - if (icon) { - container.appendChild(icon); - } - - container.appendChild(mainDisplay); - - // Add subtle hover effects - container.addEventListener('mouseenter', () => { - container.style.opacity = '0.8'; - container.style.transform = 'translateY(-1px)'; - }); - - container.addEventListener('mouseleave', () => { - container.style.opacity = '1'; - container.style.transform = 'translateY(0)'; - }); - - // Create tooltip - const tooltip = this.createTooltip(date, formattedDate, isDarkTheme); - container.appendChild(tooltip); - - // Add click handler for additional info - container.addEventListener('click', (e) => { - e.preventDefault(); - this.showDateDetails(date, formattedDate, container); - }); - - return container; - } - - /** - * Create time-based icon - sadece รงok yeni olanlar iรงin - */ - createTimeIcon(date, isDarkTheme) { - const now = new Date(); - const timeDiff = now - date; - const hours = Math.floor(timeDiff / (1000 * 60 * 60)); - - // Sadece รงok yeni aktiviteler iรงin ikon gรถster - if (hours >= 1) return null; - - const icon = document.createElement('span'); - icon.style.cssText = ` - width: 8px; - height: 8px; - border-radius: 50%; - background: ${isDarkTheme ? '#2ea043' : '#1a7f37'}; - display: inline-block; - opacity: 0.8; - flex-shrink: 0; - `; - icon.title = 'Very recent activity'; - - return icon; - } - - /** - * Create tooltip element - */ - createTooltip(date, formattedDate, isDarkTheme) { - const tooltip = document.createElement('div'); - tooltip.className = 'github-enhancer-date-tooltip'; - - const colors = isDarkTheme ? { - background: '#161b22', - text: '#f0f6fc', - border: '#30363d' - } : { - background: '#ffffff', - text: '#24292f', - border: '#d0d7de' - }; - - tooltip.style.cssText = ` - position: absolute; - top: -40px; - left: 50%; - transform: translateX(-50%); - background: ${colors.background}; - color: ${colors.text}; - padding: 6px 8px; - border-radius: 4px; - border: 1px solid ${colors.border}; - font-size: 11px; - white-space: nowrap; - opacity: 0; - visibility: hidden; - transition: all 0.2s ease; - z-index: 999; - box-shadow: 0 2px 8px rgba(0, 0, 0, ${isDarkTheme ? '0.3' : '0.1'}); - pointer-events: none; - `; - - // Add arrow - const arrow = document.createElement('div'); - arrow.style.cssText = ` - position: absolute; - top: 100%; - left: 50%; - transform: translateX(-50%); - width: 0; - height: 0; - border-left: 6px solid transparent; - border-right: 6px solid transparent; - border-top: 6px solid ${colors.background}; - `; - tooltip.appendChild(arrow); - - // Tooltip content - const content = document.createElement('div'); - content.innerHTML = ` -
${formattedDate}
-
${this.getTimeZoneInfo(date)}
- `; - tooltip.appendChild(content); - - return tooltip; - } - - /** - * Show/hide tooltip on hover - */ - setupTooltipEvents(container) { - const tooltip = container.querySelector('.github-enhancer-date-tooltip'); - if (!tooltip) return; - - container.addEventListener('mouseenter', () => { - tooltip.style.opacity = '1'; - tooltip.style.visibility = 'visible'; - }); - - container.addEventListener('mouseleave', () => { - tooltip.style.opacity = '0'; - tooltip.style.visibility = 'hidden'; - }); - } - - /** - * Replace element with smooth animation - */ - replaceWithAnimation(oldElement, newElement) { - // Set initial state for animation - newElement.style.opacity = '0'; - newElement.style.transform = 'translateY(10px)'; - - // Replace element - oldElement.parentNode.replaceChild(newElement, oldElement); - - // Animate in - requestAnimationFrame(() => { - newElement.style.transition = 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)'; - newElement.style.opacity = '1'; - newElement.style.transform = 'translateY(0)'; - }); - - // Setup tooltip events - this.setupTooltipEvents(newElement); - } - - /** - * Get relative time string - */ - getRelativeTimeString(date) { - const now = new Date(); - const diffInSeconds = Math.floor((now - date) / 1000); - - if (diffInSeconds < 60) return 'just now'; - if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}m ago`; - if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}h ago`; - if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}d ago`; - if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)}mo ago`; - return `${Math.floor(diffInSeconds / 31536000)}y ago`; - } - - /** - * Get timezone info - */ - getTimeZoneInfo(date) { - const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; - return `${timeZone} โ€ข ${date.toLocaleString('en-US', { weekday: 'long' })}`; - } - - /** - * Detect dark theme - */ - detectDarkTheme() { - return document.documentElement.getAttribute('data-color-mode') === 'dark' || - document.documentElement.getAttribute('data-dark-theme') === 'dark' || - document.body.classList.contains('dark') || - getComputedStyle(document.body).backgroundColor === 'rgb(13, 17, 23)'; - } - - /** - * Show detailed date information - */ - showDateDetails(date, formattedDate, container) { - // Create a temporary detailed view - const existingDetail = document.querySelector('.github-enhancer-date-detail'); - if (existingDetail) { - existingDetail.remove(); - return; - } - - const detail = document.createElement('div'); - detail.className = 'github-enhancer-date-detail'; - - // Container'ฤฑn pozisyonunu al - const rect = container.getBoundingClientRect(); - const scrollTop = window.pageYOffset || document.documentElement.scrollTop; - const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft; - - // Popup boyutlarฤฑ (tahmini) - const popupWidth = 300; - const popupHeight = 200; - - // Ekran boyutlarฤฑ - const viewportWidth = window.innerWidth; - const viewportHeight = window.innerHeight; - - // Akฤฑllฤฑ pozisyonlama - let top = rect.bottom + scrollTop + 8; - let left = rect.left + scrollLeft; - - // SaฤŸ tarafta yer yoksa sola kaydฤฑr - if (left + popupWidth > viewportWidth) { - left = Math.max(10, viewportWidth - popupWidth - 10); - } - - // Alt tarafta yer yoksa รผste konumlandฤฑr - if (rect.bottom + popupHeight > viewportHeight) { - top = rect.top + scrollTop - popupHeight - 8; - } - - // Minimum margin'ler - left = Math.max(10, left); - top = Math.max(10, top); - - detail.style.cssText = ` - position: absolute; - top: ${top}px; - left: ${left}px; - background: ${this.detectDarkTheme() ? '#161b22' : '#ffffff'}; - border: 1px solid ${this.detectDarkTheme() ? '#30363d' : '#d0d7de'}; - border-radius: 12px; - padding: 16px; - box-shadow: 0 8px 32px rgba(0, 0, 0, ${this.detectDarkTheme() ? '0.4' : '0.15'}), - 0 0 0 1px rgba(255, 255, 255, ${this.detectDarkTheme() ? '0.05' : '0.1'}); - backdrop-filter: blur(12px); - z-index: 99999; - min-width: 280px; - max-width: 320px; - font-size: 13px; - animation: slideIn 0.2s ease; - color: ${this.detectDarkTheme() ? '#f0f6fc' : '#24292f'}; - `; - - const now = new Date(); - const diffInMs = now - date; - const diffInDays = Math.floor(diffInMs / (1000 * 60 * 60 * 24)); - - detail.innerHTML = ` -
- ๐Ÿ“… Date Details -
-
Full Date: ${formattedDate}
-
Days Ago: ${diffInDays}
-
ISO: ${date.toISOString()}
-
Unix: ${Math.floor(date.getTime() / 1000)}
-
- Click anywhere to close -
- `; - - document.body.appendChild(detail); - - // Close on click outside - setTimeout(() => { - document.addEventListener('click', function closeDetail(e) { - if (!detail.contains(e.target)) { - detail.remove(); - document.removeEventListener('click', closeDetail); - } - }); - }, 100); - } - - /** - * Check if enhancement is applicable to current page - */ - shouldObserve() { - // Date enhancement is useful on most GitHub pages - const supportedPages = [ - 'repository', - 'file_browser', - 'commit', - 'pull_request', - 'issue', - 'home' - ]; - - // This would need to be passed from the main script - // For now, assume it's always applicable - return super.shouldObserve(); - } - - /** - * Clean up enhanced elements - */ - cleanup() { - try { - // Find and revert enhanced elements - const enhancedElements = DOMUtils.safeQueryAll(`[data-${this.name}-enhanced="true"]`); - - enhancedElements.forEach(element => { - const originalDateTime = element.getAttribute('data-original-date'); - if (originalDateTime) { - // Create a new relative-time element - const relativeTimeElement = DOMUtils.createElement('relative-time', { - attributes: { - datetime: originalDateTime - }, - textContent: DateUtils.getRelativeTimeString(originalDateTime) - }); - - // Replace enhanced element with original - element.parentNode.replaceChild(relativeTimeElement, element); - } - }); - - Logger.debug(`Cleaned up ${enhancedElements.length} enhanced date elements`); - } catch (error) { - Logger.logError(error, { context: 'Date enhancer cleanup' }); - } - - super.cleanup(); - } - } - - return DateEnhancerClass; -})(); - -// Global availability -window.DateEnhancer = DateEnhancer; \ No newline at end of file diff --git a/src/enhancers/file-size-enhancer.js b/src/enhancers/file-size-enhancer.js deleted file mode 100644 index dd9b6fd..0000000 --- a/src/enhancers/file-size-enhancer.js +++ /dev/null @@ -1,447 +0,0 @@ -/** - * File Size Enhancer for GitHub Enhancer - * Displays file sizes in repository file listings - */ - -const FileSizeEnhancer = (() => { - const { BaseEnhancer } = window; - const { Logger, DOMUtils, APIUtils, Storage } = window; - const { SELECTORS } = window.GITHUB_ENHANCER_CONSTANTS; - - class FileSizeEnhancerClass extends BaseEnhancer { - constructor(name = 'FileSizeEnhancer') { - super(name, { - debounceDelay: 200, - batchSize: 10 - }); - - this.sizeCache = new Map(); - this.processingQueue = new Set(); - } - - /** - * Setup file size enhancer - */ - async setup() { - Logger.debug(`Setting up ${this.name}`); - - // Add custom CSS for file size indicators - this.insertFileSizeStyles(); - } - - /** - * Check if should enhance based on mutations - */ - shouldEnhance(mutations) { - // Only enhance on repository and file browser pages - const path = window.location.pathname; - if (!path.match(/^\/[^\/]+\/[^\/]+/) || path.includes('/issues') || path.includes('/pull')) { - return false; - } - - return mutations.some(mutation => { - if (mutation.type !== 'childList') return false; - - // Check if file rows were added - for (const node of mutation.addedNodes) { - if (node.nodeType === Node.ELEMENT_NODE) { - if (node.matches && node.matches(SELECTORS.FILE_ROWS)) return true; - if (node.querySelector && node.querySelector(SELECTORS.FILE_ROWS)) return true; - } - } - return false; - }); - } - - /** - * Main enhancement method - */ - async enhance() { - try { - this.startPerformanceTimer('fileSizeEnhancement'); - - // Find file rows that haven't been enhanced - const fileRows = DOMUtils.safeQueryAll(SELECTORS.FILE_ROWS) - .filter(row => !BaseEnhancer.isElementEnhanced(row, this.name)); - - if (fileRows.length === 0) { - Logger.debug('No new file rows found'); - return; - } - - Logger.debug(`Found ${fileRows.length} file rows to enhance`); - - // Get repository information - const repoInfo = APIUtils.getRepoInfo(); - if (!repoInfo) { - Logger.warn('Could not get repository information'); - return; - } - - // Process file rows in batches - await this.processBatch(fileRows, (row) => this.enhanceFileRow(row, repoInfo)); - - Logger.debug(`Enhanced ${fileRows.length} file rows with size information`); - - this.endPerformanceTimer('fileSizeEnhancement'); - - // Dispatch completion event - this.dispatchEvent(window.GITHUB_ENHANCER_CONSTANTS.EVENT_TYPES.ENHANCEMENT_COMPLETE, { - action: 'file_size_enhancement', - count: fileRows.length - }); - - } catch (error) { - this.handleError(error, 'File size enhancement'); - } - } - - /** - * Enhance a single file row with size information - */ - async enhanceFileRow(row, repoInfo) { - try { - // Skip if already enhanced - if (BaseEnhancer.isElementEnhanced(row, this.name)) { - return; - } - - // Extract file information from the row - const fileInfo = this.extractFileInfo(row); - if (!fileInfo) { - Logger.debug('Could not extract file info from row'); - return; - } - - // Skip if already processing - const cacheKey = `${repoInfo.owner}/${repoInfo.repo}/${fileInfo.path}`; - if (this.processingQueue.has(cacheKey)) { - return; - } - - this.processingQueue.add(cacheKey); - - try { - // Get file size - const size = await this.getFileSize(repoInfo, fileInfo); - - if (size !== null) { - // Create and insert size indicator - const sizeIndicator = this.createSizeIndicator(size, fileInfo.isDirectory); - this.insertSizeIndicator(row, sizeIndicator, fileInfo); - - // Mark as enhanced - BaseEnhancer.markElementEnhanced(row, this.name); - - Logger.debug(`Enhanced file row: ${fileInfo.path} (${this.formatFileSize(size)})`); - } - } finally { - this.processingQueue.delete(cacheKey); - } - - } catch (error) { - Logger.logError(error, { - context: `Enhancing file row`, - row: row.outerHTML.substring(0, 200) - }); - } - } - - /** - * Extract file information from a file row - */ - extractFileInfo(row) { - try { - // Try to find the file name element - const fileNameElement = row.querySelector('.react-directory-filename-column a, [data-testid="file-name-link"]'); - if (!fileNameElement) { - return null; - } - - const fileName = fileNameElement.textContent.trim(); - const href = fileNameElement.getAttribute('href') || ''; - - // Determine if it's a directory - const isDirectory = row.querySelector('.icon-directory, [data-testid="directory-icon"]') !== null; - - // Extract path from href - let path = ''; - const pathMatch = href.match(/\/blob\/[^\/]+\/(.+)$/) || href.match(/\/tree\/[^\/]+\/(.+)$/); - if (pathMatch) { - path = pathMatch[1]; - } else { - path = fileName; - } - - return { - name: fileName, - path: path, - isDirectory: isDirectory, - href: href - }; - - } catch (error) { - Logger.logError(error, { context: 'Extracting file info' }); - return null; - } - } - - /** - * Get file size from GitHub API - */ - async getFileSize(repoInfo, fileInfo) { - try { - const cacheKey = `size_${repoInfo.owner}_${repoInfo.repo}_${fileInfo.path}`; - - // Try cache first - const cached = await Storage.cache.get(cacheKey); - if (cached !== null) { - return cached; - } - - let size; - - if (fileInfo.isDirectory) { - // For directories, calculate total size of contents - size = await this.getDirectorySize(repoInfo, fileInfo.path); - } else { - // For files, get individual file size - size = await this.getIndividualFileSize(repoInfo, fileInfo.path); - } - - // Cache the result - if (size !== null) { - await Storage.cache.set(cacheKey, size, 15 * 60 * 1000); // 15 minutes - } - - return size; - - } catch (error) { - Logger.logError(error, { context: `Getting file size for ${fileInfo.path}` }); - return null; - } - } - - /** - * Get individual file size - */ - async getIndividualFileSize(repoInfo, filePath) { - try { - const fileData = await APIUtils.github.getRepoContents( - repoInfo.owner, - repoInfo.repo, - filePath, - repoInfo.branch || 'main' - ); - - return fileData.size || 0; - - } catch (error) { - if (error.statusCode === 404) { - Logger.debug(`File not found: ${filePath}`); - return 0; - } - throw error; - } - } - - /** - * Get directory size (sum of all files) - */ - async getDirectorySize(repoInfo, dirPath) { - try { - const contents = await APIUtils.github.getRepoContents( - repoInfo.owner, - repoInfo.repo, - dirPath, - repoInfo.branch || 'main' - ); - - if (!Array.isArray(contents)) { - return 0; - } - - // Sum up sizes of all files (not directories) - let totalSize = 0; - for (const item of contents) { - if (item.type === 'file' && item.size) { - totalSize += item.size; - } - } - - return totalSize; - - } catch (error) { - if (error.statusCode === 404) { - Logger.debug(`Directory not found: ${dirPath}`); - return 0; - } - throw error; - } - } - - /** - * Create size indicator element - */ - createSizeIndicator(size, isDirectory) { - const formattedSize = this.formatFileSize(size); - const sizeClass = this.getSizeClass(size); - const icon = isDirectory ? '๐Ÿ“' : '๐Ÿ“„'; - - return DOMUtils.createElement('span', { - classes: ['github-enhancer-file-size', `size-${sizeClass}`], - textContent: `${icon} ${formattedSize}`, - attributes: { - title: `${isDirectory ? 'Directory' : 'File'} size: ${formattedSize}` - }, - styles: { - fontSize: '11px', - color: '#586069', - marginLeft: '8px', - padding: '2px 6px', - borderRadius: '3px', - backgroundColor: '#f6f8fa', - border: '1px solid #e1e4e8' - } - }); - } - - /** - * Insert size indicator into file row - */ - insertSizeIndicator(row, sizeIndicator, fileInfo) { - // Find the best place to insert the size indicator - const fileNameCell = row.querySelector('.react-directory-row-name-cell-small-screen, .react-directory-filename-column'); - - if (fileNameCell) { - // Look for existing size indicator and remove it - const existingIndicator = fileNameCell.querySelector('.github-enhancer-file-size'); - if (existingIndicator) { - existingIndicator.remove(); - } - - // Append new size indicator - fileNameCell.appendChild(sizeIndicator); - } - } - - /** - * Format file size in human readable format - */ - formatFileSize(bytes) { - if (bytes === 0) return '0 B'; - - const units = ['B', 'KB', 'MB', 'GB', 'TB']; - const i = Math.floor(Math.log2(bytes) / 10); - const value = (bytes / Math.pow(1024, i)).toFixed(1); - - return `${value} ${units[i]}`; - } - - /** - * Get size class for styling - */ - getSizeClass(bytes) { - if (bytes < 1024) return 'tiny'; - if (bytes < 10 * 1024) return 'small'; - if (bytes < 100 * 1024) return 'medium'; - if (bytes < 1024 * 1024) return 'large'; - return 'huge'; - } - - /** - * Insert CSS styles for file size indicators - */ - insertFileSizeStyles() { - const css = ` - .github-enhancer-file-size { - display: inline-block; - transition: all 0.2s ease; - font-weight: 500; - } - - .github-enhancer-file-size.size-tiny { - background-color: #dcfce7; - border-color: #bbf7d0; - color: #166534; - } - - .github-enhancer-file-size.size-small { - background-color: #dbeafe; - border-color: #bfdbfe; - color: #1e40af; - } - - .github-enhancer-file-size.size-medium { - background-color: #fef3c7; - border-color: #fde68a; - color: #92400e; - } - - .github-enhancer-file-size.size-large { - background-color: #fed7aa; - border-color: #fdba74; - color: #ea580c; - } - - .github-enhancer-file-size.size-huge { - background-color: #fecaca; - border-color: #fca5a5; - color: #dc2626; - } - - .github-enhancer-file-size:hover { - transform: scale(1.05); - box-shadow: 0 2px 4px rgba(0,0,0,0.1); - } - - @media (prefers-color-scheme: dark) { - .github-enhancer-file-size { - background-color: #30363d !important; - border-color: #484f58 !important; - color: #c9d1d9 !important; - } - } - - @keyframes fadeInSize { - from { opacity: 0; transform: scale(0.8); } - to { opacity: 1; transform: scale(1); } - } - - .github-enhancer-file-size { - animation: fadeInSize 0.3s ease-in-out; - } - `; - - DOMUtils.insertCSS(css, 'github-enhancer-file-size-styles'); - } - - /** - * Cleanup enhanced file size indicators - */ - cleanup() { - try { - // Remove size indicators - const sizeIndicators = DOMUtils.safeQueryAll('.github-enhancer-file-size'); - sizeIndicators.forEach(indicator => indicator.remove()); - - // Remove styles - DOMUtils.removeElements('#github-enhancer-file-size-styles'); - - // Clear processing queue - this.processingQueue.clear(); - - Logger.debug('Cleaned up file size enhancements'); - } catch (error) { - Logger.logError(error, { context: 'File size enhancer cleanup' }); - } - - super.cleanup(); - } - } - - return FileSizeEnhancerClass; -})(); - -// Global availability -window.FileSizeEnhancer = FileSizeEnhancer; \ No newline at end of file diff --git a/src/enhancers/theme-enhancer.js b/src/enhancers/theme-enhancer.js deleted file mode 100644 index 32b3d5a..0000000 --- a/src/enhancers/theme-enhancer.js +++ /dev/null @@ -1,1214 +0,0 @@ -/** - * Theme Enhancer for GitHub - * Applies modern animations and glassmorphism effects across GitHub - */ - -const ThemeEnhancer = (() => { - const Logger = window.Logger; - const BaseEnhancer = window.BaseEnhancer; - const DOMUtils = window.DOMUtils; - - class ThemeEnhancerClass extends BaseEnhancer { - constructor(name = 'ThemeEnhancer') { - super(name); - this.isActive = false; - this.animationObserver = null; - this.styleElement = null; - this.orbContainer = null; - } - - async setup() { - Logger.info('Setting up Theme Enhancer...'); - - try { - await this.insertGlobalThemeStyles(); - await this.setupScrollAnimations(); - this.setupCursorTrail(); - this.setupStarButtonEnhancements(); - this.setupMicroInteractions(); - this.isActive = true; - Logger.info('Theme Enhancer setup completed'); - } catch (error) { - Logger.logError(error, { context: 'Theme Enhancer setup' }); - } - } - - shouldEnhance(mutations) { - if (!this.isActive) return false; - - // Check for new elements that need theme enhancement - return mutations.some(mutation => { - return mutation.addedNodes && - Array.from(mutation.addedNodes).some(node => - node.nodeType === Node.ELEMENT_NODE && - (node.matches && ( - node.matches('.js-navigation-item') || - node.matches('.Box') || - node.matches('.UnderlineNav') || - node.matches('.Header') || - node.matches('.repository-content') || - node.matches('.btn') || - node.matches('.Button') - )) - ); - }); - } - - async enhance() { - try { - Logger.debug('Running theme enhancement...'); - - this.enhanceBoxElements(); - this.enhanceNavigationItems(); - this.enhanceButtons(); - this.enhanceCards(); - this.enhanceHeaders(); - this.addFloatingElements(); - - Logger.debug('Theme enhancement completed'); - } catch (error) { - Logger.logError(error, { context: 'Theme enhancement failed' }); - } - } - - async insertGlobalThemeStyles() { - try { - // Remove existing styles if any - if (this.styleElement) { - this.styleElement.remove(); - } - - const isDarkTheme = this.detectDarkTheme(); - Logger.debug(`Theme detected: ${isDarkTheme ? 'dark' : 'light'}`); - - const css = ` - /* GitHub Enhancer Theme Styles */ - :root { - --gh-enhancer-primary: ${isDarkTheme ? '#58a6ff' : '#0969da'}; - --gh-enhancer-secondary: ${isDarkTheme ? '#bc8cff' : '#7c3aed'}; - --gh-enhancer-success: ${isDarkTheme ? '#2ea043' : '#1a7f37'}; - --gh-enhancer-glass-bg: ${isDarkTheme ? 'rgba(22, 27, 34, 0.8)' : 'rgba(255, 255, 255, 0.8)'}; - --gh-enhancer-glass-border: ${isDarkTheme ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0, 0, 0, 0.1)'}; - --gh-enhancer-shadow: ${isDarkTheme ? '0 8px 32px rgba(0, 0, 0, 0.4)' : '0 8px 32px rgba(0, 0, 0, 0.12)'}; - --gh-enhancer-glow: ${isDarkTheme ? 'rgba(88, 166, 255, 0.3)' : 'rgba(9, 105, 218, 0.3)'}; - } - - /* ๐ŸŒŒ Dynamic Floating Orbs Background - Dramatic Effect */ - body::before { - content: ''; - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: - radial-gradient(circle at 10% 20%, rgba(88, 166, 255, 0.08) 0%, transparent 40%), - radial-gradient(circle at 90% 80%, rgba(188, 140, 255, 0.06) 0%, transparent 40%), - radial-gradient(circle at 70% 30%, rgba(46, 160, 67, 0.05) 0%, transparent 35%), - radial-gradient(circle at 30% 70%, rgba(248, 81, 73, 0.07) 0%, transparent 45%), - radial-gradient(circle at 50% 10%, rgba(255, 215, 0, 0.04) 0%, transparent 30%); - animation: orbFloat1 25s ease-in-out infinite; - pointer-events: none; - z-index: 0; - } - - /* Second layer of floating orbs */ - body::after { - content: ''; - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - background: - radial-gradient(circle at 80% 10%, rgba(138, 43, 226, 0.05) 0%, transparent 35%), - radial-gradient(circle at 20% 90%, rgba(0, 255, 127, 0.04) 0%, transparent 40%), - radial-gradient(circle at 60% 60%, rgba(255, 20, 147, 0.03) 0%, transparent 30%), - radial-gradient(circle at 40% 20%, rgba(88, 166, 255, 0.06) 0%, transparent 45%); - animation: orbFloat2 30s ease-in-out infinite reverse; - pointer-events: none; - z-index: 0; - } - - @keyframes orbFloat1 { - 0%, 100% { - transform: translate(0px, 0px) scale(1); - opacity: 0.7; - } - 25% { - transform: translate(20px, -15px) scale(1.1); - opacity: 0.9; - } - 50% { - transform: translate(-10px, 10px) scale(0.9); - opacity: 0.8; - } - 75% { - transform: translate(15px, -5px) scale(1.05); - opacity: 0.85; - } - } - - @keyframes orbFloat2 { - 0%, 100% { - transform: translate(0px, 0px) scale(1) rotate(0deg); - opacity: 0.6; - } - 33% { - transform: translate(-25px, 20px) scale(1.15) rotate(120deg); - opacity: 0.8; - } - 66% { - transform: translate(10px, -25px) scale(0.85) rotate(240deg); - opacity: 0.75; - } - } - - /* ๐ŸŒŸ Interactive Cursor Trail - Binary Particles */ - .cursor-trail { - position: fixed; - font-family: 'Courier New', monospace; - font-size: 12px; - font-weight: bold; - color: rgba(0, 255, 127, 0.3); - pointer-events: none; - z-index: 9999; - text-shadow: 0 0 2px rgba(0, 255, 127, 0.15); - user-select: none; - transform-origin: center center; - } - - /* Binary trail fade animation that preserves rotation */ - .cursor-trail { - animation: binaryTrailFade 2.5s ease-out forwards; - } - - .cursor-trail.zero { - color: rgba(88, 166, 255, 0.3); - text-shadow: 0 0 2px rgba(88, 166, 255, 0.15); - } - - .cursor-trail.one { - color: rgba(0, 255, 127, 0.3); - text-shadow: 0 0 2px rgba(0, 255, 127, 0.15); - } - - .cursor-trail.matrix { - color: rgba(0, 255, 0, 0.25); - text-shadow: 0 0 2px rgba(0, 255, 0, 0.2); - font-size: 10px; - } - - .cursor-trail.cyber { - color: rgba(255, 20, 147, 0.25); - text-shadow: 0 0 2px rgba(255, 20, 147, 0.15); - font-size: 14px; - } - - @keyframes binaryTrailFade { - 0% { - opacity: 1; - transform: scale(1); - } - 25% { - opacity: 0.8; - transform: scale(1.1); - } - 70% { - opacity: 0.3; - transform: scale(0.8); - } - 100% { - opacity: 0; - transform: scale(0.3); - } - } - - /* ๐ŸŒŸ ENHANCED STAR/LIKE BUTTON ANIMATIONS */ - .btn[aria-label*="Star"], - .btn[aria-label*="Unstar"], - .btn[data-action="star"], - .btn-with-count, - [data-testid="star-button"], - .js-social-form button { - position: relative !important; - overflow: hidden !important; - transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275) !important; - background: linear-gradient(135deg, - rgba(255, 255, 255, 0.05) 0%, - rgba(255, 255, 255, 0.02) 100%) !important; - backdrop-filter: blur(10px) !important; - border: 2px solid transparent !important; - transform-style: preserve-3d !important; - } - - /* Magical glow on hover - Fixed Position */ - .btn[aria-label*="Star"]:hover, - .btn[aria-label*="Unstar"]:hover, - .btn[data-action="star"]:hover, - .btn-with-count:hover, - [data-testid="star-button"]:hover, - .js-social-form button:hover { - background: linear-gradient(135deg, - #ffd700 0%, - #ffed4e 25%, - #fff700 50%, - #ffa500 75%, - #ff8c00 100%) !important; - color: #000 !important; - border: 2px solid #ffd700 !important; - box-shadow: - 0 0 30px rgba(255, 215, 0, 0.8), - 0 0 60px rgba(255, 215, 0, 0.5), - 0 0 90px rgba(255, 215, 0, 0.3), - inset 0 0 20px rgba(255, 255, 255, 0.3) !important; - animation: starMagicGlow 1.5s ease-in-out infinite !important; - text-shadow: 0 0 10px rgba(0, 0, 0, 0.5) !important; - } - - /* Sparkle border animation */ - .btn[aria-label*="Star"]:hover::before, - .btn[data-action="star"]:hover::before, - [data-testid="star-button"]:hover::before { - content: ''; - position: absolute; - top: -3px; - left: -3px; - right: -3px; - bottom: -3px; - background: linear-gradient(45deg, - #ffd700, #ffed4e, #fff700, #ffa500, - #ff8c00, #ffd700, #ffed4e, #fff700); - background-size: 400% 400%; - border-radius: inherit; - z-index: -1; - animation: sparkleRotate 2s linear infinite; - } - - /* Click explosion effect */ - .btn[aria-label*="Star"]:active, - .btn[aria-label*="Unstar"]:active, - .btn[data-action="star"]:active { - animation: starMegaExplosion 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) !important; - transform: scale(1.2) rotateZ(15deg) !important; - } - - @keyframes starMagicGlow { - 0%, 100% { - filter: brightness(1) saturate(1); - box-shadow: - 0 0 30px rgba(255, 215, 0, 0.8), - 0 0 60px rgba(255, 215, 0, 0.5), - 0 0 90px rgba(255, 215, 0, 0.3), - inset 0 0 20px rgba(255, 255, 255, 0.3); - } - 50% { - filter: brightness(1.2) saturate(1.3); - box-shadow: - 0 0 40px rgba(255, 215, 0, 1), - 0 0 80px rgba(255, 215, 0, 0.7), - 0 0 120px rgba(255, 215, 0, 0.5), - inset 0 0 30px rgba(255, 255, 255, 0.5); - } - } - - @keyframes sparkleRotate { - 0% { background-position: 0% 50%; } - 50% { background-position: 100% 50%; } - 100% { background-position: 0% 50%; } - } - - @keyframes starMegaExplosion { - 0% { - transform: scale(1.08) rotateZ(0deg); - filter: brightness(1); - } - 25% { - transform: scale(1.3) rotateZ(5deg); - filter: brightness(1.5) saturate(2); - } - 50% { - transform: scale(1.5) rotateZ(10deg); - filter: brightness(2) saturate(3); - } - 75% { - transform: scale(1.4) rotateZ(8deg); - filter: brightness(1.3) saturate(1.5); - } - 100% { - transform: scale(1.1) rotateZ(0deg); - filter: brightness(1); - } - } - - /* Subtle floating stars on hover */ - .btn[aria-label*="Star"]:hover::after, - .btn[data-action="star"]:hover::after, - [data-testid="star-button"]:hover::after { - content: 'โœจ'; - position: absolute; - top: -25px; - left: 50%; - transform: translateX(-50%); - font-size: 12px; - opacity: 0; - animation: subtleFloatingStars 3s ease-in-out infinite; - pointer-events: none; - z-index: 10; - } - - @keyframes subtleFloatingStars { - 0% { - opacity: 0; - transform: translateX(-50%) translateY(0px) scale(0.3); - } - 50% { - opacity: 0.7; - transform: translateX(-50%) translateY(-8px) scale(0.8); - } - 100% { - opacity: 0; - transform: translateX(-50%) translateY(-15px) scale(0.3); - } - } - - /* ๐Ÿ’ซ Enhanced 3D Glassmorphism Effects */ - .Box:not(.github-enhancer-contributor-card), - .Box-row:not(.github-enhancer-contributor-card), - .Box-header:not(.github-enhancer-contributor-card) { - backdrop-filter: blur(12px) !important; - background: var(--gh-enhancer-glass-bg) !important; - border: 1px solid var(--gh-enhancer-glass-border) !important; - transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) !important; - position: relative !important; - overflow: hidden !important; - transform-style: preserve-3d !important; - } - - .Box:not(.github-enhancer-contributor-card):hover { - transform: translateY(-8px) rotateX(5deg) rotateY(-2deg) !important; - box-shadow: - var(--gh-enhancer-shadow), - 0 0 30px var(--gh-enhancer-glow) !important; - border-color: var(--gh-enhancer-primary) !important; - background: linear-gradient(135deg, - var(--gh-enhancer-glass-bg), - rgba(88, 166, 255, 0.1)) !important; - } - - /* 3D Card flip effect for repository cards */ - .Box.pinned-repo-item { - perspective: 1000px !important; - } - - .Box.pinned-repo-item:hover { - transform: rotateY(10deg) rotateX(5deg) translateZ(20px) !important; - } - - /* โšก Enhanced Buttons with 3D Effects */ - .btn, .Button { - position: relative !important; - overflow: hidden !important; - transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important; - backdrop-filter: blur(8px) !important; - transform-style: preserve-3d !important; - } - - .btn::before, .Button::before { - content: ''; - position: absolute; - top: 0; - left: -100%; - width: 100%; - height: 100%; - background: linear-gradient(90deg, - transparent, - rgba(255, 255, 255, 0.2), - transparent); - transition: left 0.5s ease; - } - - .btn:hover::before, .Button:hover::before { - left: 100%; - } - - .btn:hover, .Button:hover { - transform: translateY(-3px) translateZ(10px) !important; - box-shadow: - 0 10px 25px rgba(0, 0, 0, 0.3), - 0 0 20px var(--gh-enhancer-glow) !important; - border-color: var(--gh-enhancer-primary) !important; - } - - /* ๐ŸŽฏ Navigation with Modern Hover */ - .UnderlineNav-item, .js-navigation-item { - position: relative !important; - transition: all 0.3s ease !important; - overflow: hidden !important; - } - - .UnderlineNav-item::before, .js-navigation-item::before { - content: ''; - position: absolute; - bottom: 0; - left: 50%; - width: 0; - height: 3px; - background: linear-gradient(90deg, var(--gh-enhancer-primary), var(--gh-enhancer-secondary)); - transition: all 0.3s ease; - transform: translateX(-50%); - } - - .UnderlineNav-item:hover::before, .js-navigation-item:hover::before { - width: 100%; - } - - .UnderlineNav-item:hover, .js-navigation-item:hover { - transform: translateY(-2px); - color: var(--gh-enhancer-primary) !important; - text-shadow: 0 0 10px var(--gh-enhancer-glow); - } - - /* ๐Ÿ“ File Browser with Slide Animation */ - .react-directory-row, [data-testid="tree-view-item"] { - transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94) !important; - position: relative !important; - border-radius: 8px !important; - } - - .react-directory-row:hover, [data-testid="tree-view-item"]:hover { - background: linear-gradient(90deg, - var(--gh-enhancer-glass-bg), - rgba(88, 166, 255, 0.1)) !important; - transform: translateX(12px) scale(1.02) !important; - border-left: 4px solid var(--gh-enhancer-primary) !important; - box-shadow: 0 4px 15px rgba(88, 166, 255, 0.2) !important; - } - - /* ๐Ÿ’ฌ Comment Expand/Collapse Animations */ - .js-comment-body, .comment-body { - transition: all 0.4s ease !important; - } - - .js-comment-body.collapsed { - max-height: 100px !important; - overflow: hidden !important; - opacity: 0.7 !important; - } - - /* ๐Ÿ“ Code Folding Animations */ - .js-file-content, .highlight { - transition: all 0.3s ease !important; - } - - .js-file-content:hover, .highlight:hover { - background: var(--gh-enhancer-glass-bg) !important; - transform: translateX(4px) !important; - border-left: 3px solid var(--gh-enhancer-primary) !important; - } - - /* ๐Ÿ”ฅ Repository Header with Gradient */ - .Header, .repository-content .Box-header { - background: linear-gradient(135deg, - var(--gh-enhancer-glass-bg), - rgba(88, 166, 255, 0.05)) !important; - backdrop-filter: blur(20px) !important; - border-bottom: 1px solid var(--gh-enhancer-glass-border) !important; - position: relative !important; - } - - .Header::after, .repository-content .Box-header::after { - content: ''; - position: absolute; - top: 0; - left: 0; - right: 0; - height: 2px; - background: linear-gradient(90deg, - var(--gh-enhancer-primary), - var(--gh-enhancer-secondary), - var(--gh-enhancer-success), - var(--gh-enhancer-primary)); - background-size: 200% 100%; - animation: headerGradient 3s linear infinite; - } - - @keyframes headerGradient { - 0% { background-position: 0% 50%; } - 100% { background-position: 200% 50%; } - } - - /* ๐ŸŒŸ Enhanced Code Blocks */ - .highlight, .blob-code { - background: var(--gh-enhancer-glass-bg) !important; - backdrop-filter: blur(8px) !important; - border-radius: 8px !important; - transition: all 0.3s ease !important; - position: relative !important; - } - - .highlight:hover, .blob-code:hover { - transform: translateY(-1px) !important; - box-shadow: 0 4px 12px rgba(88, 166, 255, 0.2) !important; - border-left: 3px solid var(--gh-enhancer-primary) !important; - } - - /* โœจ Loading States */ - .github-enhancer-loading { - position: relative; - overflow: hidden; - } - - .github-enhancer-loading::before { - content: ''; - position: absolute; - top: 0; - left: -100%; - width: 100%; - height: 100%; - background: linear-gradient(90deg, - transparent, - var(--gh-enhancer-glow), - transparent); - animation: shimmer 1.5s infinite; - } - - @keyframes shimmer { - 0% { left: -100%; } - 100% { left: 100%; } - } - - /* ๐ŸŽจ Staggered Fade-in Animation */ - .github-enhancer-fade-in { - animation: fadeInUp 0.6s ease forwards; - opacity: 0; - transform: translateY(20px); - } - - .github-enhancer-fade-in:nth-child(1) { animation-delay: 0.1s; } - .github-enhancer-fade-in:nth-child(2) { animation-delay: 0.2s; } - .github-enhancer-fade-in:nth-child(3) { animation-delay: 0.3s; } - .github-enhancer-fade-in:nth-child(4) { animation-delay: 0.4s; } - .github-enhancer-fade-in:nth-child(5) { animation-delay: 0.5s; } - - @keyframes fadeInUp { - to { - opacity: 1; - transform: translateY(0); - } - } - - /* ๐Ÿ’ซ Pulse Animation for Interactive Elements */ - .github-enhancer-pulse { - animation: pulse 2s infinite; - } - - @keyframes pulse { - 0% { - box-shadow: 0 0 0 0 var(--gh-enhancer-glow); - } - 70% { - box-shadow: 0 0 0 10px transparent; - } - 100% { - box-shadow: 0 0 0 0 transparent; - } - } - - /* ๐ŸŽ† Ripple Effect Keyframes */ - @keyframes ripple { - to { - transform: scale(2); - opacity: 0; - } - } - - /* โšก Enhanced Focus States */ - *:focus { - outline: 2px solid var(--gh-enhancer-primary) !important; - outline-offset: 2px !important; - box-shadow: 0 0 0 4px var(--gh-enhancer-glow) !important; - } - - /* ๐ŸŽญ Reduce motion for accessibility */ - @media (prefers-reduced-motion: reduce) { - *, *::before, *::after { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } - } - `; - - this.styleElement = DOMUtils.insertCSS(css, 'github-enhancer-theme-styles'); - Logger.info('Theme styles inserted successfully'); - } catch (error) { - Logger.logError(error, { context: 'Inserting theme styles' }); - throw error; - } - } - - enhanceBoxElements() { - const boxes = document.querySelectorAll('.Box:not(.github-enhancer-themed):not(.github-enhancer-contributor-card)'); - boxes.forEach((box, index) => { - box.classList.add('github-enhancer-themed', 'github-enhancer-fade-in'); - box.style.animationDelay = `${index * 0.1}s`; - }); - if (boxes.length > 0) { - Logger.debug(`Enhanced ${boxes.length} box elements`); - } - } - - enhanceNavigationItems() { - const navItems = document.querySelectorAll('.js-navigation-item:not(.github-enhancer-themed), .UnderlineNav-item:not(.github-enhancer-themed)'); - navItems.forEach(item => { - item.classList.add('github-enhancer-themed'); - - // Add ripple effect on click - item.addEventListener('click', this.createRippleEffect.bind(this)); - }); - if (navItems.length > 0) { - Logger.debug(`Enhanced ${navItems.length} navigation items`); - } - } - - enhanceButtons() { - const buttons = document.querySelectorAll('.btn:not(.github-enhancer-themed), .Button:not(.github-enhancer-themed)'); - buttons.forEach(button => { - button.classList.add('github-enhancer-themed'); - - // Add pulse effect for primary buttons - if (button.classList.contains('btn-primary') || button.classList.contains('Button--primary')) { - button.classList.add('github-enhancer-pulse'); - } - - // Add ripple effect on click - button.addEventListener('click', this.createRippleEffect.bind(this)); - }); - if (buttons.length > 0) { - Logger.debug(`Enhanced ${buttons.length} buttons`); - } - } - - enhanceCards() { - const cards = document.querySelectorAll('.Box-row:not(.github-enhancer-themed):not(.github-enhancer-contributor-card)'); - cards.forEach((card, index) => { - card.classList.add('github-enhancer-themed', 'github-enhancer-fade-in'); - card.style.animationDelay = `${index * 0.05}s`; - }); - if (cards.length > 0) { - Logger.debug(`Enhanced ${cards.length} card elements`); - } - } - - enhanceHeaders() { - const headers = document.querySelectorAll('.Header:not(.github-enhancer-themed), .Box-header:not(.github-enhancer-themed)'); - headers.forEach(header => { - header.classList.add('github-enhancer-themed'); - }); - if (headers.length > 0) { - Logger.debug(`Enhanced ${headers.length} header elements`); - } - } - - addFloatingElements() { - if (this.orbContainer || document.querySelector('.github-enhancer-floating-orbs')) { - return; - } - - try { - // Create floating orbs container - this.orbContainer = document.createElement('div'); - this.orbContainer.className = 'github-enhancer-floating-orbs'; - this.orbContainer.style.cssText = ` - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; - pointer-events: none; - z-index: 1; - overflow: hidden; - `; - - const isDarkTheme = this.detectDarkTheme(); - const colors = isDarkTheme - ? ['#58a6ff', '#bc8cff', '#2ea043', '#f85149', '#ffd700', '#ff6b6b'] - : ['#0969da', '#7c3aed', '#1a7f37', '#d1242f', '#ff8c00', '#20b2aa']; - - // Create multiple types of floating elements - for (let i = 0; i < 12; i++) { - const orb = document.createElement('div'); - orb.className = 'floating-orb'; - - const size = 15 + Math.random() * 25; - const color = colors[Math.floor(Math.random() * colors.length)]; - const delay = Math.random() * 20; - const duration = 15 + Math.random() * 15; - const startX = Math.random() * 100; - const startY = Math.random() * 100; - - orb.style.cssText = ` - position: absolute; - width: ${size}px; - height: ${size}px; - background: radial-gradient(circle, ${color}20, ${color}05, transparent); - border: 1px solid ${color}30; - border-radius: 50%; - left: ${startX}%; - top: ${startY}%; - animation: floatOrb ${duration}s ease-in-out infinite; - animation-delay: ${delay}s; - box-shadow: 0 0 ${size}px ${color}15, inset 0 0 ${size/2}px ${color}10; - `; - - this.orbContainer.appendChild(orb); - } - - // Add some geometric particles - for (let i = 0; i < 8; i++) { - const particle = document.createElement('div'); - particle.className = 'floating-particle'; - - const shapes = ['square', 'triangle', 'diamond']; - const shape = shapes[Math.floor(Math.random() * shapes.length)]; - const color = colors[Math.floor(Math.random() * colors.length)]; - const size = 8 + Math.random() * 12; - const delay = Math.random() * 25; - const duration = 20 + Math.random() * 20; - - let shapeCSS = ''; - if (shape === 'square') { - shapeCSS = ` - width: ${size}px; - height: ${size}px; - background: ${color}15; - border: 1px solid ${color}25; - transform: rotate(45deg); - `; - } else if (shape === 'triangle') { - shapeCSS = ` - width: 0; - height: 0; - border-left: ${size/2}px solid transparent; - border-right: ${size/2}px solid transparent; - border-bottom: ${size}px solid ${color}20; - `; - } else { - shapeCSS = ` - width: ${size}px; - height: ${size}px; - background: ${color}10; - border: 1px solid ${color}20; - transform: rotate(45deg); - clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); - `; - } - - particle.style.cssText = ` - position: absolute; - ${shapeCSS} - left: ${Math.random() * 100}%; - top: ${Math.random() * 100}%; - animation: floatParticle ${duration}s linear infinite; - animation-delay: ${delay}s; - `; - - this.orbContainer.appendChild(particle); - } - - // Add CSS animations - const style = document.createElement('style'); - style.textContent = ` - @keyframes floatOrb { - 0%, 100% { - transform: translate(0px, 0px) scale(1); - opacity: 0.6; - } - 25% { - transform: translate(30px, -20px) scale(1.1); - opacity: 0.8; - } - 50% { - transform: translate(-20px, 15px) scale(0.9); - opacity: 0.7; - } - 75% { - transform: translate(25px, -10px) scale(1.05); - opacity: 0.75; - } - } - - @keyframes floatParticle { - 0% { - transform: translateY(100vh) rotate(0deg); - opacity: 0; - } - 10% { - opacity: 0.6; - } - 90% { - opacity: 0.3; - } - 100% { - transform: translateY(-100px) rotate(360deg); - opacity: 0; - } - } - `; - document.head.appendChild(style); - - document.body.appendChild(this.orbContainer); - Logger.debug('Enhanced floating elements added'); - } catch (error) { - Logger.logError(error, { context: 'Adding floating elements' }); - } - } - - setupCursorTrail() { - try { - let lastTrailTime = 0; - const trailDelay = 100; // Slower for binary particles - - document.addEventListener('mousemove', (e) => { - const now = Date.now(); - if (now - lastTrailTime < trailDelay) return; - - lastTrailTime = now; - - const trail = document.createElement('div'); - trail.className = 'cursor-trail'; - - // Random binary values and styles - const binaryValue = Math.random() < 0.5 ? '0' : '1'; - const styles = ['zero', 'one', 'matrix', 'cyber']; - - // Set the binary content - trail.textContent = binaryValue; - - // Random style based on binary value - if (binaryValue === '0') { - trail.classList.add(Math.random() < 0.7 ? 'zero' : 'matrix'); - } else { - trail.classList.add(Math.random() < 0.7 ? 'one' : 'cyber'); - } - - // Subtle offset for more natural feel - const offsetX = (Math.random() - 0.5) * 20; - const offsetY = (Math.random() - 0.5) * 20; - - // Random rotation between -45 and 45 degrees for better visibility - const randomRotation = (Math.random() - 0.5) * 90; // -45 to +45 degrees - - trail.style.left = (e.clientX + offsetX) + 'px'; - trail.style.top = (e.clientY + offsetY) + 'px'; - trail.style.transform = `rotate(${randomRotation}deg)`; - trail.style.transformOrigin = 'center center'; - - document.body.appendChild(trail); - - // Remove trail element after animation - setTimeout(() => { - if (trail.parentNode) { - trail.remove(); - } - }, 2500); - }); - - Logger.debug('Binary cursor trail setup completed'); - } catch (error) { - Logger.logError(error, { context: 'Setting up cursor trail' }); - } - } - - setupStarButtonEnhancements() { - try { - // Enhanced star button click effects - const starSelectors = [ - '.btn[aria-label*="Star"]', - '.btn[aria-label*="Unstar"]', - '.btn[data-action="star"]', - '[data-testid="star-button"]', - '.js-social-form button' - ]; - - starSelectors.forEach(selector => { - document.addEventListener('click', (e) => { - if (e.target.closest(selector)) { - this.createStarExplosion(e); - } - }); - }); - - Logger.debug('Star button enhancements setup completed'); - } catch (error) { - Logger.logError(error, { context: 'Setting up star button enhancements' }); - } - } - - createStarExplosion(event) { - try { - const button = event.target.closest('button, .btn'); - if (!button) return; - - // Create multiple star particles - const colors = ['#ffd700', '#ffed4e', '#fff700', '#ffa500']; - - for (let i = 0; i < 8; i++) { - const star = document.createElement('div'); - star.innerHTML = 'โญ'; - star.style.cssText = ` - position: absolute; - pointer-events: none; - z-index: 9999; - font-size: 16px; - color: ${colors[Math.floor(Math.random() * colors.length)]}; - animation: starExplosion 1s ease-out forwards; - animation-delay: ${i * 0.1}s; - `; - - const rect = button.getBoundingClientRect(); - star.style.left = (rect.left + rect.width / 2) + 'px'; - star.style.top = (rect.top + rect.height / 2) + 'px'; - - document.body.appendChild(star); - - // Random explosion direction - const angle = (i / 8) * 2 * Math.PI; - const distance = 100 + Math.random() * 50; - const finalX = Math.cos(angle) * distance; - const finalY = Math.sin(angle) * distance; - - star.style.setProperty('--final-x', finalX + 'px'); - star.style.setProperty('--final-y', finalY + 'px'); - - setTimeout(() => star.remove(), 1000); - } - - // Add explosion keyframes if not already added - if (!document.querySelector('#star-explosion-keyframes')) { - const style = document.createElement('style'); - style.id = 'star-explosion-keyframes'; - style.textContent = ` - @keyframes starExplosion { - 0% { - transform: translate(0, 0) scale(1) rotate(0deg); - opacity: 1; - } - 100% { - transform: translate(var(--final-x), var(--final-y)) scale(0) rotate(360deg); - opacity: 0; - } - } - `; - document.head.appendChild(style); - } - } catch (error) { - Logger.warn(`Star explosion error: ${error.message}`); - } - } - - setupMicroInteractions() { - try { - // Code folding hover effects - this.setupCodeFoldingEffects(); - - // Comment expand/collapse effects - this.setupCommentEffects(); - - // File tree interactions - this.setupFileTreeEffects(); - - Logger.debug('Micro-interactions setup completed'); - } catch (error) { - Logger.logError(error, { context: 'Setting up micro-interactions' }); - } - } - - setupCodeFoldingEffects() { - document.addEventListener('mouseover', (e) => { - const codeElement = e.target.closest('.highlight, .js-file-content'); - if (codeElement && !codeElement.classList.contains('github-enhancer-code-enhanced')) { - codeElement.classList.add('github-enhancer-code-enhanced'); - - // Add line number hover effects - const lines = codeElement.querySelectorAll('.js-file-line'); - lines.forEach((line, index) => { - line.addEventListener('mouseenter', () => { - line.style.background = 'rgba(88, 166, 255, 0.1)'; - line.style.borderLeft = '3px solid var(--gh-enhancer-primary)'; - line.style.transform = 'translateX(4px)'; - }); - - line.addEventListener('mouseleave', () => { - line.style.background = ''; - line.style.borderLeft = ''; - line.style.transform = ''; - }); - }); - } - }); - } - - setupCommentEffects() { - document.addEventListener('click', (e) => { - const expandButton = e.target.closest('.js-details-target'); - if (expandButton) { - const commentBody = expandButton.closest('.js-comment').querySelector('.comment-body'); - if (commentBody) { - commentBody.style.transition = 'all 0.4s ease'; - } - } - }); - } - - setupFileTreeEffects() { - document.addEventListener('mouseover', (e) => { - const fileRow = e.target.closest('.react-directory-row, [data-testid="tree-view-item"]'); - if (fileRow && !fileRow.classList.contains('github-enhancer-file-enhanced')) { - fileRow.classList.add('github-enhancer-file-enhanced'); - - // Add file type icon glow - const icon = fileRow.querySelector('.octicon'); - if (icon) { - fileRow.addEventListener('mouseenter', () => { - icon.style.filter = 'drop-shadow(0 0 8px var(--gh-enhancer-primary))'; - icon.style.transform = 'scale(1.1)'; - }); - - fileRow.addEventListener('mouseleave', () => { - icon.style.filter = ''; - icon.style.transform = ''; - }); - } - } - }); - } - - setupScrollAnimations() { - try { - // Intersection Observer for scroll animations - this.animationObserver = new IntersectionObserver((entries) => { - entries.forEach(entry => { - if (entry.isIntersecting) { - entry.target.classList.add('github-enhancer-fade-in'); - } - }); - }, { - threshold: 0.1, - rootMargin: '50px' - }); - - // Observe elements for scroll animations - const observeElements = () => { - const elements = document.querySelectorAll('.Box-row, .commit-group-title, .file-navigation'); - elements.forEach(el => { - if (!el.classList.contains('github-enhancer-observed')) { - el.classList.add('github-enhancer-observed'); - this.animationObserver.observe(el); - } - }); - }; - - observeElements(); - - // Re-observe on mutations with debounce - const debouncedObserve = DOMUtils.debounce(observeElements, 300); - const mutationObserver = new MutationObserver(debouncedObserve); - - mutationObserver.observe(document.body, { - childList: true, - subtree: true - }); - - Logger.debug('Scroll animations set up'); - } catch (error) { - Logger.logError(error, { context: 'Setting up scroll animations' }); - } - } - - createRippleEffect(event) { - try { - const button = event.currentTarget; - const rect = button.getBoundingClientRect(); - const ripple = document.createElement('span'); - - const size = Math.max(rect.width, rect.height); - const x = event.clientX - rect.left - size / 2; - const y = event.clientY - rect.top - size / 2; - - ripple.style.cssText = ` - position: absolute; - width: ${size}px; - height: ${size}px; - left: ${x}px; - top: ${y}px; - background: radial-gradient(circle, var(--gh-enhancer-glow) 0%, transparent 70%); - border-radius: 50%; - transform: scale(0); - animation: ripple 0.6s ease-out; - pointer-events: none; - z-index: 1; - `; - - button.style.position = 'relative'; - button.appendChild(ripple); - - setTimeout(() => { - if (ripple.parentNode) { - ripple.remove(); - } - }, 600); - } catch (error) { - Logger.warn(`Ripple effect error: ${error.message}`); - } - } - - detectDarkTheme() { - return document.documentElement.getAttribute('data-color-mode') === 'dark' || - document.documentElement.getAttribute('data-dark-theme') === 'dark' || - document.body.classList.contains('dark') || - getComputedStyle(document.body).backgroundColor === 'rgb(13, 17, 23)'; - } - - cleanup() { - try { - if (this.animationObserver) { - this.animationObserver.disconnect(); - this.animationObserver = null; - } - - // Remove floating orbs - if (this.orbContainer) { - this.orbContainer.remove(); - this.orbContainer = null; - } - - // Remove styles - if (this.styleElement) { - this.styleElement.remove(); - this.styleElement = null; - } - - // Remove cursor trails - const trails = document.querySelectorAll('.cursor-trail'); - trails.forEach(trail => trail.remove()); - - // Remove star explosion keyframes - const explosionStyles = document.querySelector('#star-explosion-keyframes'); - if (explosionStyles) { - explosionStyles.remove(); - } - - this.isActive = false; - Logger.info('Theme Enhancer cleaned up'); - } catch (error) { - Logger.logError(error, { context: 'Theme Enhancer cleanup' }); - } - } - } - - return ThemeEnhancerClass; -})(); - -window.ThemeEnhancer = ThemeEnhancer; \ No newline at end of file diff --git a/src/options/options.css b/src/options/options.css new file mode 100644 index 0000000..1ab14ba --- /dev/null +++ b/src/options/options.css @@ -0,0 +1,4 @@ +html{scroll-padding-top:28px;font-size:14px}body{min-width:300px}.settings-header{max-width:1064px;margin:0 auto;min-height:92px;padding:24px 32px;display:flex;align-items:center;justify-content:space-between;gap:20px;border-bottom:1px solid var(--border)}.settings-header .brand{color:var(--ink)}.settings-header .brand:hover{text-decoration:none}.header-caption{font-size:12px;color:var(--muted)}.settings-layout{display:grid;grid-template-columns:192px minmax(0,1fr);gap:56px;max-width:1064px;padding:44px 32px 24px;margin:0 auto}.settings-sidebar{align-self:start;position:sticky;top:32px}.sidebar-title{font-size:14px;font-weight:650;margin:0 10px 15px}.settings-sidebar nav{display:grid;gap:4px}.settings-sidebar nav a{display:block;border-radius:6px;padding:10px;color:var(--muted);font-size:13px}.settings-sidebar nav a:hover,.settings-sidebar nav a:focus-visible{background:var(--surface);color:var(--ink);text-decoration:none}.sidebar-footnote{color:var(--muted);font-size:11px;margin:36px 10px;display:flex;align-items:center;gap:7px}.local-dot{width:6px;height:6px;background:var(--success);border-radius:50%}.page-heading h1{font-size:32px;letter-spacing:-.04em;line-height:1.2;font-weight:650;margin-bottom:12px}.page-heading>p{color:var(--muted);font-size:14px;max-width:54ch}.save-feedback{min-height:51px;display:flex;align-items:center;gap:12px;margin:9px 0 23px}.save-feedback p{font-size:12px;color:var(--success)}.save-feedback p[data-error="true"],#backup-status[data-error="true"]{color:var(--danger)}main{min-width:0}main:focus{outline:none}main section{border-top:1px solid var(--border);padding:28px 0 30px}h2{font-size:18px;letter-spacing:-.025em;font-weight:650;line-height:1.35}.section-description{font-size:13px;color:var(--muted);margin-top:9px;max-width:68ch}.setting-row{display:flex;gap:26px;align-items:flex-start;justify-content:space-between;padding:21px 0}.setting-row+ .setting-row{border-top:1px solid var(--border)}.setting-row>div{min-width:0;max-width:48ch}.setting-row label{display:block;font-size:13px;font-weight:600;line-height:1.5;cursor:pointer}.setting-row p{color:var(--muted);font-size:12px;margin-top:5px;line-height:1.6}.master-row{background:var(--surface);border:1px solid var(--border);border-radius:8px;margin-top:19px;padding:18px}.master-row + .setting-row{border-top:0}.switch{appearance:none;flex-shrink:0;width:34px;height:20px;border:1px solid var(--muted);border-radius:12px;background:var(--surface-hover);position:relative;cursor:pointer;margin:1px 0 0}.switch::after{content:"";position:absolute;top:3px;left:3px;width:12px;height:12px;background:var(--muted);border-radius:50%}.switch:checked{background:var(--accent);border-color:var(--accent)}.switch:checked::after{left:17px;background:var(--canvas)}.switch:disabled{opacity:.55;cursor:wait}select{border:1px solid var(--border);border-radius:6px;padding:7px 30px 7px 10px;background:var(--canvas);color:var(--ink);min-width:151px;max-width:100%;font-size:12px;cursor:pointer}select:disabled{opacity:.65;cursor:wait}kbd{font-family:inherit;background:var(--surface);border:1px solid var(--border);border-radius:3px;padding:0 4px;font-size:10px;white-space:nowrap}.date-sample{font-size:12px;padding:13px 15px;background:var(--surface);border-radius:6px;display:flex;flex-wrap:wrap;gap:12px;color:var(--muted);margin-bottom:6px}.sample-label{font-weight:600}#date-preview{color:var(--ink)}.section-title-row{display:flex;justify-content:space-between;align-items:center;gap:15px}.item-count{font-size:11px;color:var(--muted);white-space:nowrap}.backup-actions{display:flex;gap:9px;margin:21px 0 16px;flex-wrap:wrap}.backup-detail{font-size:12px;color:var(--muted);margin-top:9px;max-width:67ch}#backup-status{font-size:12px;color:var(--success);margin-top:14px;overflow-wrap:anywhere}.permission-list{margin:23px 0;display:grid;gap:18px}.permission-list>div{display:grid;grid-template-columns:112px minmax(0,1fr);gap:15px}.permission-list dt{font-size:12px;font-weight:600;line-height:1.6}.permission-list dd{font-size:12px;color:var(--muted);line-height:1.6;margin:0}.privacy-note{font-size:12px;color:var(--muted);max-width:67ch}.settings-footer{border-top:1px solid var(--border);padding:23px 0;display:flex;justify-content:space-between;gap:12px;font-size:11px;color:var(--muted)}.skip-link{position:fixed;top:8px;left:8px;padding:10px;background:var(--canvas);border:1px solid var(--border);border-radius:6px;transform:translateY(-150%);z-index:10}.skip-link:focus{transform:translateY(0)}[hidden]{display:none!important} +@media(max-width:800px){.settings-layout{grid-template-columns:155px minmax(0,1fr);gap:30px;padding:34px 24px}.settings-header{padding:22px 24px}.setting-row{gap:18px}.setting-row>div{max-width:44ch}.setting-row:has(select){flex-wrap:wrap}.setting-row select{min-width:180px}.permission-list>div{grid-template-columns:1fr;gap:3px}} +@media(max-width:560px){.settings-header{min-height:74px;padding:18px 20px}.header-caption{display:none}.settings-layout{display:block;padding:24px 20px}.settings-sidebar{position:static}.sidebar-title,.sidebar-footnote{display:none}.settings-sidebar nav{display:flex;gap:5px;flex-wrap:wrap;margin:-4px -7px 30px}.settings-sidebar nav a{padding:7px;font-size:11px}.page-heading h1{font-size:29px}.save-feedback{margin-bottom:13px}.master-row{padding:16px}.section-title-row{align-items:flex-start;flex-wrap:wrap;gap:6px}.setting-row{gap:16px}.setting-row select{min-width:160px}.settings-footer{padding-bottom:12px}} +@media(forced-colors:active){.switch:checked{background:Highlight}.switch::after{background:ButtonText}.switch:checked::after{background:HighlightText}} diff --git a/src/options/options.html b/src/options/options.html new file mode 100644 index 0000000..5882c91 --- /dev/null +++ b/src/options/options.html @@ -0,0 +1,110 @@ + + + + + + Settings ยท GitHub Enhancer + + + + + + + + +
+ + + GitHub Enhancer + + Your personal workbench +
+
+ +
+
+

Make it yours.

+

Adjust your workbench and the way you read GitHub.

+
+
+

Loading your settingsโ€ฆ

+ +
+
+
+

General

+
+

Show the workbench and your reading enhancements on GitHub. Turning it off keeps your saved work.

+ +
+
+

Automatic follows GitHub in the workbench and your device in extension pages. GitHub keeps its own appearance.

+ +
+
+

Open command search with Alt + Shift + K. On Mac, use Option for Alt. GitHubโ€™s own shortcut is unchanged.

+ +
+
+
+

Reading

+

Small changes to help you stay oriented. Apply them individually.

+
+

Add the full date and time beside GitHubโ€™s relative timestamps. The original timestamp stays in place.

+ +
+
+

Controls date formatting. The extension interface stays in English.

+ +
+
+

Use your deviceโ€™s time zone or a shared UTC reference.

+ +
+
Preview2 days ago
+
+

Give supported repository content containers more room on larger screens.

+ +
+
+

Hide the About sidebar on repository overview pages. Issue and pull request controls stay visible.

+ +
+
+
+
+

Workspace backups

Loadingโ€ฆ
+

Your workspace belongs to this browser profile. Export a backup to keep a copy or move it to another device.

+
+ + + +
+

JSON backups include saved links, code excerpts, workspaces, private review notes, marks, and settings. The file is not encrypted, so store and share it with care.

+

Import merges saved items and keeps newer local edits. Settings included in the backup are applied.

+

+
+
+

Privacy & permissions

+

No account, token, or external service is needed. Your saved pages and notes stay in this browser profile unless you export them.

+
+
Storage
Stores your saved items, notes, and preferences on this device.
+
Current tab
Reads the GitHub page you open the popup on, including loaded code or diffs for its page tools.
+
GitHub pages
Adds the workbench and optional reading controls on github.com. Pages you visit are not automatically saved.
+
+

No analytics, remote fonts, or background GitHub API requests. Uninstalling the extension can remove its local data; export a backup first if you want to keep it.

+
+ +
+
+ + diff --git a/src/options/options.js b/src/options/options.js new file mode 100644 index 0000000..2ee110f --- /dev/null +++ b/src/options/options.js @@ -0,0 +1,130 @@ +(() => { + 'use strict'; + const GHE = globalThis.GHE; + + GHE.createOptions = function createOptions(document) { + const form = document.querySelector('#settings-form'); + const controls = [...form.querySelectorAll('[name]')]; + const saveStatus = document.querySelector('#save-status'); + const backupStatus = document.querySelector('#backup-status'); + const retry = document.querySelector('#retry-load'); + const exportButton = document.querySelector('#export-button'); + const importButton = document.querySelector('#import-button'); + const fileInput = document.querySelector('#import-file'); + let state; + let busy = false; + + function status(target, message, error = false) { + target.textContent = message; + target.dataset.error = String(error); + } + + function setBusy(value) { + busy = value; + for (const control of controls) control.disabled = value || !state; + exportButton.disabled = value || !state; + importButton.disabled = value || !state; + } + + function render(next) { + state = next; + for (const control of controls) { + if (control.type === 'checkbox') control.checked = state.settings[control.name]; + else control.value = state.settings[control.name]; + } + document.documentElement.dataset.theme = state.settings.theme; + const sample = GHE.formatDate(Date.now() - 2 * 86400000, state.settings); + document.querySelector('#date-preview').textContent = state.settings.exactDates ? `(${sample})` : ''; + const count = state.items.length; + document.querySelector('#workspace-count').textContent = `${count} saved ${count === 1 ? 'page' : 'pages'} ยท ${(state.snippets || []).length} snippets ยท ${(state.workspaces || []).length} workspaces ยท ${(state.reviews || []).length} reviews ยท ${(state.templates || []).length} templates`; + } + + async function load() { + if (busy) return; + setBusy(true); + retry.hidden = true; + status(saveStatus, 'Loading your settingsโ€ฆ'); + try { + render(await GHE.request({ type: 'GET_STATE' })); + status(saveStatus, 'Changes save automatically.'); + } catch (error) { + status(saveStatus, error.message || 'Could not load settings. Try again.', true); + retry.hidden = false; + } finally { + setBusy(false); + } + } + + form.addEventListener('submit', event => event.preventDefault()); + form.addEventListener('change', async event => { + const control = event.target; + if (!controls.includes(control) || !state || busy) return; + const value = control.type === 'checkbox' ? control.checked : control.value; + setBusy(true); + status(saveStatus, 'Savingโ€ฆ'); + try { + render(await GHE.request({ type: 'SET_SETTINGS', patch: { [control.name]: value } })); + status(saveStatus, 'Settings saved.'); + } catch (error) { + render(state); + status(saveStatus, error.message || 'Could not save. Your previous setting has been restored.', true); + } finally { + setBusy(false); + } + }); + + retry.addEventListener('click', load); + importButton.addEventListener('click', () => fileInput.click()); + fileInput.addEventListener('change', async () => { + const file = fileInput.files && fileInput.files[0]; + if (!file || busy) return; + setBusy(true); + status(backupStatus, 'Importing backupโ€ฆ'); + try { + if (file.size > GHE.LIMITS.importBytes) throw new Error(`Choose a JSON backup no larger than ${GHE.LIMITS.importBytes / (1024 * 1024)} MB.`); + const text = await new Promise((resolve, reject) => { + const reader = new document.defaultView.FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = () => reject(new Error('Could not read this file. Choose it again.')); + reader.readAsText(file); + }); + render(await GHE.request({ type: 'IMPORT_ITEMS', text })); + status(backupStatus, 'Backup imported. Saved items were merged and newer local edits kept.'); + } catch (error) { + status(backupStatus, error.message || 'Could not import this backup. Your workspace is unchanged.', true); + } finally { + fileInput.value = ''; + setBusy(false); + } + }); + + exportButton.addEventListener('click', async () => { + if (busy) return; + setBusy(true); + status(backupStatus, 'Preparing backupโ€ฆ'); + try { + const latest = await GHE.request({ type: 'GET_STATE' }); + const payload = GHE.exportBackup(latest); + const view = document.defaultView; + const url = view.URL.createObjectURL(new view.Blob([payload], { type: 'application/json' })); + const link = document.createElement('a'); + link.href = url; + link.download = `github-enhancer-backup-${new Date().toISOString().slice(0, 10)}.json`; + document.body.append(link); + link.click(); + link.remove(); + view.setTimeout(() => view.URL.revokeObjectURL(url), 1000); + render(latest); + status(backupStatus, 'Backup download started. The file includes your private notes.'); + } catch (error) { + status(backupStatus, error.message || 'Could not export your backup. Try again.', true); + } finally { + setBusy(false); + } + }); + + return { ready: load() }; + }; + + if (globalThis.chrome?.runtime && document.querySelector('#settings-form')) GHE.createOptions(document); +})(); diff --git a/src/panel/panel.css b/src/panel/panel.css new file mode 100644 index 0000000..f927482 --- /dev/null +++ b/src/panel/panel.css @@ -0,0 +1 @@ +html,body,#app{width:100%;height:100%;overflow:hidden}.workbench{min-height:0} diff --git a/src/panel/panel.html b/src/panel/panel.html new file mode 100644 index 0000000..778f3dd --- /dev/null +++ b/src/panel/panel.html @@ -0,0 +1,2 @@ + +GitHub Enhancer workspace
diff --git a/src/panel/panel.js b/src/panel/panel.js new file mode 100644 index 0000000..c38fa3c --- /dev/null +++ b/src/panel/panel.js @@ -0,0 +1,30 @@ +(() => { + document.documentElement.dataset.gheBuild='hello-v2';document.documentElement.dataset.gheEvent='script'; + const G=globalThis.GHE, params=new URLSearchParams(location.search); + const context=G.parseContext(params.get('url'),params.get('title')||''); + const pending=new Map();let sequence=0; + const pageAction=action=>new Promise((resolve,reject)=>{const requestId=String(++sequence);const timeout=setTimeout(()=>{pending.delete(requestId);reject(new Error('Page action timed out. Refresh the GitHub page.'));},5000);pending.set(requestId,{resolve,reject,timeout});parent.postMessage({source:'ghe-panel',type:'PAGE_ACTION',requestId,action},'https://github.com');}); + const refreshPage=()=>{parent.postMessage({source:'ghe-panel',type:'REQUEST_CONTEXT'},'https://github.com');return null;}; + const ui=G.mountWorkbench(document.querySelector('#app'),{...G.draftOptions,request:G.request,context,copy:G.copy,pageAction,refreshPage,openPages:G.openPages,openOptions:()=>chrome.runtime.openOptionsPage(),close:()=>parent.postMessage({source:'ghe-panel',type:'CLOSE'},'https://github.com')}); + let pageTheme=params.get('theme')||'dark'; + async function syncTheme(){await ui.ready;const setting=ui.getState().settings.theme;document.querySelector('#app').dataset.theme=setting==='auto'?pageTheme:setting;} + window.addEventListener('message',event=>{ + if(event.source!==parent||event.origin!=='https://github.com'||event.data?.source!=='ghe-host')return; + if(event.data.type==='PING'&&typeof event.data.requestId==='string'){ + document.documentElement.dataset.gheEvent='ping-received';document.documentElement.dataset.gheRequestId=event.data.requestId; + const requestId=event.data.requestId; + ui.ready.then(()=>{document.documentElement.dataset.gheEvent='ready-sent';parent.postMessage({source:'ghe-panel',type:'READY',requestId},'https://github.com');}); + } + else if(event.data.type==='CONTEXT'){ui.setContext(G.parseContext(event.data.url,event.data.title),event.data.pageData||{});pageTheme=event.data.theme==='light'?'light':'dark';syncTheme();} + else if(event.data.type==='ACTION_RESULT'){const p=pending.get(event.data.requestId);if(p){clearTimeout(p.timeout);pending.delete(event.data.requestId);if(event.data.ok)p.resolve(true);else p.reject(new Error('This part of the page is no longer loaded. Refresh page data.'));}} + else if(event.data.type==='COMMANDS')ui.openPalette(); + }); + chrome.storage.onChanged.addListener(async(_changes,area)=>{if(area==='local'){await ui.refresh();syncTheme();}}); + window.addEventListener('beforeunload',event=>{if(G.hasUnprotectedDrafts()){event.preventDefault();event.returnValue='';}}); + window.addEventListener('keydown',event=>{if(event.key==='Escape'&&!event.defaultPrevented&&!document.querySelector('.command-overlay'))parent.postMessage({source:'ghe-panel',type:'CLOSE'},'https://github.com');}); + syncTheme(); + // The frame's load event invalidates the host connection. Announce on the next + // task so the parent has processed that event before authenticating this document. + const announce=()=>{document.documentElement.dataset.gheEvent='load';setTimeout(()=>{document.documentElement.dataset.gheEvent='hello-sent';parent.postMessage({source:'ghe-panel',type:'HELLO'},'https://github.com');},0);}; + if(document.readyState==='complete')announce();else window.addEventListener('load',announce,{once:true}); +})(); diff --git a/src/popup/popup.css b/src/popup/popup.css index 93eda68..9874f19 100644 --- a/src/popup/popup.css +++ b/src/popup/popup.css @@ -1,313 +1 @@ -/* Popup styles for GitHub Enhancer */ - -* { - box-sizing: border-box; - margin: 0; - padding: 0; -} - -body { - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; - font-size: 14px; - line-height: 1.5; - color: #24292e; - background: #ffffff; - width: 400px; - max-height: 600px; - overflow-y: auto; -} - -.popup-container { - display: flex; - flex-direction: column; - min-height: 100vh; -} - -/* Header */ -.popup-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 16px 20px; - background: #f6f8fa; - border-bottom: 1px solid #e1e4e8; -} - -.popup-header h1 { - font-size: 18px; - font-weight: 600; - color: #24292e; -} - -.version { - font-size: 12px; - color: #6a737d; - background: #e1e4e8; - padding: 2px 6px; - border-radius: 3px; -} - -/* Main content */ -.popup-content { - flex: 1; - padding: 20px; -} - -.settings-section { - margin-bottom: 24px; -} - -.settings-section:last-child { - margin-bottom: 0; -} - -.settings-section h2 { - font-size: 16px; - font-weight: 600; - color: #24292e; - margin-bottom: 12px; - padding-bottom: 4px; - border-bottom: 1px solid #e1e4e8; -} - -.setting-group { - display: flex; - flex-direction: column; - gap: 12px; -} - -.setting-item { - display: flex; - align-items: center; - gap: 8px; - padding: 8px 0; - cursor: pointer; -} - -.setting-item input[type="checkbox"] { - margin: 0; - cursor: pointer; -} - -.setting-item input[type="range"] { - flex: 1; - margin: 0 8px; -} - -.setting-item select { - padding: 4px 8px; - border: 1px solid #d1d5da; - border-radius: 4px; - background: white; - font-size: 14px; -} - -.setting-item label { - font-weight: 500; - color: #24292e; - flex: 1; -} - -/* Range inputs */ -input[type="range"] { - -webkit-appearance: none; - appearance: none; - height: 4px; - background: #e1e4e8; - border-radius: 2px; - outline: none; -} - -input[type="range"]::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - width: 16px; - height: 16px; - background: #0366d6; - border-radius: 50%; - cursor: pointer; -} - -input[type="range"]::-moz-range-thumb { - width: 16px; - height: 16px; - background: #0366d6; - border-radius: 50%; - cursor: pointer; - border: none; -} - -/* Footer */ -.popup-footer { - padding: 16px 20px; - background: #f6f8fa; - border-top: 1px solid #e1e4e8; - display: flex; - gap: 12px; -} - -/* Buttons */ -.button-primary { - background: #0366d6; - color: white; - border: none; - padding: 8px 16px; - border-radius: 4px; - font-size: 14px; - font-weight: 500; - cursor: pointer; - transition: background-color 0.2s; -} - -.button-primary:hover { - background: #0256cc; -} - -.button-primary:disabled { - background: #94a3b8; - cursor: not-allowed; -} - -.button-secondary { - background: white; - color: #24292e; - border: 1px solid #d1d5da; - padding: 8px 16px; - border-radius: 4px; - font-size: 14px; - font-weight: 500; - cursor: pointer; - transition: background-color 0.2s, border-color 0.2s; -} - -.button-secondary:hover { - background: #f6f8fa; - border-color: #c6cbd1; -} - -.button-secondary:disabled { - background: #f6f8fa; - color: #6a737d; - cursor: not-allowed; -} - -/* Toast notifications */ -.toast { - position: fixed; - top: 20px; - right: 20px; - padding: 12px 16px; - border-radius: 4px; - font-size: 14px; - font-weight: 500; - z-index: 1000; - transform: translateX(100%); - transition: transform 0.3s ease; -} - -.toast-show { - transform: translateX(0); -} - -.toast-success { - background: #d4edda; - color: #155724; - border: 1px solid #c3e6cb; -} - -.toast-error { - background: #f8d7da; - color: #721c24; - border: 1px solid #f5c6cb; -} - -.toast-warning { - background: #fff3cd; - color: #856404; - border: 1px solid #ffeaa7; -} - -.toast-info { - background: #d1ecf1; - color: #0c5460; - border: 1px solid #bee5eb; -} - -/* Responsive design */ -@media (max-width: 480px) { - body { - width: 100vw; - } - - .popup-header, - .popup-content, - .popup-footer { - padding-left: 16px; - padding-right: 16px; - } -} - -/* Focus styles */ -input:focus, -select:focus, -button:focus { - outline: 2px solid #0366d6; - outline-offset: 2px; -} - -/* Dark mode support */ -@media (prefers-color-scheme: dark) { - body { - background: #0d1117; - color: #c9d1d9; - } - - .popup-header { - background: #161b22; - border-bottom-color: #30363d; - } - - .popup-header h1 { - color: #c9d1d9; - } - - .version { - background: #30363d; - color: #8b949e; - } - - .settings-section h2 { - color: #c9d1d9; - border-bottom-color: #30363d; - } - - .setting-item label { - color: #c9d1d9; - } - - .setting-item select { - background: #21262d; - border-color: #30363d; - color: #c9d1d9; - } - - input[type="range"] { - background: #30363d; - } - - .popup-footer { - background: #161b22; - border-top-color: #30363d; - } - - .button-secondary { - background: #21262d; - border-color: #30363d; - color: #c9d1d9; - } - - .button-secondary:hover { - background: #30363d; - border-color: #484f58; - } -} \ No newline at end of file +body{width:400px;height:580px}#app{height:100%} diff --git a/src/popup/popup.html b/src/popup/popup.html index 2f14ecc..daf99d1 100644 --- a/src/popup/popup.html +++ b/src/popup/popup.html @@ -1,69 +1,2 @@ - - - - - - GitHub Enhancer Settings - - - - - - - - \ No newline at end of file + +GitHub Enhancer
diff --git a/src/popup/popup.js b/src/popup/popup.js index c0212d8..b1fbe17 100644 --- a/src/popup/popup.js +++ b/src/popup/popup.js @@ -1,405 +1,11 @@ -/** - * Popup script for GitHub Enhancer settings - */ - -// DOM elements -const elements = { - // Checkboxes - enhanceContributors: null, - enhanceDateTimes: null, - enhanceFileSizes: null, - enableThemeEnhancements: null, - showCommitInfo: null, - showTeamInfo: null, - showOrgInfo: null, - animationsEnabled: null, - debugMode: null, - - // Range inputs - cardWidth: null, - maxCards: null, - - // Select inputs - locale: null, - theme: null, - - // Value displays - cardWidthValue: null, - maxCardsValue: null, - - // Buttons - saveButton: null, - resetButton: null, - clearCacheButton: null, - - // Info elements - storageUsage: null, - toast: null, - toastMessage: null -}; - -// Settings state -let currentSettings = {}; -const defaultSettings = { - enhanceContributors: true, - enhanceDateTimes: true, - enhanceFileSizes: true, - enableThemeEnhancements: true, - showCommitInfo: true, - showTeamInfo: true, - showOrgInfo: true, - cardWidth: 250, - maxCards: 10, - locale: 'en-US', - theme: 'auto', - animationsEnabled: true, - debugMode: false -}; - -/** - * Initialize popup when DOM is loaded - */ -document.addEventListener('DOMContentLoaded', initializePopup); - -/** - * Initialize popup - */ -async function initializePopup() { - try { - // Get DOM elements - getDOMElements(); - - // Set up event listeners - setupEventListeners(); - - // Load current settings - await loadSettings(); - - // Update storage usage display - await updateStorageUsage(); - - console.log('Popup initialized successfully'); - } catch (error) { - console.error('Failed to initialize popup:', error); - showToast('Failed to initialize settings', 'error'); - } -} - -/** - * Get DOM elements - */ -function getDOMElements() { - // Checkboxes - elements.enhanceContributors = document.getElementById('enhanceContributors'); - elements.enhanceDateTimes = document.getElementById('enhanceDateTimes'); - elements.enhanceFileSizes = document.getElementById('enhanceFileSizes'); - elements.enableThemeEnhancements = document.getElementById('enableThemeEnhancements'); - elements.showCommitInfo = document.getElementById('showCommitInfo'); - elements.showTeamInfo = document.getElementById('showTeamInfo'); - elements.showOrgInfo = document.getElementById('showOrgInfo'); - elements.animationsEnabled = document.getElementById('animationsEnabled'); - elements.debugMode = document.getElementById('debugMode'); - - // Range inputs - elements.cardWidth = document.getElementById('cardWidth'); - elements.maxCards = document.getElementById('maxCards'); - - // Select inputs - elements.locale = document.getElementById('locale'); - elements.theme = document.getElementById('theme'); - - // Value displays - elements.cardWidthValue = document.getElementById('cardWidthValue'); - elements.maxCardsValue = document.getElementById('maxCardsValue'); - - // Buttons - elements.saveButton = document.getElementById('saveButton'); - elements.resetButton = document.getElementById('resetButton'); - elements.clearCacheButton = document.getElementById('clearCacheButton'); - - // Info elements - elements.storageUsage = document.getElementById('storageUsage'); - elements.toast = document.getElementById('toast'); - elements.toastMessage = document.getElementById('toastMessage'); -} - -/** - * Set up event listeners - */ -function setupEventListeners() { - // Range input updates - if (elements.cardWidth && elements.cardWidthValue) { - elements.cardWidth.addEventListener('input', (e) => { - elements.cardWidthValue.textContent = `${e.target.value}px`; - }); - } - - if (elements.maxCards && elements.maxCardsValue) { - elements.maxCards.addEventListener('input', (e) => { - elements.maxCardsValue.textContent = e.target.value; - }); - } - - // Button clicks - if (elements.saveButton) { - elements.saveButton.addEventListener('click', saveSettings); - } - if (elements.resetButton) { - elements.resetButton.addEventListener('click', resetSettings); - } - if (elements.clearCacheButton) { - elements.clearCacheButton.addEventListener('click', clearCache); - } - - // Auto-save on change (optional) - const autoSaveElements = [ - elements.enhanceContributors, - elements.enhanceDateTimes, - elements.enhanceFileSizes, - elements.enableThemeEnhancements, - elements.locale - ].filter(Boolean); - - autoSaveElements.forEach(element => { - element.addEventListener('change', debounce(saveSettings, 500)); - }); -} - -/** - * Load settings from storage - */ -async function loadSettings() { - try { - const response = await chrome.runtime.sendMessage({ type: 'GET_SETTINGS' }); - - if (response.success) { - currentSettings = { ...defaultSettings, ...response.settings }; - updateUI(currentSettings); - } else { - throw new Error(response.error || 'Failed to load settings'); - } - } catch (error) { - console.error('Failed to load settings:', error); - currentSettings = { ...defaultSettings }; - updateUI(currentSettings); - showToast('Using default settings', 'warning'); - } -} - -/** - * Update UI with settings - */ -function updateUI(settings) { - // Checkboxes - if (elements.enhanceContributors) elements.enhanceContributors.checked = settings.enhanceContributors; - if (elements.enhanceDateTimes) elements.enhanceDateTimes.checked = settings.enhanceDateTimes; - if (elements.enhanceFileSizes) elements.enhanceFileSizes.checked = settings.enhanceFileSizes; - if (elements.enableThemeEnhancements) elements.enableThemeEnhancements.checked = settings.enableThemeEnhancements; - - // Range inputs - if (elements.cardWidth) { - elements.cardWidth.value = settings.cardWidth; - elements.cardWidthValue.textContent = `${settings.cardWidth}px`; - } - - if (elements.maxCards) { - elements.maxCards.value = settings.maxCards; - elements.maxCardsValue.textContent = settings.maxCards; - } - - // Select inputs - if (elements.locale) elements.locale.value = settings.locale; -} - -/** - * Collect settings from UI - */ -function collectSettings() { - return { - enhanceContributors: elements.enhanceContributors?.checked ?? defaultSettings.enhanceContributors, - enhanceDateTimes: elements.enhanceDateTimes?.checked ?? defaultSettings.enhanceDateTimes, - enhanceFileSizes: elements.enhanceFileSizes?.checked ?? defaultSettings.enhanceFileSizes, - enableThemeEnhancements: elements.enableThemeEnhancements?.checked ?? defaultSettings.enableThemeEnhancements, - showCommitInfo: currentSettings.showCommitInfo, - showTeamInfo: currentSettings.showTeamInfo, - showOrgInfo: currentSettings.showOrgInfo, - cardWidth: parseInt(elements.cardWidth?.value ?? defaultSettings.cardWidth), - maxCards: parseInt(elements.maxCards?.value ?? defaultSettings.maxCards), - locale: elements.locale?.value ?? defaultSettings.locale, - theme: currentSettings.theme, - animationsEnabled: currentSettings.animationsEnabled, - debugMode: currentSettings.debugMode - }; -} - -/** - * Save settings - */ -async function saveSettings() { - try { - elements.saveButton.disabled = true; - elements.saveButton.textContent = 'Saving...'; - - const newSettings = collectSettings(); - - const response = await chrome.runtime.sendMessage({ - type: 'SAVE_SETTINGS', - payload: newSettings - }); - - if (response.success) { - currentSettings = newSettings; - showToast('Settings saved successfully!', 'success'); - } else { - throw new Error(response.error || 'Failed to save settings'); - } - } catch (error) { - console.error('Failed to save settings:', error); - showToast('Failed to save settings', 'error'); - } finally { - elements.saveButton.disabled = false; - elements.saveButton.textContent = 'Save Settings'; - } -} - -/** - * Reset settings to defaults - */ -async function resetSettings() { - if (!confirm('Are you sure you want to reset all settings to defaults?')) { - return; - } - - try { - elements.resetButton.disabled = true; - elements.resetButton.textContent = 'Resetting...'; - - const response = await chrome.runtime.sendMessage({ - type: 'SAVE_SETTINGS', - payload: defaultSettings - }); - - if (response.success) { - currentSettings = { ...defaultSettings }; - updateUI(currentSettings); - showToast('Settings reset to defaults', 'success'); - } else { - throw new Error(response.error || 'Failed to reset settings'); - } - } catch (error) { - console.error('Failed to reset settings:', error); - showToast('Failed to reset settings', 'error'); - } finally { - elements.resetButton.disabled = false; - elements.resetButton.textContent = 'Reset'; - } -} - -/** - * Clear cache - */ -async function clearCache() { - if (!confirm('Are you sure you want to clear the cache?')) { - return; - } - - try { - elements.clearCacheButton.disabled = true; - elements.clearCacheButton.textContent = 'Clearing...'; - - const response = await chrome.runtime.sendMessage({ type: 'CLEAR_CACHE' }); - - if (response.success) { - showToast('Cache cleared successfully!', 'success'); - await updateStorageUsage(); - } else { - throw new Error(response.error || 'Failed to clear cache'); - } - } catch (error) { - console.error('Failed to clear cache:', error); - showToast('Failed to clear cache', 'error'); - } finally { - elements.clearCacheButton.disabled = false; - elements.clearCacheButton.textContent = 'Clear Cache'; - } -} - -/** - * Update storage usage display - */ -async function updateStorageUsage() { - try { - const response = await chrome.runtime.sendMessage({ type: 'GET_STORAGE_USAGE' }); - - if (response.success && elements.storageUsage) { - const kb = Math.round(response.bytesInUse / 1024); - elements.storageUsage.textContent = `Storage: ${kb} KB`; - } - } catch (error) { - console.error('Failed to get storage usage:', error); - } -} - -/** - * Show toast notification - */ -function showToast(message, type = 'info') { - const toast = document.createElement('div'); - toast.className = `toast toast-${type}`; - toast.textContent = message; - - document.body.appendChild(toast); - - // Trigger animation - setTimeout(() => toast.classList.add('toast-show'), 100); - - // Remove after delay - setTimeout(() => { - toast.classList.remove('toast-show'); - setTimeout(() => toast.remove(), 300); - }, 3000); -} - -/** - * Debounce utility - */ -function debounce(func, wait) { - let timeout; - return function executedFunction(...args) { - const later = () => { - clearTimeout(timeout); - func(...args); - }; - clearTimeout(timeout); - timeout = setTimeout(later, wait); - }; -} - -/** - * Handle keyboard shortcuts - */ -document.addEventListener('keydown', (e) => { - if (e.ctrlKey || e.metaKey) { - if (e.key === 's') { - e.preventDefault(); - saveSettings(); - } else if (e.key === 'r') { - e.preventDefault(); - resetSettings(); - } - } - - if (e.key === 'Escape') { - window.close(); - } -}); - -// Additional initialization check (backup) -if (document.readyState === 'loading') { - // Already handled by the DOMContentLoaded listener above -} else { - // If DOM is already loaded, initialize immediately - if (typeof initializePopup === 'function') { - initializePopup(); - } -} \ No newline at end of file +(async()=>{ + const G=globalThis.GHE; + let context=null,pageData={},tabId=null; + async function refreshPage(){if(tabId===null)throw new Error('Open a GitHub repository first.');try{return await chrome.tabs.sendMessage(tabId,{type:'GET_CONTEXT'});}catch{throw new Error('Reload the GitHub page to enable page tools.');}} + try{const [tab]=await chrome.tabs.query({active:true,currentWindow:true});context=G.parseContext(tab?.url,tab?.title);tabId=tab?.id??null;if(context){const data=await refreshPage();context=data.context||context;pageData=data.pageData||{};}} + catch{/* Saved pages remain usable when there is no supported active tab. */} + const pageAction=async action=>{const result=await chrome.tabs.sendMessage(tabId,{type:'PAGE_ACTION',action});if(!result?.ok)throw new Error('This part of the page is no longer loaded. Refresh page data.');return true;}; + const ui=G.mountWorkbench(document.querySelector('#app'),{...G.draftOptions,request:G.request,context,pageData,pageAction,refreshPage,openPages:G.openPages,copy:G.copy,openOptions:()=>chrome.runtime.openOptionsPage()}); + chrome.storage.onChanged.addListener((_changes,area)=>{if(area==='local')ui.refresh();}); + window.addEventListener('beforeunload',event=>{if(G.hasUnprotectedDrafts()){event.preventDefault();event.returnValue='';}}); +})(); diff --git a/src/shared/basket.css b/src/shared/basket.css new file mode 100644 index 0000000..c1f73ae --- /dev/null +++ b/src/shared/basket.css @@ -0,0 +1,2 @@ +.basket{color:var(--ink);min-width:0}.basket-header{padding:20px 22px 16px}.basket-title{font-size:20px;line-height:1.3;letter-spacing:-.025em;margin:0 0 7px}.basket-description{font-size:12px;color:var(--muted);line-height:1.55;max-width:60ch}.basket-composer{padding:18px 22px 22px;background:var(--surface);border-block:1px solid var(--border)}.basket-heading{font-size:14px;font-weight:650;margin:0}.basket-composer>.basket-heading{margin-bottom:10px}.basket-path{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;overflow-wrap:anywhere;margin:0 0 4px}.basket-meta{font-size:11px;color:var(--muted);line-height:1.5}.basket-field{display:flex;flex-direction:column;gap:6px;margin-block:12px;min-width:0}.basket-label{font-size:12px;font-weight:550}.basket-input{width:100%;min-width:0;padding:8px 10px;border:1px solid var(--border);border-radius:7px;background:var(--canvas);color:var(--ink);font-size:12px;line-height:1.5}.basket-input::placeholder{color:var(--muted)}.basket-range{display:flex;align-items:end;gap:9px;flex-wrap:wrap;margin-block:4px 12px}.basket-range>.basket-field{flex:1;min-width:80px;margin-bottom:0}.basket-range>.button{width:100%;justify-content:flex-start;background:transparent;border-color:transparent;padding-inline:0;color:var(--accent);min-height:25px}.basket-preview{display:block;margin:12px 0 7px;padding:12px;max-height:220px;overflow:auto;border:1px solid var(--border);border-radius:7px;background:var(--canvas);color:var(--ink);font:11px/1.65 ui-monospace,SFMono-Regular,Consolas,monospace;tab-size:4;white-space:pre;overflow-wrap:normal}.basket-note{font-size:12px;line-height:1.55;min-height:70px;padding:9px 10px}.basket-actions{display:flex;flex-wrap:wrap;gap:7px;margin-top:12px}.basket-warning{margin-top:8px;font-size:12px;line-height:1.5;color:var(--ink)}.basket-error{color:var(--danger)}.basket-saved{padding:22px}.basket-section-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap}.basket-search{margin-top:16px}.basket-item{padding-block:18px;border-bottom:1px solid var(--border)}.basket-item:last-child{border-bottom:0}.basket-item-heading{display:flex;align-items:start;gap:8px}.basket-item-title{font-size:13px;line-height:1.5;font-weight:650;margin:0 0 5px;overflow-wrap:anywhere}.basket-source-link{display:block;font:11px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace;overflow-wrap:anywhere}.basket-item>.basket-meta{margin-top:4px}.basket-code-details{margin-top:10px}.basket-code-details>summary{font-size:11px;cursor:pointer;color:var(--muted);padding-block:4px}.basket-code-details[open]>summary{color:var(--ink)}.basket-saved-note{margin-top:9px;white-space:pre-wrap;font-size:12px;line-height:1.55;overflow-wrap:anywhere}.basket-item-actions .button{font-size:11px;min-height:28px}.basket-item-actions [data-basket-action="remove-snippet"]{margin-left:auto;background:transparent;color:var(--muted);border-color:transparent}.basket-item-actions [data-basket-action="remove-snippet"]:hover{color:var(--danger);background:var(--surface)}.basket-empty{padding:22px 0 8px;color:var(--muted);font-size:12px;line-height:1.65}.basket-undo:not(:empty){display:flex;align-items:center;justify-content:space-between;gap:12px;border-top:1px solid var(--border);padding-top:12px;font-size:12px;color:var(--success)} +@media(max-width:350px){.basket-header,.basket-composer,.basket-saved{padding-inline:14px}.basket-actions .button{padding-inline:9px}.basket-title{font-size:18px}} diff --git a/src/shared/basket.js b/src/shared/basket.js new file mode 100644 index 0000000..a99a9be --- /dev/null +++ b/src/shared/basket.js @@ -0,0 +1,409 @@ +/* Local code excerpts. Page text is never interpreted as HTML. */ +(() => { + 'use strict'; + const G = globalThis.GHE = globalThis.GHE || {}; + const MAX_CODE = 20000; + const MAX_NOTE = 10000; + const MAX_TITLE = 300; + const plain = value => String(value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim(); + const markdownText = value => String(value ?? '').replace(/&/g, '&').replace(//g, '>').replace(/[\\`*_{}\[\]()#+.!|~\-]/g, '\\$&'); + + function sourceURL(snippet) { + const context = G.parseContext(snippet?.url); + if (!context || context.type !== 'code' || !/^\/[^/]+\/[^/]+\/blob\//.test(new URL(context.url).pathname)) throw new Error('Choose a supported GitHub code source.'); + const url = new URL(context.url); + if (!Number.isSafeInteger(snippet.lineStart) || !Number.isSafeInteger(snippet.lineEnd) || snippet.lineStart < 1 || snippet.lineEnd < snippet.lineStart) throw new Error('Choose a valid source line range.'); + url.hash = snippet.lineStart === snippet.lineEnd ? `L${snippet.lineStart}` : `L${snippet.lineStart}-L${snippet.lineEnd}`; + return url; + } + + function provenance(snippet) { + const url = sourceURL(snippet); + const match = url.pathname.match(/^\/[^/]+\/[^/]+\/blob\/([a-f0-9]{40})\//i); + return match ? `Commit permalink ยท ${match[1].slice(0, 12)}` : 'Branch or tag link ยท source may change'; + } + + function snippetMarkdown(snippet) { + const url = sourceURL(snippet).href.replace(/\(/g, '%28').replace(/\)/g, '%29'); + const code = String(snippet.code ?? ''); + const longest = Math.max(0, ...(code.match(/`+/g) || []).map(run => run.length)); + const fence = '`'.repeat(Math.max(3, longest + 1)); + const language = /^[a-z0-9_+.-]{1,40}$/i.test(snippet.language || '') ? snippet.language : ''; + const title = markdownText(plain(snippet.title || snippet.path || 'Code excerpt')); + const path = markdownText(plain(snippet.path || 'Source')); + const range = snippet.lineStart === snippet.lineEnd ? `line ${snippet.lineStart}` : `lines ${snippet.lineStart}โ€“${snippet.lineEnd}`; + const note = String(snippet.note || '').trim(); + return `## ${title}\n\n[${path} ยท ${range}](${url})\n\n${provenance(snippet)}\n\n${fence}${language}\n${code}${code.endsWith('\n') ? '' : '\n'}${fence}${note ? '\n\n' + note.split(/\r?\n/).map(line => '> ' + markdownText(line)).join('\n') : ''}\n`; + } + + function basketMarkdown(snippets, title = 'Code basket') { + return `# ${markdownText(plain(title) || 'Code basket')}\n\n${snippets.map(snippetMarkdown).join('\n')}`; + } + + function mountBasket(root, options) { + const document = root.ownerDocument; + const view = document.defaultView; + const composerDrafts = new Map(); + const composerBaselines = new Map(); + const snippetDrafts = new Map(); + const snippetBaselines = new Map(); + const touchedDraftKeys = new Set(); + const recoverySnapshots = new Map(); + const composerFields = ['start', 'end', 'title', 'note']; + const snippetFields = ['title', 'note']; + const editors = new Set(); + const expanded = new Set(); + let query = '', busy = false, undoItem = null; + let composer, list, listCount, search, undoArea, exportNotice; + root.classList.add('basket'); + + const state = () => options.getState() || {}; + const snippets = () => Array.isArray(state().snippets) ? state().snippets : []; + const findSnippet = id => snippets().find(item => item.id === id); + const sameFields = (left, right, fields) => fields.every(key => left?.[key] === right?.[key]); + function hasDrafts() { + for (const [url, draft] of composerDrafts) if (!sameFields(draft, composerBaselines.get(url), composerFields)) return true; + for (const [id, draft] of snippetDrafts) if (!sameFields(draft, snippetBaselines.get(id), snippetFields)) return true; + return false; + } + function draftSnapshot(key, draft) { + const fields = key.startsWith('composer:') ? composerFields : snippetFields; + return Object.fromEntries(fields.map(field => [field, draft[field]])); + } + async function clearRecovery(key, expected, message = 'Draft recovery could not be cleared. Please try again.') { + if (!expected) return true; + try { + await options.deleteToolDraft?.('basket', key, expected); + if (JSON.stringify(recoverySnapshots.get(key)) === JSON.stringify(expected)) recoverySnapshots.delete(key); + return true; + } catch { notify(message, true); return false; } + } + function persistDraft(key, draft, baseline) { + touchedDraftKeys.add(key); + const snapshot = draftSnapshot(key, draft); + const fields = key.startsWith('composer:') ? composerFields : snippetFields; + if (sameFields(snapshot, baseline, fields)) { + const previous = recoverySnapshots.get(key); + if (previous) void clearRecovery(key, previous); + return; + } + recoverySnapshots.set(key, snapshot); + const failed = () => notify('Draft recovery unavailable. Save your basket edits before closing.', true); + try { Promise.resolve(options.saveToolDraft?.('basket', key, snapshot)).catch(failed); } + catch { failed(); } + } + function persistComposer(url) { persistDraft('composer:' + url, composerDrafts.get(url), composerBaselines.get(url)); } + function persistSnippet(id) { persistDraft('snippet:' + id, snippetDrafts.get(id), snippetBaselines.get(id)); updateExportNotice(); } + function updateExportNotice(){if(exportNotice)exportNotice.hidden=!snippets().some(item=>snippetDrafts.has(item.id)&&!sameFields(snippetDrafts.get(item.id),item,snippetFields));} + function node(tag, className, text) { + const element = document.createElement(tag); + if (className) element.className = className; + if (text !== undefined) element.textContent = text; + return element; + } + function button(text, action, id, primary = false) { + const element = node('button', `button compact${primary ? ' primary' : ''}`, text); + element.type = 'button'; + element.dataset.basketAction = action; + if (id !== undefined) element.dataset.snippetId = id; + element.disabled = busy; + return element; + } + function field(labelText, input, key) { + const label = node('label', 'basket-field'); + input.dataset.basketFocus = key; + label.append(node('span', 'basket-label', labelText), input); + return label; + } + function notify(message, error = false) { options.notify?.(message, error); } + function activeFocus() { + const active = document.activeElement; + return root.contains(active) && active.dataset.basketFocus + ? {key: active.dataset.basketFocus, start: active.selectionStart, end: active.selectionEnd} + : null; + } + function restoreFocus(focus) { + if (!focus) return; + const target = [...root.querySelectorAll('[data-basket-focus]')].find(element => element.dataset.basketFocus === focus.key); + if (!target) return; + target.focus({preventScroll: true}); + if (typeof focus.start === 'number' && typeof target.setSelectionRange === 'function') { + try { target.setSelectionRange(focus.start, focus.end); } catch { /* Number fields have no selection range. */ } + } + } + + function currentCode() { + const code = options.getPageData()?.code; + if (!code || typeof code.text !== 'string' || typeof code.path !== 'string') return null; + const parsed = G.parseContext(code.url); + if (!parsed || parsed.type !== 'code' || !new URL(parsed.url).pathname.includes('/blob/')) return null; + const current = options.getContext?.(); + if (current?.url) { + const context = G.parseContext(current.url); + if (!context || new URL(context.url).pathname !== new URL(parsed.url).pathname) return null; + } + // A bounded page snapshot may end halfway through a source line. Never + // label that partial fragment as the complete line in a saved citation. + const text = code.truncated ? code.text.slice(0, Math.max(0, code.text.lastIndexOf('\n'))) : code.text; + return {...code, text, url: parsed.url.split('#')[0]}; + } + function composerDraft(code) { + if (!composerBaselines.has(code.url)) { + const length = code.text.split('\n').length; + const start = Number(code.selection?.start ?? 1); + const end = Number(code.selection?.end ?? Math.min(12, length)); + composerBaselines.set(code.url, {start: String(start), end: String(end), title: '', note: ''}); + } + if (!composerDrafts.has(code.url)) composerDrafts.set(code.url, {...composerBaselines.get(code.url)}); + return composerDrafts.get(code.url); + } + function selectedSnippet(code, draft) { + const lines = code.text.split('\n'); + const start = Number(draft.start), end = Number(draft.end); + if (!/^\d+$/.test(draft.start) || !/^\d+$/.test(draft.end) || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 1 || end < start || end > lines.length) throw new Error(code.selectionError&&start===code.selection?.start&&end===code.selection?.end?code.selectionError:`Selected lines are not fully available in this loaded snapshot. Choose a line range from 1 to ${lines.length.toLocaleString()}.`); + const selected = lines.slice(start - 1, end).join('\n'); + if (!selected.length) throw new Error('This range is empty. Choose lines containing code.'); + if (selected.length > MAX_CODE) throw new Error('Choose fewer lines. Each excerpt can contain up to 20,000 characters.'); + const revision = new URL(code.url).pathname.match(/^\/[^/]+\/[^/]+\/blob\/([a-f0-9]{40})\//i)?.[1]?.toLowerCase() || null; + return {url: code.url, title: plain(draft.title).slice(0, MAX_TITLE), path: code.path, language: code.language || '', lineStart: start, lineEnd: end, code: selected, note: draft.note, revision}; + } + + function renderComposer() { + composer.replaceChildren(); + const code = currentCode(); + composer.append(node('h3', 'basket-heading', 'Capture an excerpt')); + if (!code) { + composer.append(node('p', 'basket-description', 'Open a code file on GitHub to choose lines and add an excerpt. Your saved excerpts stay available below.')); + return; + } + if (!code.text.length) { + composer.append(node('p', 'basket-description', code.truncated ? 'This loaded source ends before its first complete line. No excerpt can be captured from this partial text.' : 'This file has no code to capture. Your saved excerpts remain available below.')); + return; + } + const draft = composerDraft(code); + const totalLines = code.text.split('\n').length; + composer.append(node('p', 'basket-path', code.path)); + const bytes = Number.isFinite(code.bytes) ? `${code.bytes.toLocaleString()} bytes` : null; + composer.append(node('p', 'basket-meta', `${totalLines.toLocaleString()} loaded lines${bytes ? ' ยท ' + bytes : ''}`)); + if (code.truncated) composer.append(node('p', 'basket-warning', 'Only part of this file is available. Excerpts use the loaded text shown here.')); + const fields = node('div', 'basket-range'); + for (const [name, label] of [['start', 'From line'], ['end', 'To line']]) { + const input = node('input', 'basket-input'); + input.type = 'number'; input.min = '1'; input.max = String(totalLines); input.step = '1'; input.value = draft[name]; + input.dataset.basketField = name; + fields.append(field(label, input, `composer:${code.url}:${name}`)); + input.addEventListener('input', () => { draft[name] = input.value; persistComposer(code.url); updatePreview(); }); + } + const useSelection = button('Use GitHub selection', 'use-selection'); + fields.append(useSelection); + const titleInput = node('input', 'basket-input'); + titleInput.type = 'text'; titleInput.maxLength = MAX_TITLE; titleInput.placeholder = 'A short label for this excerpt'; titleInput.value = draft.title; titleInput.dataset.basketField = 'title'; + titleInput.addEventListener('input', () => { draft.title = titleInput.value; persistComposer(code.url); updatePreview(); }); + const preview = node('pre', 'basket-preview'); preview.tabIndex = 0; preview.setAttribute('aria-label', 'Code excerpt preview'); preview.dataset.basketPreview = ''; + const rangeStatus = node('p', 'basket-meta'); rangeStatus.dataset.basketRangeStatus = ''; rangeStatus.setAttribute('role', 'status'); + const note = node('textarea', 'basket-note'); note.rows = 2; note.maxLength = MAX_NOTE; note.placeholder = 'Why is this code useful?'; note.value = draft.note; note.dataset.basketField = 'note'; + note.addEventListener('input', () => { draft.note = note.value; persistComposer(code.url); updatePreview(); }); + const actions = node('div', 'basket-actions'); + const save = button('Save excerpt', 'save-excerpt', undefined, true), copy = button('Copy Markdown', 'copy-excerpt'); + const discard = button('Discard draft', 'discard-composer'); + actions.append(save, copy, discard); + composer.append(fields, field('Title (optional)', titleInput, `composer:${code.url}:title`), preview, rangeStatus, field('Private note (optional)', note, `composer:${code.url}:note`), actions); + function updatePreview() { + discard.disabled = busy || sameFields(draft, composerBaselines.get(code.url), composerFields); + try { + const selected = selectedSnippet(code, draft); + preview.textContent = selected.code; + rangeStatus.textContent = `${(selected.lineEnd - selected.lineStart + 1).toLocaleString()} lines ยท ${selected.code.length.toLocaleString()} characters ยท ${provenance(selected)}`; + rangeStatus.classList.remove('basket-error'); save.disabled = busy; copy.disabled = busy; + } catch (error) { + preview.textContent = 'Choose a valid range to preview the code.'; + rangeStatus.textContent = error.message; rangeStatus.classList.add('basket-error'); save.disabled = true; copy.disabled = true; + } + } + updatePreview(); + } + + function renderList() { + const focus = activeFocus(); + list.replaceChildren(); + const all = snippets(); + const files = new Set(all.map(item => `${G.parseContext(item.url)?.repo}/${item.path}`)); + listCount.textContent = `${all.length} ${all.length === 1 ? 'excerpt' : 'excerpts'} ยท ${files.size} ${files.size === 1 ? 'file' : 'files'}`; + const words = query.toLocaleLowerCase().trim().split(/\s+/).filter(Boolean); + const filtered = all.filter(item => words.every(word => [item.title, item.path, item.note, item.code, item.url].join(' ').toLocaleLowerCase().includes(word))); + if (!filtered.length) { + list.append(node('p', 'basket-empty', all.length ? 'No excerpts match this search.' : 'Collect code from several files, add your context, and export it together.')); + } + for (const item of filtered) { + const article = node('article', 'basket-item'); article.dataset.basketSnippet = item.id; + const heading = node('div', 'basket-item-heading'); + const title = node('h4', 'basket-item-title', item.title || item.path); + heading.append(title); + article.append(heading); + const link = node('a', 'basket-source-link', `${item.path} ยท ${item.lineStart === item.lineEnd ? 'L' + item.lineStart : 'L' + item.lineStart + 'โ€“L' + item.lineEnd}`); + try { link.href = sourceURL(item).href; } catch { /* Invalid data remains inert. */ } + link.target = '_blank'; link.rel = 'noopener noreferrer'; article.append(link); + try { article.append(node('p', 'basket-meta', provenance(item))); } catch { /* Backend validates saved records. */ } + const details = node('details', 'basket-code-details'); details.open = expanded.has(item.id); + details.append(node('summary', '', 'Preview code')); + const preview = node('pre', 'basket-preview', item.code); preview.tabIndex = 0; preview.setAttribute('aria-label', `Code from ${item.path}`); details.append(preview); + details.addEventListener('toggle', () => { if (details.open) expanded.add(item.id); else expanded.delete(item.id); }); + article.append(details); + if (editors.has(item.id)) { + const draft = snippetDrafts.get(item.id) || {title: item.title || '', note: item.note || ''}; + if (!snippetBaselines.has(item.id)) snippetBaselines.set(item.id, {title: item.title || '', note: item.note || ''}); + snippetDrafts.set(item.id, draft); + const titleInput = node('input', 'basket-input'); titleInput.type = 'text'; titleInput.maxLength = MAX_TITLE; titleInput.value = draft.title; titleInput.dataset.basketEdit = 'title'; + titleInput.addEventListener('input', () => { draft.title = titleInput.value; persistSnippet(item.id); }); + const note = node('textarea', 'basket-note'); note.rows = 3; note.maxLength = MAX_NOTE; note.value = draft.note; note.dataset.basketEdit = 'note'; + note.addEventListener('input', () => { draft.note = note.value; persistSnippet(item.id); }); + const editActions = node('div', 'basket-actions'); editActions.append(button('Save note', 'save-snippet', item.id, true), button('Cancel edits', 'cancel-edit', item.id)); + article.append(field('Excerpt title', titleInput, `snippet:${item.id}:title`), field('Private note', note, `snippet:${item.id}:note`), editActions); + } else if (item.note) article.append(node('p', 'basket-saved-note', item.note)); + const actions = node('div', 'basket-actions basket-item-actions'); + if (!editors.has(item.id)) actions.append(button('Edit note', 'edit-snippet', item.id)); + actions.append(button('Copy excerpt', 'copy-snippet', item.id), button('Remove', 'remove-snippet', item.id)); + article.append(actions); list.append(article); + } + restoreFocus(focus); + } + + function renderUndo() { + undoArea.replaceChildren(); + if (undoItem) undoArea.append(node('span', '', 'Excerpt removed.'), button('Undo', 'undo-remove')); + } + function render() { + const focus = activeFocus(); + root.replaceChildren(); + const header = node('header', 'basket-header'); + header.append(node('h2', 'basket-title', 'Code basket'), node('p', 'basket-description', 'Keep useful code from different files, with the source and your notes.')); + composer = node('section', 'basket-composer'); composer.dataset.basketComposer = ''; + const savedSection = node('section', 'basket-saved'); + const heading = node('div', 'basket-section-heading'); + heading.append(node('h3', 'basket-heading', 'Saved excerpts')); + listCount = node('span', 'basket-meta'); heading.append(listCount); + const exportActions = node('div', 'basket-actions'); + const copy = button('Copy basket', 'copy-basket'), download = button('Download .md', 'download-basket'); + copy.disabled = download.disabled = busy || !snippets().length; + exportActions.append(copy, download); + exportNotice=node('p','basket-meta','Export uses saved notes and titles. Save your edits to include them.');exportNotice.dataset.basketExportNotice='';updateExportNotice(); + search = node('input', 'basket-input basket-search'); search.type = 'search'; search.placeholder = 'Search paths, code, or notesโ€ฆ'; search.value = query; search.setAttribute('aria-label', 'Search code basket'); search.dataset.basketFocus = 'search'; + search.addEventListener('input', () => { query = search.value; renderList(); }); + list = node('div', 'basket-list'); + undoArea = node('div', 'basket-undo'); undoArea.setAttribute('role', 'status'); + savedSection.append(heading, exportActions, exportNotice, search, list, undoArea); + root.append(header, composer, savedSection); + renderComposer(); renderList(); renderUndo(); restoreFocus(focus); + } + + async function mutate(message, success, after) { + if (busy) return; + busy = true; render(); + try { + const next = await options.request(message); + options.onState(next); + if (await after?.() !== false) notify(success); + } catch (error) { notify(error.message || 'Could not save this change. Try again.', true); } + finally { busy = false; render(); } + } + async function copyMarkdown(text, label) { + try { await options.copy(text); notify(`${label} copied`); } + catch { notify('Clipboard unavailable. Try the Chrome toolbar popup.', true); } + } + function downloadMarkdown() { + const text = basketMarkdown(snippets()); + const url = view.URL.createObjectURL(new view.Blob([text], {type: 'text/markdown;charset=utf-8'})); + const link = node('a'); link.href = url; link.download = `github-code-basket-${new Date().toISOString().slice(0, 10)}.md`; + document.body.append(link); link.click(); link.remove(); + view.setTimeout(() => view.URL.revokeObjectURL(url), 1000); + notify('Markdown download started. It includes saved code and notes.'); + } + + root.addEventListener('click', async event => { + const control = event.target.closest('[data-basket-action]'); + if (!control || !root.contains(control) || control.disabled) return; + const action = control.dataset.basketAction, id = control.dataset.snippetId; + try { + if (action === 'use-selection') { + const code = currentCode(); if (!code) return; + const draft = composerDraft(code), lines = code.text.split('\n').length; + draft.start = String(code.selection?.start ?? 1); + draft.end = String(code.selection?.end ?? Math.min(12, lines)); + persistComposer(code.url); + render(); + } else if (action === 'discard-composer') { + const code = currentCode(); if (!code) return; + const key = 'composer:' + code.url, expected = draftSnapshot(key, composerDraft(code)); + touchedDraftKeys.add(key); + composerDrafts.set(code.url, {...composerBaselines.get(code.url)}); render(); + if (await clearRecovery(key, expected)) notify('Composer draft discarded'); + } else if (action === 'save-excerpt' || action === 'copy-excerpt') { + const code = currentCode(); if (!code) return; + const snippet = selectedSnippet(code, composerDraft(code)); + if (action === 'save-excerpt') { + const submitted = {...composerDraft(code)}; + const key = 'composer:' + code.url; + touchedDraftKeys.add(key); + await mutate({type: 'SAVE_SNIPPET', snippet}, 'Excerpt saved to your code basket', async () => { + composerBaselines.set(code.url, submitted); + return clearRecovery(key, submitted, 'Excerpt saved, but its recovery draft could not be cleared.'); + }); + } + else await copyMarkdown(snippetMarkdown(snippet), 'Excerpt Markdown'); + } else if (action === 'edit-snippet') { + editors.add(id); render(); + [...root.querySelectorAll('[data-basket-focus]')].find(element => element.dataset.basketFocus === `snippet:${id}:note`)?.focus(); + } else if (action === 'cancel-edit') { + const key = 'snippet:' + id, expected = snippetDrafts.get(id) && draftSnapshot(key, snippetDrafts.get(id)); + touchedDraftKeys.add(key); snippetDrafts.delete(id); snippetBaselines.delete(id); editors.delete(id); render(); + await clearRecovery(key, expected); + } + else if (action === 'save-snippet') { + const draft = snippetDrafts.get(id); if (!draft || !findSnippet(id)) return; + const patch = {title: plain(draft.title).slice(0, MAX_TITLE), note: draft.note}; + const submitted = {...draft}; + const key = 'snippet:' + id; + touchedDraftKeys.add(key); + await mutate({type: 'UPDATE_SNIPPET', id, patch}, 'Excerpt note saved', async () => { + const current = snippetDrafts.get(id); + if (current?.title === submitted.title && current?.note === submitted.note) { snippetDrafts.delete(id); snippetBaselines.delete(id); editors.delete(id); } + else snippetBaselines.set(id, submitted); + return clearRecovery(key, submitted, 'Excerpt note saved, but its recovery draft could not be cleared.'); + }); + } else if (action === 'remove-snippet') { + const snippet = findSnippet(id); if (!snippet) return; + await mutate({type: 'REMOVE_SNIPPET', id}, 'Excerpt removed', () => { undoItem = snippet; }); + } else if (action === 'undo-remove' && undoItem) { + const snippet = undoItem; + await mutate({type: 'RESTORE_SNIPPET', snippet}, 'Excerpt restored', () => { if (undoItem === snippet) undoItem = null; }); + } else if (action === 'copy-snippet') { + const snippet = findSnippet(id); if (snippet) await copyMarkdown(snippetMarkdown(snippet), 'Excerpt Markdown'); + } else if (action === 'copy-basket') await copyMarkdown(basketMarkdown(snippets()), 'Code basket'); + else if (action === 'download-basket') downloadMarkdown(); + } catch (error) { notify(error.message || 'This action could not be completed.', true); } + }); + render(); + const ready = Promise.resolve().then(() => options.loadToolDrafts?.('basket') || []).then(recovered => { + if (!Array.isArray(recovered)) return; + for (const entry of recovered.slice(0, 200)) { + if (!Array.isArray(entry) || entry.length !== 2) continue; + const [key, value] = entry; + if (typeof key !== 'string' || touchedDraftKeys.has(key) || !value || typeof value !== 'object' || Array.isArray(value)) continue; + if (typeof value.title !== 'string' || value.title.length > MAX_TITLE || typeof value.note !== 'string' || value.note.length > MAX_NOTE) continue; + if (key.startsWith('composer:')) { + const url = key.slice(9), context = G.parseContext(url); + if (!context || context.type !== 'code' || !new URL(context.url).pathname.includes('/blob/') || !['start', 'end'].every(field => typeof value[field] === 'string' && /^[+-]?\d{0,10}$/.test(value[field]))) continue; + const snapshot = draftSnapshot(key, value); + composerDrafts.set(url, snapshot); recoverySnapshots.set(key, {...snapshot}); + } else if (key.startsWith('snippet:') && /^[a-zA-Z0-9_-]{1,100}$/.test(key.slice(8))) { + const id = key.slice(8), snapshot = draftSnapshot(key, value); + snippetDrafts.set(id, snapshot); recoverySnapshots.set(key, {...snapshot}); editors.add(id); + } + } + render(); + }).catch(() => notify('Basket draft recovery unavailable. Saved excerpts are still available.', true)); + return {render, hasDrafts, ready, reveal(id){if(!findSnippet(id))return false;query='';search.value='';expanded.add(id);render();const card=[...list.querySelectorAll('[data-basket-snippet]')].find(node=>node.dataset.basketSnippet===id);if(card){card.tabIndex=-1;card.focus({preventScroll:true});card.scrollIntoView?.({block:'nearest'});}return Boolean(card);}}; + } + + Object.assign(G, {mountBasket, snippetMarkdown, basketMarkdown}); +})(); diff --git a/src/shared/client.js b/src/shared/client.js new file mode 100644 index 0000000..ebe5840 --- /dev/null +++ b/src/shared/client.js @@ -0,0 +1,56 @@ +(() => { + async function request(message) { + let response; + try { response = await chrome.runtime.sendMessage(message); } + catch { throw new Error('Extension connection lost. Reload this page and try again.'); } + if (response?.ok === false && typeof response.error === 'string' && response.error.trim()) throw new Error(response.error); + if (response?.ok !== true || !response.state || typeof response.state !== 'object' || Array.isArray(response.state)) { + throw new Error('Extension did not respond. Reload GitHub Enhancer in chrome://extensions, then reload this GitHub page.'); + } + return response.state; + } + async function copy(text) { + try { await navigator.clipboard.writeText(text); } + catch { + const input=document.createElement('textarea');input.value=text;input.style.position='fixed';input.style.opacity='0';document.body.append(input);input.select(); + const ok=document.execCommand('copy');input.remove();if(!ok)throw new Error('Clipboard unavailable'); + } + } + const prefix='ghe:draft:'; + // All extension surfaces share this origin-wide lock, including popup and panel. + const withDraftLock=operation=>navigator.locks.request('ghe-drafts',operation); + // Recovery copies are already safe to leave behind. Warn only while the + // latest edit in this surface has not reached session storage successfully. + const unprotectedDrafts=new Map();let draftVersion=0; + const hasUnprotectedDrafts=()=>unprotectedDrafts.size>0; + function saveRecovery(key,value){ + const write={version:++draftVersion,value};unprotectedDrafts.set(key,write); + return (async()=>{ + await withDraftLock(()=>chrome.storage.session.set({[key]:value})); + if(unprotectedDrafts.get(key)===write)unprotectedDrafts.delete(key); + })(); + } + function deleteRecovery(key,expected){ + const write=unprotectedDrafts.get(key); + return withDraftLock(async()=>{ + const data=await chrome.storage.session.get(key); + if(data[key]===expected)await chrome.storage.session.remove(key); + // Saving permanently or explicitly discarding an edit also makes it safe + // to leave. A newer queued edit must retain its own protection. + if(write?.value===expected&&unprotectedDrafts.get(key)===write)unprotectedDrafts.delete(key); + }); + } + function toolPrefix(kind){if(!['basket','review','workspaces','composer'].includes(kind))throw new Error('Unknown draft kind');return 'ghe:tool-draft:'+kind+':';} + function toolKey(kind,key){if(typeof key!=='string'||key.length>3000)throw new Error('Invalid draft key');return toolPrefix(kind)+encodeURIComponent(key);} + function draftJSON(value){if(!value||typeof value!=='object'||Array.isArray(value))throw new Error('Invalid draft');const text=JSON.stringify(Object.fromEntries(Object.keys(value).sort().map(key=>[key,value[key]])));if(text.length>22000)throw new Error('Draft is too large');return text;} + const draftOptions={ + loadToolDrafts:kind=>withDraftLock(async()=>{const prefix=toolPrefix(kind),data=await chrome.storage.session.get(null),result=[];for(const [key,value] of Object.entries(data)){if(!key.startsWith(prefix)||typeof value!=='string'||value.length>22000)continue;try{const parsed=JSON.parse(value);draftJSON(parsed);result.push([decodeURIComponent(key.slice(prefix.length)),parsed]);}catch{}}return result;}), + saveToolDraft:(kind,key,value)=>{const id=toolKey(kind,key);let text;try{text=draftJSON(value);}catch(error){unprotectedDrafts.set(id,{version:++draftVersion,value:undefined});throw error;}return saveRecovery(id,text);}, + deleteToolDraft:(kind,key,expected)=>{const id=toolKey(kind,key),text=draftJSON(expected);return deleteRecovery(id,text);}, + loadDrafts:()=>withDraftLock(async()=>{const data=await chrome.storage.session.get(null);return Object.entries(data).filter(([key,value])=>key.startsWith(prefix)&&typeof value==='string'&&value.length<=10000).map(([key,value])=>[decodeURIComponent(key.slice(prefix.length)),value]);}), + saveDraft:(url,note)=>saveRecovery(prefix+encodeURIComponent(url),note), + deleteDraft:(url,expectedNote)=>deleteRecovery(prefix+encodeURIComponent(url),expectedNote) + }; + async function openPages(urls){for(const value of urls.slice(0,10)){const context=globalThis.GHE.parseContext(value);if(!context)throw new Error('Unsupported workspace URL');await chrome.tabs.create({url:context.url,active:false});}} + Object.assign(globalThis.GHE, {request,copy,draftOptions,openPages,hasUnprotectedDrafts}); +})(); diff --git a/src/shared/composer.css b/src/shared/composer.css new file mode 100644 index 0000000..cf749a5 --- /dev/null +++ b/src/shared/composer.css @@ -0,0 +1,2 @@ +.write-composer{color:var(--ink);min-width:0}.composer-header{padding:20px 22px 16px}.composer-title{font-size:20px;letter-spacing:-.025em;line-height:1.3;margin:0 0 7px}.composer-description{font-size:12px;color:var(--muted);line-height:1.6}.composer-context{margin-inline:22px;padding:12px 0;border-block:1px solid var(--border)}.composer-label{display:block;font-size:12px;font-weight:550}.composer-context-link{display:block;font-size:13px;font-weight:550;line-height:1.5;overflow-wrap:anywhere;margin:6px 0 3px}.composer-context>.composer-description{margin-top:6px}.composer-meta{font-size:11px;color:var(--muted);line-height:1.5}.composer-editor{padding:6px 22px 20px}.composer-field{display:flex;flex-direction:column;gap:6px;min-width:0;margin-block:12px}.composer-body,.composer-template-body{background:var(--canvas);color:var(--ink);border:1px solid var(--border);border-radius:7px;padding:11px;font:12px/1.65 ui-monospace,SFMono-Regular,Consolas,monospace;resize:vertical;max-height:440px;min-height:210px;tab-size:2}.composer-body::placeholder{font-family:var(--sans);font-size:12px;line-height:1.65}.composer-actions{display:flex;flex-wrap:wrap;gap:7px;margin-block:12px}.composer-private{font-size:11px;color:var(--muted);line-height:1.6}.composer-preview{margin-top:12px}.composer-preview>summary{font-size:11px;color:var(--muted);cursor:pointer;padding-block:4px}.composer-source{white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.65 ui-monospace,SFMono-Regular,Consolas,monospace;background:var(--surface);color:var(--ink);border:1px solid var(--border);border-radius:7px;padding:11px;max-height:220px;overflow:auto;margin-block:10px}.composer-library{padding:20px 22px;border-top:1px solid var(--border)}.composer-section-heading{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:8px}.composer-section-heading h3{font-size:14px;font-weight:650;margin:0}.composer-input{width:100%;min-width:0;border:1px solid var(--border);border-radius:7px;padding:8px 10px;background:var(--canvas);color:var(--ink);font-size:12px;line-height:1.5}.composer-library>select{margin-top:12px}.composer-template-preview{max-height:170px}.composer-template-editor{padding-block:15px;margin-top:16px;border-block:1px solid var(--border)}.composer-template-editor h4,.composer-create h4{font-size:12px;font-weight:650;margin:0}.composer-template-body{min-height:135px}.composer-create{margin-top:20px}.composer-undo{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:18px;padding-top:12px;border-top:1px solid var(--border);font-size:12px;color:var(--success)}.composer-actions [data-composer-action="remove-template"],.composer-actions [data-composer-action="discard"]{background:transparent;border-color:transparent;color:var(--muted);margin-left:auto}.composer-actions [data-composer-action="remove-template"]:hover,.composer-actions [data-composer-action="discard"]:hover{background:var(--surface);color:var(--danger)} +@media(max-width:350px){.composer-header,.composer-editor,.composer-library{padding-inline:14px}.composer-context{margin-inline:14px}.composer-title{font-size:18px}} diff --git a/src/shared/composer.js b/src/shared/composer.js new file mode 100644 index 0000000..13454d9 --- /dev/null +++ b/src/shared/composer.js @@ -0,0 +1,271 @@ +/* Private Markdown preparation. No page filling or GitHub submission. */ +(() => { + 'use strict'; + const G = globalThis.GHE = globalThis.GHE || {}; + const MAX_BODY = 10000, MAX_TITLE = 100, MAX_TEMPLATES = 40; + const starters = [ + {id: 'review-feedback', title: 'Review feedback', body: '## Observation\n\nWhat did you notice?\n\n## Why it matters\n\nDescribe the behavior or risk.\n\n## Suggested change\n\nExplain a concrete next step.\n\n## Verification\n\nHow could we check the result?'}, + {id: 'bug-reproduction', title: 'Bug reproduction', body: '## What happened\n\nDescribe the unexpected behavior.\n\n## Steps to reproduce\n\n1. \n2. \n3. \n\n## Expected behavior\n\nWhat should happen instead?\n\n## Environment\n\nInclude the relevant version and setup.'} + ]; + + function composerContextKey(context) { + const parsed = G.parseContext(context?.url); + if (!parsed || !['issue', 'pull', 'discussion', 'commit'].includes(parsed.type)) return 'global'; + const url = new URL(parsed.url); + url.hash = ''; + if (parsed.type === 'pull') url.pathname = url.pathname.split('/').slice(0, 5).join('/'); + return url.href; + } + + function mountComposer(root, options) { + const document = root.ownerDocument; + const drafts = new Map(), touched = new Set(), recoveredSnapshots = new Map(); + const templateEdits = new Map(), templateBaselines = new Map(); + let selected = '', editing = null, newTitle = '', busy = false, undo = null, previewOpen = false; + root.classList.add('write-composer'); + const templates = () => options.getState()?.templates || []; + const currentKey = () => composerContextKey(options.getContext?.()); + const bodyFor = key => drafts.get(key) || ''; + const savedTemplate = id => templates().find(template => template.id === id); + const selectedTemplate = () => selected.startsWith('builtin:') ? starters.find(template => template.id === selected.slice(8)) : selected.startsWith('saved:') ? savedTemplate(selected.slice(6)) : null; + const notify = (message, error = false) => options.notify?.(message, error); + + function element(tag, cls, text) { + const node = document.createElement(tag); + if (cls) node.className = cls; + if (text !== undefined) node.textContent = text; + return node; + } + function button(label, action, primary = false) { + const node = element('button', `button compact${primary ? ' primary' : ''}`, label); + node.type = 'button'; node.dataset.composerAction = action; node.disabled = busy; + return node; + } + function field(label, input, focus) { + const node = element('label', 'composer-field'); + input.setAttribute('aria-label', label); input.dataset.composerFocus = focus; + node.append(element('span', 'composer-label', label), input); + return node; + } + function focusState() { + const active = document.activeElement; + return root.contains(active) && active.dataset.composerFocus ? {key: active.dataset.composerFocus, start: active.selectionStart, end: active.selectionEnd} : null; + } + function restoreFocus(focus) { + if (!focus) return; + const node = [...root.querySelectorAll('[data-composer-focus]')].find(input => input.dataset.composerFocus === focus.key); + if (!node) return; + node.focus({preventScroll: true}); + if (typeof focus.start === 'number' && node.setSelectionRange) node.setSelectionRange(focus.start, focus.end); + } + async function clearRecovery(key, snapshot) { + if (!snapshot) return true; + try { + await options.deleteToolDraft?.('composer', key, snapshot); + if (JSON.stringify(recoveredSnapshots.get(key)) === JSON.stringify(snapshot)) recoveredSnapshots.delete(key); + return true; + } catch { notify('The draft was cleared here, but its recovery copy could not be removed. Try again before closing.', true); return false; } + } + function persistMetadata(key, snapshot) { + touched.add(key); recoveredSnapshots.set(key, {...snapshot}); + const failed = () => notify('Draft recovery unavailable. Save your template changes before closing.', true); + try { Promise.resolve(options.saveToolDraft?.('composer', key, snapshot)).catch(failed); } + catch { failed(); } + } + function editBody(key, body) { + touched.add(key); drafts.set(key, body); + if (!body) { + const previous = recoveredSnapshots.get(key); + if (previous) void clearRecovery(key, previous); + return; + } + const snapshot = {body}; recoveredSnapshots.set(key, snapshot); + const failed = () => notify('Draft recovery unavailable. Copy your draft before closing.', true); + try { Promise.resolve(options.saveToolDraft?.('composer', key, snapshot)).catch(failed); } + catch { failed(); } + } + function hasDrafts() { + if (newTitle.trim() || [...drafts.values()].some(body => body.length > 0)) return true; + for (const [id, draft] of templateEdits) { + const original = templateBaselines.get(id); + if (savedTemplate(id) && (draft.title !== original?.title || draft.body !== original?.body)) return true; + } + return false; + } + async function mutate(message, success, after) { + if (busy) return; + busy = true; render(); + try { const next = await options.request(message); options.onState(next); if (await after?.(next) !== false) notify(success); } + catch (error) { notify(error.message || 'Could not save your template. Try again.', true); } + finally { busy = false; render(); } + } + + function render() { + const focus = focusState(), key = currentKey(), context = options.getContext?.(); + const body = bodyFor(key), choice = selectedTemplate(); + root.replaceChildren(); root.setAttribute('aria-busy', String(busy)); + const heading = element('header', 'composer-header'); + heading.append(element('h2', 'composer-title', 'Write'), element('p', 'composer-description', 'Prepare a clear comment in Markdown. Copy it when you are ready.')); + root.append(heading); + + const contextPanel = element('section', 'composer-context'); + contextPanel.append(element('span', 'composer-label', key === 'global' ? 'General draft' : 'Draft for this thread')); + if (key === 'global') contextPanel.append(element('p', 'composer-description', 'Open an issue, pull request, discussion, or commit for a separate thread draft.')); + else { + const link = element('a', 'composer-context-link', context?.title || context?.repo || 'Current thread'); + link.href = key; link.target = '_blank'; link.rel = 'noopener noreferrer'; link.dataset.composerContextLink = ''; + contextPanel.append(link, element('p', 'composer-meta', context?.repo || new URL(key).pathname.split('/').slice(1, 3).join('/'))); + } + root.append(contextPanel); + + const editorSection = element('section', 'composer-editor'); + const bodyInput = element('textarea', 'composer-body'); bodyInput.rows = 10; bodyInput.maxLength = MAX_BODY; bodyInput.value = body; bodyInput.placeholder = 'Write your comment, review feedback, or investigation notesโ€ฆ'; + editorSection.append(field('Markdown draft', bodyInput, 'draft:' + key)); + const counter = element('p', 'composer-meta'); counter.setAttribute('aria-live', 'off'); + const actions = element('div', 'composer-actions'); + const copy = button('Copy Markdown', 'copy', true), discard = button('Discard draft', 'discard'); actions.append(copy, discard); + editorSection.append(counter, actions, element('p', 'composer-private', 'Private in this browser. Nothing is posted or inserted into GitHub.')); + const preview = element('details', 'composer-preview'); preview.open = previewOpen; + preview.append(element('summary', '', 'Preview Markdown source')); + const previewText = element('pre', 'composer-source'); previewText.dataset.composerPreview = ''; previewText.tabIndex = 0; previewText.setAttribute('aria-label', 'Markdown source preview'); preview.append(previewText); + preview.addEventListener('toggle', () => { if (preview.isConnected) previewOpen = preview.open; }); + editorSection.append(preview); root.append(editorSection); + + const library = element('section', 'composer-library'); + const libraryHeading = element('div', 'composer-section-heading'); + libraryHeading.append(element('h3', '', 'Reusable templates'), element('span', 'composer-meta', `${templates().length} / ${MAX_TEMPLATES} saved`)); + library.append(libraryHeading, element('p', 'composer-description', 'Choose a starting point, preview it, then use it explicitly.')); + const picker = element('select', 'composer-input'); picker.setAttribute('aria-label', 'Choose a template'); picker.dataset.composerFocus = 'template-picker'; + const empty = element('option', '', 'Choose a templateโ€ฆ'); empty.value = ''; picker.append(empty); + const builtins = element('optgroup'); builtins.label = 'Starter templates'; + for (const template of starters) { const option = element('option', '', template.title); option.value = 'builtin:' + template.id; builtins.append(option); } + picker.append(builtins); + if (templates().length) { + const own = element('optgroup'); own.label = 'Your templates'; + for (const template of templates()) { const option = element('option', '', template.title); option.value = 'saved:' + template.id; own.append(option); } + picker.append(own); + } + picker.value = choice ? selected : ''; + picker.addEventListener('change', () => { selected = picker.value; const id = selected.startsWith('saved:') ? selected.slice(6) : null; editing = id && templateEdits.has(id) ? id : null; render(); }); + library.append(picker); + let useTemplate; + if (choice) { + const templatePreview = element('pre', 'composer-source composer-template-preview', choice.body); templatePreview.tabIndex = 0; templatePreview.setAttribute('aria-label', 'Selected template preview'); + library.append(templatePreview); + const templateActions = element('div', 'composer-actions'); useTemplate = button('', 'use-template'); templateActions.append(useTemplate); + if (selected.startsWith('saved:')) templateActions.append(button('Edit template', 'edit-template'), button('Remove', 'remove-template')); + library.append(templateActions); + } + if (editing && savedTemplate(editing)) { + const original = savedTemplate(editing); + if (!templateEdits.has(editing)) templateEdits.set(editing, {title: original.title, body: original.body}); + if (!templateBaselines.has(editing)) templateBaselines.set(editing, {title: original.title, body: original.body}); + const draft = templateEdits.get(editing), editBox = element('section', 'composer-template-editor'); + editBox.append(element('h4', '', 'Edit saved template')); + const title = element('input', 'composer-input'); title.type = 'text'; title.maxLength = MAX_TITLE; title.value = draft.title; + const text = element('textarea', 'composer-template-body'); text.rows = 6; text.maxLength = MAX_BODY; text.value = draft.body; + title.addEventListener('input', () => { draft.title = title.value; persistMetadata('templateedit:' + original.id, draft); }); text.addEventListener('input', () => { draft.body = text.value; persistMetadata('templateedit:' + original.id, draft); }); + const editActions = element('div', 'composer-actions'); editActions.append(button('Save template', 'save-template', true), button('Cancel editing', 'cancel-template')); + editBox.append(field('Template name', title, 'template-title:' + editing), field('Template body', text, 'template-body:' + editing), editActions); library.append(editBox); + } + const creation = element('section', 'composer-create'); creation.append(element('h4', '', 'Save this draft as a template')); + const name = element('input', 'composer-input'); name.type = 'text'; name.maxLength = MAX_TITLE; name.value = newTitle; name.placeholder = 'e.g. Reproduction request'; + const create = button('Save new template', 'create-template'); + name.addEventListener('input', () => { newTitle = name.value; persistMetadata('newtemplate', {title: newTitle}); updateDraftControls(); }); + creation.append(field('New template name', name, 'new-template-name'), create); + if (templates().length >= MAX_TEMPLATES) creation.append(element('p', 'composer-meta', 'Your template library is full. Remove an unused template to add another.')); + library.append(creation); + if (undo) { + const undoRow = element('div', 'composer-undo'); undoRow.setAttribute('role', 'status'); + undoRow.append(element('span', '', 'Template removed.'), button('Undo', 'undo-template')); library.append(undoRow); + } + root.append(library); + + function updateDraftControls() { + const value = bodyFor(key); + counter.textContent = `${value.length.toLocaleString()} / 10,000 characters ยท draft recovery lasts for this browser session`; + previewText.textContent = value || 'Your Markdown source will appear here.'; + copy.disabled = busy || !value.trim(); discard.disabled = busy || !value.length; + if (useTemplate) useTemplate.textContent = value.length ? 'Replace draft with template' : 'Use template'; + create.disabled = busy || !value.trim() || !newTitle.trim() || templates().length >= MAX_TEMPLATES; + } + bodyInput.addEventListener('input', () => { editBody(key, bodyInput.value); updateDraftControls(); }); + updateDraftControls(); restoreFocus(focus); + } + + root.addEventListener('click', async event => { + const control = event.target.closest('[data-composer-action]'); + if (!control || !root.contains(control) || control.disabled) return; + const action = control.dataset.composerAction, key = currentKey(); + if (action === 'copy') { + const body = bodyFor(key); if (!body.trim()) return; + try { await options.copy(body); notify('Markdown copied. Paste it into GitHub when you are ready.'); } + catch { notify('Clipboard unavailable. Select your draft and copy it manually.', true); } + } else if (action === 'discard') { + const snapshot = {body: bodyFor(key)}; touched.add(key); drafts.set(key, ''); render(); + if (await clearRecovery(key, snapshot)) notify('Draft discarded'); + } else if (action === 'use-template') { + const template = selectedTemplate(); if (!template) return; + editBody(key, template.body); render(); + const input = root.querySelector('[aria-label="Markdown draft"]'); input.focus(); input.setSelectionRange(input.value.length, input.value.length); + } else if (action === 'create-template') { + const submittedTitle = newTitle, title = newTitle.trim(), body = bodyFor(key); touched.add('newtemplate'); + if (!title || !body.trim()) { notify('Add a name and draft text before saving a template.', true); return; } + const previous = new Set(templates().map(template => template.id)); + await mutate({type: 'CREATE_TEMPLATE', title, body}, 'Template saved', async next => { + if (newTitle === submittedTitle) newTitle = ''; + const created = next.templates.find(template => !previous.has(template.id)); + if (created) selected = 'saved:' + created.id; + return clearRecovery('newtemplate', {title: submittedTitle}); + }); + } else if (action === 'edit-template') { + const template = selectedTemplate(); if (!template || !selected.startsWith('saved:')) return; + editing = template.id; render(); root.querySelector('[aria-label="Template body"]')?.focus(); + } else if (action === 'cancel-template') { + const id = editing, snapshot = templateEdits.get(id); touched.add('templateedit:' + id); + templateEdits.delete(id); templateBaselines.delete(id); editing = null; render(); + await clearRecovery('templateedit:' + id, snapshot); + } else if (action === 'save-template' && editing) { + const id = editing, submitted = {...templateEdits.get(id)}, patch = {title: submitted.title.trim(), body: submitted.body}; touched.add('templateedit:' + id); + if (!patch.title || !patch.body.trim()) { notify('A template needs both a name and body.', true); return; } + await mutate({type: 'UPDATE_TEMPLATE', id, patch}, 'Template updated', async () => { + const current = templateEdits.get(id); + if (current?.title === submitted.title && current?.body === submitted.body) { templateEdits.delete(id); templateBaselines.delete(id); if (editing === id) editing = null; } + else templateBaselines.set(id, submitted); + return clearRecovery('templateedit:' + id, submitted); + }); + } else if (action === 'remove-template') { + const template = selectedTemplate(); if (!template || !selected.startsWith('saved:')) return; + await mutate({type: 'REMOVE_TEMPLATE', id: template.id}, 'Template removed', () => { undo = template; if (selected === 'saved:' + template.id) selected = ''; if (editing === template.id) editing = null; }); + } else if (action === 'undo-template' && undo) { + const template = undo; + await mutate({type: 'RESTORE_TEMPLATE', template}, 'Template restored', () => { if (undo === template) undo = null; selected = 'saved:' + template.id; if (templateEdits.has(template.id)) editing = template.id; }); + } + }); + render(); + const ready = Promise.resolve().then(() => options.loadToolDrafts?.('composer') || []).then(entries => { + if (!Array.isArray(entries)) return; + for (const entry of entries) { + if (!Array.isArray(entry) || entry.length !== 2) continue; + const [key, value] = entry; + if (typeof key !== 'string' || touched.has(key) || !value || typeof value !== 'object') continue; + if (key === 'newtemplate') { + if (typeof value.title === 'string' && value.title.length <= MAX_TITLE) { newTitle = value.title; recoveredSnapshots.set(key, {title: value.title}); } + continue; + } + if (key.startsWith('templateedit:')) { + const id = key.slice(13), original = savedTemplate(id); + if (/^[a-zA-Z0-9_-]{1,80}$/.test(id) && typeof value.title === 'string' && value.title.length <= MAX_TITLE && typeof value.body === 'string' && value.body.length <= MAX_BODY) { + const snapshot = {title: value.title, body: value.body}; templateEdits.set(id, snapshot); if (original) templateBaselines.set(id, {title: original.title, body: original.body}); recoveredSnapshots.set(key, {...snapshot}); + } + continue; + } + if ((key !== 'global' && composerContextKey({url: key}) !== key) || !value || typeof value !== 'object' || typeof value.body !== 'string' || value.body.length > MAX_BODY) continue; + drafts.set(key, value.body); recoveredSnapshots.set(key, {body: value.body}); + } + render(); + }).catch(() => notify('Composer draft recovery unavailable. Copy your draft before closing.', true)); + return {render, ready, hasDrafts}; + } + Object.assign(G, {mountComposer, composerContextKey}); +})(); diff --git a/src/shared/conversation.css b/src/shared/conversation.css new file mode 100644 index 0000000..4468dc5 --- /dev/null +++ b/src/shared/conversation.css @@ -0,0 +1,4 @@ +.conversation-controls{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;margin:14px 0}.conversation-controls input[type=search]{grid-column:1/-1;width:100%}.conversation-controls select{min-width:0;max-width:100%}.conversation-saved{display:flex;align-items:center;gap:6px;font-size:12px}.conversation-count{font-size:12px;color:var(--muted);margin:14px 0 8px}.conversation-card{padding:14px 0;border-top:1px solid var(--border)}.conversation-card h3{font-size:12px;margin:0 0 8px;overflow-wrap:anywhere}.conversation-text{margin:8px 0 12px;font-size:12px;line-height:1.6;overflow-wrap:anywhere}.conversation-text summary{cursor:pointer}.conversation-text pre{white-space:pre-wrap;font:inherit;max-height:300px;overflow:auto}.conversation-limit{font-size:12px;color:var(--ink);border-left:2px solid var(--accent);padding-left:10px} + +.conversation-controls input[type=search],.conversation-controls select{background:var(--canvas);color:var(--ink);border:1px solid var(--border);border-radius:6px;padding:9px;font-size:12px} +.conversation-text mark{color:var(--ink);background:var(--accent-soft);font-weight:650;border-radius:2px;padding:0 1px} diff --git a/src/shared/conversation.js b/src/shared/conversation.js new file mode 100644 index 0000000..9a48ec4 --- /dev/null +++ b/src/shared/conversation.js @@ -0,0 +1,62 @@ +/* Local navigation over the bounded snapshot; GitHub's conversation is untouched. */ +(() => { + const G=globalThis.GHE; + const node=(tag,cls,text)=>{const el=document.createElement(tag);if(cls)el.className=cls;if(text!==undefined)el.textContent=text;return el;}; + const button=(text,action,id)=>{const el=node('button','button compact',text);el.type='button';el.dataset.conversation=action;el.dataset.id=id;return el;}; + G.mountConversation=(root,options)=>{ + let query='',author='',onlySaved=false,busy=false,lastThread=''; + const expanded=new Set(); + const snapshot=()=>options.getPageData()?.conversation; + const comments=()=>snapshot()?.comments||[]; + const saved=url=>(options.getState().items||[]).some(item=>item.url===url); + function rememberExpanded(){for(const details of root.querySelectorAll('details[data-comment-id]')){if(details.open)expanded.add(details.dataset.commentId);else expanded.delete(details.dataset.commentId);}} + function matchSummary(text,q){ + const index=q?text.toLowerCase().indexOf(q):-1,start=index>140?Math.max(0,index-70):0,end=Math.min(text.length,Math.max(start+200,index<0?0:index+q.length+70)); + const summary=node('summary'); + if(start)summary.append(document.createTextNode('โ€ฆ')); + if(index>=start&&indexel.dataset.id===focus.id);next=controls.find(el=>el.dataset.conversation===focus.action&&!el.disabled);if(!next&&focus.action==='save')next=controls.find(el=>el.dataset.conversation==='jump'&&!el.disabled);} + else if(focus.label)next=[...root.querySelectorAll('[aria-label]')].find(el=>el.getAttribute('aria-label')===focus.label); + next?.focus({preventScroll:true});if(next?.type==='search'&&focus.cursor!=null)next.setSelectionRange(focus.cursor,focus.cursorEnd??focus.cursor); + } + function render(){ + const focus=captureFocus(),previousThread=lastThread; + rememberExpanded(); + const thread=(options.getContext()?.url||'').split('#')[0];if(lastThread!==thread){query='';author='';onlySaved=false;lastThread=thread;expanded.clear();} + root.replaceChildren();if(!snapshot())return;root.className='conversation-section tool-section'; + root.append(node('h2','','Conversation navigator'),node('p','muted small',`${comments().length} loaded comments ยท Only loaded content is searched. Load more on GitHub, then refresh page data.`)); + if(snapshot().truncated)root.append(node('p','conversation-limit','Snapshot limit reached. Some loaded text or comments are omitted.')); + const controls=node('div','conversation-controls'),search=node('input');search.type='search';search.placeholder='Find a decision, error or authorโ€ฆ';search.setAttribute('aria-label','Search loaded comments');search.value=query; + search.addEventListener('input',()=>{query=search.value;renderResults();}); + const authors=node('select');authors.setAttribute('aria-label','Filter comment author');const all=node('option','','All authors');all.value='';authors.append(all); + for(const name of [...new Set(comments().map(c=>c.author))].sort()){const option=node('option','',name||'Unknown author');option.value=name;authors.append(option);}if(author&&![...authors.options].some(o=>o.value===author))author='';authors.value=author;authors.addEventListener('change',()=>{author=authors.value;renderResults();}); + const savedLabel=node('label','conversation-saved'),check=node('input');check.type='checkbox';check.checked=onlySaved;check.setAttribute('aria-label','Only saved comments');check.addEventListener('change',()=>{onlySaved=check.checked;renderResults();});savedLabel.append(check,document.createTextNode('Saved only'));controls.append(search,authors,savedLabel);root.append(controls,node('p','muted small','Save important comments to Saved, then add them to a workspace.')); + root.append(node('p','conversation-count'),node('div','conversation-results'));renderResults(); + if(previousThread===lastThread)restoreFocus(focus); + } + function renderResults(){ + const list=root.querySelector('.conversation-results');if(!list)return;const focus=captureFocus();rememberExpanded();list.replaceChildren();const q=query.trim().toLowerCase(),all=comments(),matches=all.filter(c=>(!author||c.author===author)&&(!onlySaved||saved(c.url))&&(!q||`${c.author}\n${c.body}`.toLowerCase().includes(q))); + root.querySelector('.conversation-count').textContent=`${matches.length} of ${all.length} loaded comments`; + if(!matches.length){list.append(node('p','muted',all.length?'No matches in this loaded snapshot. Try another filter or load more on GitHub.':'No readable comments in this snapshot. Load the conversation on GitHub, then refresh page data.'));return;} + for(const comment of matches){const card=node('article','conversation-card');card.append(node('h3','',`${comment.author||'Unknown author'} ยท ${comment.kind}`));const body=node('details','conversation-text');body.dataset.commentId=comment.id;body.open=expanded.has(comment.id);body.append(matchSummary(comment.body,q),node('pre','',comment.body));body.addEventListener('toggle',()=>{if(!root.contains(body))return;if(body.open)expanded.add(comment.id);else expanded.delete(comment.id);});card.append(body);const actions=node('div','tool-actions'),jump=button('Jump to comment','jump',comment.id),save=button(saved(comment.url)?'Saved':'Save important','save',comment.id);jump.disabled=busy;save.disabled=busy||saved(comment.url);const link=node('a','text-button','Source');link.href=comment.url;link.target='_blank';link.rel='noopener noreferrer';actions.append(jump,save,link);card.append(actions);list.append(card);} + restoreFocus(focus); + } + root.addEventListener('click',async event=>{ + const target=event.target.closest('[data-conversation]');if(!target||busy)return;const comment=comments().find(c=>c.id===target.dataset.id);if(!comment)return;const action=target.dataset.conversation,thread=lastThread;busy=true;renderResults(); + try{if(target.dataset.conversation==='jump'){const result=await options.pageAction({type:'conversation-jump',id:comment.id});if(result===false)throw Error('Comment is no longer loaded. Refresh page data.');options.notify('Jumped to comment');} + else if(target.dataset.conversation==='save'){const context=G.parseContext(comment.url,`${comment.author||'Comment'}: ${comment.body.replace(/\s+/g,' ').slice(0,240)}`);if(!context)throw Error('This comment has no supported GitHub source.');options.onState(await options.request({type:'SAVE_ITEM',context}));options.notify('Important comment saved. Add it to a workspace from Workspaces.');}} + catch(error){options.notify(error.message||'Could not complete the action.',true);}finally{busy=false;renderResults();if(action==='save'&&lastThread===thread){const controls=[...root.querySelectorAll('[data-conversation]')].filter(el=>el.dataset.id===comment.id);const next=controls.find(el=>el.dataset.conversation==='save'&&!el.disabled)||controls.find(el=>el.dataset.conversation==='jump'&&!el.disabled);next?.focus({preventScroll:true});}} + }); + return {render,focusSearch(){root.querySelector('[aria-label="Search loaded comments"]')?.focus();}}; + }; +})(); diff --git a/src/shared/model.js b/src/shared/model.js new file mode 100644 index 0000000..da4c4e1 --- /dev/null +++ b/src/shared/model.js @@ -0,0 +1,222 @@ +/* Shared, dependency-free data rules for extension pages and the worker. */ +(() => { + 'use strict'; + const DEFAULT_SETTINGS = Object.freeze({enabled:true, exactDates:true, wide:false, focus:false, theme:'auto', locale:'auto', timeZone:'local', shortcut:true}); + const LIMITS = Object.freeze({items:500, note:10000, title:300, importBytes:32*1024*1024,snippets:100,code:20000,workspaces:40,workspaceTitle:100,reviews:50,reviewFiles:500,path:1000,templates:40,templateTitle:100,templateBody:10000}); + const reserved = new Set(['about','account','apps','blog','business','codespaces','collections','contact','copilot','customer-stories','dashboard','discussions','enterprise','events','explore','features','gist','issues','join','login','logout','marketplace','new','notifications','organizations','orgs','password_reset','pricing','pulls','readme','resources','search','security','sessions','settings','site','sponsors','stars','topics','trending','users']); + const repositorySections = new Set(['issues','pulls','discussions','actions','projects','releases','tags','branches','wiki','security','pulse','network','graphs','settings','commits','compare']); + const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value); + const cleanTitle = value => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g,' ').trim().slice(0,LIMITS.title) : ''; + + function parseContext(value, title = '') { + if (typeof value !== 'string' || value.length > 4096 || /[\u0000-\u0020\u007f\\]/.test(value)) return null; + try { + const url = new URL(value); + if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.port || url.username || url.password) return null; + const parts = url.pathname.replace(/\/+$/, '').split('/').slice(1); + if (parts.length < 2 || parts.some(part => !part)) return null; + const decoded = parts.map(decodeURIComponent); + if (decoded.some(part => /[\\\u0000-\u001f\u007f]/.test(part)) || decoded.slice(0,2).some(part=>part.includes('/'))) return null; + const owner = decoded[0].toLowerCase(); + const name = decoded[1].toLowerCase(); + if (reserved.has(owner) || !/^[a-z0-9][a-z0-9-]{0,38}$/.test(owner) || !/^[a-z0-9._-]{1,100}$/.test(name) || /^\.{1,2}$/.test(name)) return null; + const section = decoded[2]; + let type = 'repository'; + if (section === 'blob' || section === 'tree') { + if (!decoded[3] || (section === 'blob' && !decoded[4])) return null; + type = 'code'; + } else if (section === 'issues' && decoded[3]) { + if (!/^\d+$/.test(decoded[3]) || decoded.length !== 4) return null; + type = 'issue'; + } else if (section === 'pull' && decoded[3]) { + const commitChanges = decoded.length === 6 && decoded[4] === 'changes' && /^[a-f0-9]{40}$/i.test(decoded[5]); + if (!/^\d+$/.test(decoded[3]) || (decoded.length > 5 && !commitChanges) || (decoded[4] && !['files','changes','commits','checks'].includes(decoded[4]))) return null; + type = 'pull'; + } else if (section === 'discussions' && decoded[3]) { + if (!/^\d+$/.test(decoded[3]) || decoded.length !== 4) return null; + type = 'discussion'; + } else if (section === 'commit' && decoded[3]) { + if (!/^[a-f0-9]{6,40}$/i.test(decoded[3]) || decoded.length !== 4) return null; + type = 'commit'; + } else if (section && !repositorySections.has(section)) return null; + url.pathname = '/' + [owner,name,...parts.slice(2)].join('/'); + const ref = type === 'code' ? url.searchParams.get('ref') : null; + url.search = ''; + if (ref) url.searchParams.set('ref',ref); + if (url.hash === '#') url.hash = ''; + return {url:url.href, repo:`${owner}/${name}`, owner, name, type, title:cleanTitle(title) || `${owner}/${name}`}; + } catch { return null; } + } + + function normalizeSettings(input, legacy) { + const result = {...DEFAULT_SETTINGS}; + if (isObject(legacy)) { + if (typeof legacy.enhanceDateTimes === 'boolean') result.exactDates = legacy.enhanceDateTimes; + if (['auto','en-US','tr-TR'].includes(legacy.locale)) result.locale = legacy.locale; + } + if (!isObject(input)) return result; + for (const key of ['enabled','exactDates','wide','focus','shortcut']) if (typeof input[key] === 'boolean') result[key] = input[key]; + for (const [key, values] of Object.entries({theme:['auto','light','dark'],locale:['auto','en-US','tr-TR'],timeZone:['local','UTC']})) { + if (values.includes(input[key])) result[key] = input[key]; + } + return result; + } + + function validateSettingsPatch(input) { + if (!isObject(input)) throw new Error('Settings must be an object.'); + const normalized = normalizeSettings(input); + for (const [key,value] of Object.entries(input)) { + if (!Object.hasOwn(DEFAULT_SETTINGS,key) || normalized[key] !== value) throw new Error(`Invalid setting: ${key}.`); + } + return {...input}; + } + + function validateItem(input) { + if (!isObject(input)) throw new Error('Each saved item must be an object.'); + if (typeof input.title !== 'string' || input.title.length > LIMITS.title) throw new Error(`Titles must be at most ${LIMITS.title} characters.`); + if (typeof input.note !== 'string' || input.note.length > LIMITS.note) throw new Error(`Notes must be at most ${LIMITS.note} characters.`); + const context = parseContext(input.url,input.title); + if (!context) throw new Error('Saved items must use a supported GitHub URL.'); + for (const key of ['createdAt','updatedAt']) { + if (!Number.isSafeInteger(input[key]) || input[key] < 0 || input[key] > Date.now()+86400000) throw new Error('Saved item timestamps are invalid.'); + } + if (input.updatedAt < input.createdAt) throw new Error('A saved item cannot be updated before it was created.'); + return {...context,note:input.note,createdAt:input.createdAt,updatedAt:input.updatedAt}; + } + + function boundedText(value, label, max, allowEmpty = true) { + if (typeof value !== 'string' || value.length > max || (!allowEmpty && !value.trim())) throw new Error(`${label} must be ${allowEmpty?'at most':'between 1 and'} ${max} characters.`); + return value; + } + function validateId(value) { + if (typeof value !== 'string' || !/^[a-zA-Z0-9_-]{1,80}$/.test(value)) throw new Error('Invalid record ID.'); + return value; + } + function validateRevision(value) { + if (value === null) return null; + if (typeof value !== 'string' || !/^[a-f0-9]{40}$/i.test(value)) throw new Error('Revision must be a full commit SHA or explicitly unknown.'); + return value.toLowerCase(); + } + function validatePath(value, allowEmpty = false) { + boundedText(value,'File path',LIMITS.path,allowEmpty); + if (/[\u0000-\u001f\u007f]/.test(value) || value.startsWith('/') || value.split('/').some(part=>part==='..')) throw new Error('Invalid file path.'); + return value; + } + function validateTimestamp(value) { + if (!Number.isSafeInteger(value) || value < 0 || value > Date.now()+86400000) throw new Error('Record timestamps are invalid.'); + return value; + } + function recordTimes(input) { + const createdAt=validateTimestamp(input.createdAt),updatedAt=validateTimestamp(input.updatedAt); + if(updatedAt=1&&Number.isSafeInteger(end)&&end>=start&&end<=10000000)) throw new Error('Invalid snippet line range.'); + return {id:validateId(input.id),url:context.url,repo:context.repo,title:cleanTitle(input.title)||cleanTitle(input.path)||context.title,path:validatePath(input.path,true),language,lineStart:start,lineEnd:end,code:boundedText(input.code,'Code',LIMITS.code,false),note:boundedText(input.note,'Note',LIMITS.note),revision,...recordTimes(input)}; + } + function validateWorkspace(input) { + if(!isObject(input))throw new Error('A workspace must be an object.'); + boundedText(input.title,'Workspace title',LIMITS.workspaceTitle,false); + if(!Array.isArray(input.itemUrls)||input.itemUrls.length>LIMITS.items||!Array.isArray(input.snippetIds)||input.snippetIds.length>LIMITS.snippets)throw new Error('Workspace references exceed the allowed limit.'); + const itemUrls=input.itemUrls.map(url=>{const context=parseContext(url);if(!context)throw new Error('Workspace links must use supported GitHub URLs.');return context.url;}); + return {id:validateId(input.id),title:cleanTitle(input.title),note:boundedText(input.note,'Note',LIMITS.note),itemUrls:[...new Set(itemUrls)],snippetIds:[...new Set(input.snippetIds.map(validateId))],...recordTimes(input)}; + } + function validateTemplate(input) { + if(!isObject(input))throw new Error('A template must be an object.'); + boundedText(input.title,'Template title',LIMITS.templateTitle,false); + const title=cleanTitle(input.title); + if(!title)throw new Error('Template title must not be empty.'); + return {id:validateId(input.id),title,body:boundedText(input.body,'Template body',LIMITS.templateBody,false),...recordTimes(input)}; + } + function canonicalPrUrl(value) { + const context=parseContext(value); + if(context?.type!=='pull')throw new Error('Review sessions require a GitHub pull request URL.'); + const number=new URL(context.url).pathname.split('/')[4]; + return `https://github.com/${context.repo}/pull/${number}`; + } + function validateReviewFile(input) { + if(!isObject(input)||typeof input.reviewed!=='boolean')throw new Error('Invalid review file marker.'); + const updatedAt=validateTimestamp(input.updatedAt),revision=validateRevision(input.reviewedRevision); + const reviewedAt=input.reviewedAt===null?null:validateTimestamp(input.reviewedAt); + if((input.reviewed&&reviewedAt===null)||(!input.reviewed&&(reviewedAt!==null||revision!==null))||(reviewedAt!==null&&reviewedAt>updatedAt))throw new Error('Review marker timestamps are invalid.'); + return {path:validatePath(input.path),note:boundedText(input.note,'File note',LIMITS.note),reviewed:input.reviewed,reviewedRevision:revision,reviewedAt,updatedAt}; + } + function validateReview(input) { + if(!isObject(input)||!Array.isArray(input.files)||input.files.length>LIMITS.reviewFiles)throw new Error(`A review can contain at most ${LIMITS.reviewFiles} file records.`); + const prUrl=canonicalPrUrl(input.prUrl),files=input.files.map(validateReviewFile),times=recordTimes(input); + if(new Set(files.map(file=>file.path)).size!==files.length)throw new Error('A review cannot contain duplicate file paths.'); + if(files.some(file=>file.updatedAt>times.updatedAt))throw new Error('Review file is newer than its session.'); + return {prUrl,repo:parseContext(prUrl).repo,files,lastFile:input.lastFile===null?null:validatePath(input.lastFile),...times}; + } + function reviewStatus(file,revision) { + if(!file?.reviewed)return 'unreviewed'; + if(!/^[a-f0-9]{40}$/i.test(revision||'')||!/^[a-f0-9]{40}$/i.test(file.reviewedRevision||''))return 'unverified'; + return revision.toLowerCase()===file.reviewedRevision.toLowerCase()?'verified':'changed'; + } + + function validateImport(text) { + if (typeof text !== 'string' || new TextEncoder().encode(text).length > LIMITS.importBytes) throw new Error('Choose a JSON backup no larger than 32 MB.'); + let value; + try { value = JSON.parse(text); } catch { throw new Error('This file is not valid JSON.'); } + if (!isObject(value) || (value.version !== undefined && ![1,2].includes(value.version)) || !Array.isArray(value.items)) throw new Error('This is not a supported GitHub Enhancer backup.'); + if (value.items.length > LIMITS.items) throw new Error(`A backup can contain at most ${LIMITS.items} items.`); + const result = {items:value.items.map(validateItem),snippets:[],workspaces:[],reviews:[],templates:[]}; + if(value.version===2){ + for(const [key,validator] of [['snippets',validateSnippet],['workspaces',validateWorkspace],['reviews',validateReview],['templates',validateTemplate]]){ + const records=value[key]??[]; + if(!Array.isArray(records)||records.length>LIMITS[key])throw new Error(`A backup can contain at most ${LIMITS[key]} ${key}.`); + result[key]=records.map(validator); + } + } + if (value.settings !== undefined) result.settings = validateSettingsPatch(value.settings); + return result; + } + + function exportBackup(state) { + const backup={version:2,items:state.items||[],snippets:state.snippets||[],workspaces:state.workspaces||[],reviews:state.reviews||[],templates:state.templates||[],settings:state.settings}; + const validated=validateImport(JSON.stringify(backup)); + const text=JSON.stringify({version:2,...validated},null,2); + if(new TextEncoder().encode(text).length>LIMITS.importBytes)throw new Error('This backup exceeds the 32 MB import limit. Export fewer saved records.'); + return text; + } + + function formatDate(value, input = {}) { + if (value === null || value === undefined || value === '') return ''; + const date = new Date(value); + if (!Number.isFinite(date.getTime())) return ''; + const settings = normalizeSettings(input); + return new Intl.DateTimeFormat(settings.locale === 'auto' ? undefined : settings.locale, { + year:'numeric',month:'short',day:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23', + ...(settings.timeZone === 'UTC' ? {timeZone:'UTC',timeZoneName:'short'} : {}) + }).format(date); + } + + function filterItems(items, query = '') { + const words = String(query).toLocaleLowerCase().trim().split(/\s+/).filter(Boolean); + return items.filter(item => { + const haystack = [item.title,item.repo,item.note,item.type].join(' ').toLocaleLowerCase(); + return words.every(word=>haystack.includes(word)); + }).sort((a,b)=>b.updatedAt-a.updatedAt || a.url?.localeCompare(b.url || '') || 0); + } + + function markdownLink(context) { + const parsed = parseContext(context?.url,context?.title); + if (!parsed) return ''; + const label = parsed.title.replace(/[\\[\]*_`<>]/g, '\\$&'); + const url = parsed.url.replace(/\(/g,'%28').replace(/\)/g,'%29'); + return `[${label}](${url})`; + } + + globalThis.GHE = {...globalThis.GHE,DEFAULT_SETTINGS,LIMITS,parseContext,normalizeSettings,validateSettingsPatch,validateItem,validateSnippet,validateWorkspace,validateReview,validateTemplate,validateReviewFile,validateId,validateRevision,validatePath,canonicalPrUrl,reviewStatus,validateImport,exportBackup,formatDate,filterItems,markdownLink}; +})(); diff --git a/src/shared/review.css b/src/shared/review.css new file mode 100644 index 0000000..1b8be38 --- /dev/null +++ b/src/shared/review.css @@ -0,0 +1,2 @@ +.review-workspace{padding:20px;display:flex;flex-direction:column;gap:12px;min-width:0}.review-workspace h2{font-size:19px;letter-spacing:-.02em}.review-summary{font-size:12px;font-weight:600}.review-revision,.review-privacy,.review-native,.review-mark-status{font-size:11px;color:var(--muted);line-height:1.5}.review-revision{padding:9px 11px;background:var(--surface);border:1px solid var(--border);border-radius:7px}.review-privacy{max-width:48ch}.review-toolbar{display:flex;flex-wrap:wrap;gap:10px}.review-search{width:100%;border:1px solid var(--border);border-radius:7px;background:var(--canvas);color:var(--ink);padding:9px 10px}.review-select{display:flex;align-items:center;gap:7px;color:var(--muted);font-size:11px;flex:1}.review-select select{min-width:0;flex:1;background:var(--canvas);color:var(--ink);border:1px solid var(--border);border-radius:6px;padding:6px}.review-files{max-height:300px;overflow:auto;border:1px solid var(--border);border-radius:8px}.review-file-group h3{position:sticky;top:0;background:var(--surface);padding:7px 10px;font-size:10px;letter-spacing:.03em;color:var(--muted);border-bottom:1px solid var(--border);overflow-wrap:anywhere}.review-file{display:flex;flex-direction:column;gap:4px;width:100%;text-align:left;padding:10px;border:0;border-bottom:1px solid var(--border);background:var(--canvas)}.review-file:hover{background:var(--surface)}.review-file[aria-pressed=true]{background:var(--accent-soft);box-shadow:inset 3px 0 var(--accent)}.review-file-path{font-family:ui-monospace,SFMono-Regular,monospace;font-size:11px;overflow-wrap:anywhere}.review-file small{font-size:10px;color:var(--muted)}.review-file[data-status=verified] small{color:var(--success)}.review-detail{border-top:1px solid var(--border);padding-top:15px;display:flex;flex-direction:column;align-items:flex-start;gap:10px}.review-detail-path{font-family:ui-monospace,SFMono-Regular,monospace;font-size:12px;line-height:1.5;overflow-wrap:anywhere}.review-navigation{display:flex;gap:5px;flex-wrap:wrap}.review-check{display:flex;gap:8px;align-items:center;font-size:12px}.review-check input{accent-color:var(--accent);width:15px;height:15px}.review-note-label{font-size:12px;font-weight:550;display:flex;flex-direction:column;gap:7px;width:100%}.review-note-label textarea{font-weight:400;min-height:90px}.review-empty{font-size:12px;color:var(--muted);padding:12px 0}.review-files>.review-empty{padding:15px} +.review-batch{display:flex;flex-wrap:wrap;gap:7px}.review-batch small{flex-basis:100%;font-size:10px;line-height:1.5;color:var(--muted)} diff --git a/src/shared/review.js b/src/shared/review.js new file mode 100644 index 0000000..f0f5ff8 --- /dev/null +++ b/src/shared/review.js @@ -0,0 +1,216 @@ +/* Extension-origin private review workspace. Never submits a GitHub review. */ +(() => { + 'use strict'; + const G = globalThis.GHE; + G.mountReview = function mountReview(root, options) { + const doc = root.ownerDocument, drafts = new Map(), collapsed = new Map(); + const touchedDrafts = new Set(), draftWrites = new Map(); + let selected = '', query = '', type = 'all', grouping = 'folder', busy = false, currentPR = '', destroyed = false; + function node(tag, cls, text) { const n = doc.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; } + function button(label, action, fn) { const b = node('button', 'button compact', label); b.type = 'button'; b.dataset.reviewAction = action; b.addEventListener('click', fn); return b; } + function data() { + const context = options.getContext(), review = options.getPageData()?.review; + let prUrl = null; + try { const url = new URL(context?.url); const match = url.pathname.match(/^\/[^/]+\/[^/]+\/pull\/\d+(?:\/|$)/); if (context?.type === 'pull' && url.origin === 'https://github.com' && match) prUrl = url.origin + match[0].replace(/\/$/, ''); } catch {} + const record = (options.getState()?.reviews || []).find(r => r.prUrl === prUrl); + const revision = /^[a-f0-9]{40}$/i.test(review?.revision || '') ? review.revision.toLowerCase() : null; + return { prUrl, review, record, revision, files: review?.files || [] }; + } + function status(file, revision) { + if (G.reviewStatus) return G.reviewStatus(file, revision); + if (!file?.reviewed) return 'unreviewed'; + if (!revision || !file.reviewedRevision) return 'unverified'; + return file.reviewedRevision === revision ? 'verified' : 'changed'; + } + const statusText = { unreviewed: 'Not marked', verified: 'Verified at this revision', changed: 'Revision changed', unverified: 'Needs confirmation' }; + function draftKey(prUrl, path) { return prUrl + '\n' + path; } + function persistDraft(key, note) { + if (!options.saveToolDraft) return; + // Keep writes from this surface in input order. Conditional deletion in + // the shared store protects newer snapshots from another surface too. + const pending = (draftWrites.get(key) || Promise.resolve()) + .then(() => options.saveToolDraft('review', key, { note })) + .catch(error => options.notify(`Draft recovery could not be saved: ${error.message}`, true)); + draftWrites.set(key, pending); + } + function hasDrafts() { + const reviews = options.getState()?.reviews || []; + for (const [key, text] of drafts) { + const [prUrl, path] = key.split('\n'); + const saved = reviews.find(review => review.prUrl === prUrl)?.files.find(file => file.path === path)?.note || ''; + if (text !== saved) return true; + } + return false; + } + async function collapseBatch(files, value) { + if (busy) return; + const { prUrl } = data(); + const pageUrl = options.getContext()?.url; + busy = true; render(); + let changed = 0, unavailable = 0; + try { + for (const file of files) { + if (options.getContext()?.url !== pageUrl) break; + try { + const result = await options.pageAction({ type: 'review-collapse', id: file.id, collapsed: value }); + if (result === false || result?.ok === false) { unavailable++; continue; } + collapsed.set(draftKey(prUrl, file.path), value); changed++; + } catch { unavailable++; } + } + options.notify(`${changed} loaded diff bodies ${value ? 'collapsed' : 'expanded'}${unavailable ? `; ${unavailable} unavailable` : ''}.`); + } finally { busy = false; render(); } + } + async function write(message, success) { + if (busy) return false; + busy = true; render(); + try { const next = await options.request(message); options.onState(next); if (success) options.notify(success); return true; } + catch (error) { options.notify(error.message || 'Could not save review.', true); return false; } + finally { busy = false; render(); } + } + async function jump(file) { + const { prUrl } = data(); if (!file || !prUrl) return; + selected = file.path; render(); + try { + const result = await options.pageAction({ type: 'review-jump', id: file.id }); + if (result === false || result?.ok === false) throw new Error('This diff is no longer loaded. Refresh the page data.'); + await write({ type: 'SET_REVIEW_LAST_FILE', prUrl, path: file.path }); + } catch (error) { options.notify(error.message, true); } + } + function render() { + if (destroyed) return; + const active = doc.activeElement; + const focus = root.contains(active) ? active?.dataset.reviewFocus : null; + const cursor = focus === 'note' || focus === 'search' ? [active.selectionStart, active.selectionEnd] : null; + const d = data(); + if (currentPR !== d.prUrl) { currentPR = d.prUrl; selected = ''; query = ''; type = 'all'; collapsed.clear(); } + root.classList.add('review-workspace'); root.setAttribute('aria-busy', String(busy)); + root.replaceChildren(); + const title = node('h2', '', 'Private review'); root.append(title); + if (!d.prUrl || !d.files.length) { + root.append(node('p', 'review-empty', 'Open a pull requestโ€™s Files changed page to work through its loaded diffs.')); + return; + } + const marks = d.record?.files || []; + const locallyMarked = d.files.filter(f => marks.some(m => m.path === f.path && m.reviewed)).length; + root.append(node('p', 'review-summary', `${locallyMarked} locally marked of ${d.files.length} loaded files${d.review.truncated ? ' ยท list capped at 200' : ''}`)); + root.append(node('p', 'review-revision', d.revision ? `Commit ${d.revision.slice(0, 12)} ยท marks apply to this revision` : 'Revision not verified; previous marks need confirmation.')); + root.append(node('p', 'review-privacy', 'Notes and marks stay on this device. GitHub Viewed and submitted reviews are unchanged.')); + const toolbar = node('div', 'review-toolbar'); + const search = node('input', 'review-search'); search.type = 'search'; search.placeholder = 'Filter loaded file pathsโ€ฆ'; search.value = query; search.setAttribute('aria-label', 'Filter loaded file paths'); search.dataset.reviewFocus = 'search'; + search.addEventListener('input', () => { query = search.value; render(); }); toolbar.append(search); + function select(label, key, choices, value, change) { + const field = node('label', 'review-select', label); const select = node('select'); select.setAttribute('aria-label', label); select.dataset.reviewFilter = key; select.dataset.reviewFocus = 'filter:' + key; + for (const [id, text] of choices) { const option = node('option', '', text); option.value = id; select.append(option); } + select.value = value; select.addEventListener('change', () => { change(select.value); render(); }); field.append(select); return field; + } + toolbar.append(select('Type', 'type', [['all', 'All types'], ['source', 'Source'], ['tests', 'Tests'], ['docs', 'Docs'], ['config', 'Config']], type, value => { type = value; })); + toolbar.append(select('Group', 'group', [['folder', 'Folder'], ['type', 'Type']], grouping, value => { grouping = value; })); + root.append(toolbar); + const batch = node('div', 'review-batch'); + const generatedFiles = d.files.filter(file => file.lockfile || file.generated); + const collapseGenerated = button(`Collapse lock / generated (${generatedFiles.length})`, 'collapse-generated', () => collapseBatch(generatedFiles, true)); + collapseGenerated.disabled = busy || !generatedFiles.length; + const expandAll = button('Expand loaded diff bodies', 'expand-all', () => collapseBatch(d.files, false)); + expandAll.disabled = busy; + batch.append(collapseGenerated, expandAll, node('small', '', 'File-name heuristics only; these files still need review.')); + root.append(batch); + const files = d.files.filter(f => (type === 'all' || f.group === type) && f.path.toLowerCase().includes(query.toLowerCase())); + if (!files.some(f => f.path === selected)) selected = files[0]?.path || ''; + const resumeFile = d.files.find(f => f.path === d.record?.lastFile); + if (resumeFile) root.append(button('Resume last file', 'resume', () => { query = ''; type = 'all'; jump(resumeFile); })); + const list = node('div', 'review-files'); list.setAttribute('aria-label', 'Loaded diff files'); + const groups = new Map(); + for (const file of files) { + const label = grouping === 'type' ? file.group : (file.folder || (file.path.includes('/') ? file.path.slice(0, file.path.lastIndexOf('/')) : 'Repository root')); + if (!groups.has(label)) groups.set(label, []); groups.get(label).push(file); + } + const displayedFiles = [...groups.values()].flat(); + root.append(node('p', 'review-keyboard-hint muted small', 'In the file list: โ†‘ / โ†“ or j / k moves between files.')); + for (const [label, members] of groups) { + const section = node('section', 'review-file-group'); section.append(node('h3', '', label)); + for (const file of members) { + const mark = marks.find(m => m.path === file.path), state = status(mark, d.revision); + const b = node('button', 'review-file'); b.type = 'button'; b.dataset.reviewFile = file.path; b.dataset.reviewFocus = 'file:' + file.path; b.dataset.status = state; b.setAttribute('aria-pressed', String(selected === file.path)); + b.append(node('span', 'review-file-path', file.path)); + const badges = [statusText[state]]; if (file.lockfile) badges.push('Lockfile'); if (file.generated) badges.push('Likely generated'); + b.append(node('small', '', badges.join(' ยท '))); + b.addEventListener('click', () => { selected = file.path; render(); }); + b.addEventListener('keydown', event => { + if (!['ArrowDown', 'ArrowUp', 'j', 'k'].includes(event.key) || event.altKey || event.ctrlKey || event.metaKey) return; + event.preventDefault(); const offset = ['ArrowDown', 'j'].includes(event.key) ? 1 : -1; + selected = displayedFiles[Math.max(0, Math.min(displayedFiles.length - 1, displayedFiles.indexOf(file) + offset))].path; + render(); [...root.querySelectorAll('[data-review-file]')].find(el => el.dataset.reviewFile === selected)?.focus(); + }); section.append(b); + } + list.append(section); + } + if (!files.length) list.append(node('p', 'review-empty', 'No loaded files match these filters.')); + root.append(list); + const file = files.find(f => f.path === selected); + if (file) { + const editor = node('section', 'review-detail'), mark = marks.find(m => m.path === file.path), key = draftKey(d.prUrl, file.path); + editor.append(node('h3', 'review-detail-path', file.path)); + const nav = node('div', 'review-navigation'); + const index = displayedFiles.indexOf(file); + const previous = button('โ† Previous', 'previous', () => jump(displayedFiles[index - 1])); previous.disabled = index === 0 || busy; + const next = button('Next โ†’', 'next', () => jump(displayedFiles[index + 1])); next.disabled = index === displayedFiles.length - 1 || busy; + nav.append(previous, button('Jump to diff', 'jump', () => jump(file)), next); editor.append(nav); + const isCollapsed = collapsed.has(key) ? collapsed.get(key) : Boolean(file.collapsed); + editor.append(button(isCollapsed ? 'Expand diff body' : 'Collapse diff body', 'collapse', async () => { + try { + const result = await options.pageAction({ type: 'review-collapse', id: file.id, collapsed: !isCollapsed }); + if (result === false || result?.ok === false) throw new Error('This diff body is not available to collapse.'); + collapsed.set(key, !isCollapsed); render(); + } catch (error) { options.notify(error.message, true); } + })); + if (file.viewedKnown || file.viewed) editor.append(node('p', 'review-native', `Native Viewed: ${file.viewed ? 'yes' : 'no'} ยท read only`)); + const checkLabel = node('label', 'review-check'); const check = node('input'); check.type = 'checkbox'; check.checked = Boolean(mark?.reviewed); check.disabled = busy; + check.addEventListener('change', () => write({ type: 'UPDATE_REVIEW_FILE', prUrl: d.prUrl, path: file.path, revision: d.revision, patch: { reviewed: check.checked } }, d.revision ? 'Local review mark saved.' : 'Local mark saved; revision is unverified.')); + checkLabel.append(check, node('span', '', 'Marked locally')); editor.append(checkLabel); + editor.append(node('p', 'review-mark-status', statusText[status(mark, d.revision)])); + if (mark?.reviewed && d.revision && status(mark, d.revision) !== 'verified') { + const confirm = button('Confirm at this revision', 'confirm-mark', () => write({ + type: 'UPDATE_REVIEW_FILE', prUrl: d.prUrl, path: file.path, revision: d.revision, patch: { reviewed: true } + }, 'Local mark confirmed at this revision.')); + confirm.disabled = busy; editor.append(confirm); + } + const label = node('label', 'review-note-label', 'Private file note'); const note = node('textarea'); note.dataset.reviewFocus = 'note'; note.setAttribute('aria-label', 'Private file note'); note.maxLength = 10000; note.value = drafts.has(key) ? drafts.get(key) : mark?.note || ''; note.placeholder = 'Questions, edge cases, follow-upโ€ฆ'; + const cue = node('p', 'review-mark-status', note.value !== (mark?.note || '') ? 'Unsaved note' : 'Note saved'); + cue.setAttribute('role', 'status'); cue.dataset.reviewDraftStatus = ''; + note.addEventListener('input', () => { + touchedDrafts.add(key); drafts.set(key, note.value); persistDraft(key, note.value); + cue.textContent = note.value !== (mark?.note || '') ? 'Unsaved note' : 'Note saved'; + }); label.append(note); editor.append(label, cue); + const save = button('Save note', 'save-note', async () => { + const text = note.value; + touchedDrafts.add(key); + const pendingDraft = draftWrites.get(key); + const saved = await write({ type: 'UPDATE_REVIEW_FILE', prUrl: d.prUrl, path: file.path, revision: d.revision, patch: { note: text } }, 'Private note saved.'); + if (saved) { + await pendingDraft; + try { await options.deleteToolDraft?.('review', key, { note: text }); } + catch (error) { options.notify(`Note saved, but its recovery copy could not be cleared: ${error.message}`, true); } + if (drafts.get(key) === text) drafts.delete(key); + render(); + } + }); save.disabled = busy; editor.append(save); root.append(editor); + } + if (focus) { + const target = [...root.querySelectorAll('[data-review-focus]')].find(el => el.dataset.reviewFocus === focus); + if (target) { target.focus({ preventScroll: true }); if (cursor && target.setSelectionRange) target.setSelectionRange(...cursor); } + } + } + render(); + const ready = (async () => { + try { + const entries = await options.loadToolDrafts?.('review') || []; + for (const entry of entries) { + if (!Array.isArray(entry) || typeof entry[0] !== 'string' || typeof entry[1]?.note !== 'string' || entry[1].note.length > 10000) continue; + if (!touchedDrafts.has(entry[0])) drafts.set(entry[0], entry[1].note); + } + render(); + } catch (error) { options.notify(`Review drafts could not be recovered: ${error.message}`, true); } + })(); + return { render, hasDrafts, ready, destroy() { destroyed = true; root.replaceChildren(); } }; + }; +})(); diff --git a/src/shared/ui.css b/src/shared/ui.css new file mode 100644 index 0000000..08000af --- /dev/null +++ b/src/shared/ui.css @@ -0,0 +1,17 @@ +:root, .workbench { + color-scheme: light dark; + --canvas:#fff;--surface:#f6f8fa;--surface-hover:#eef2f6;--ink:#1f2328;--muted:#59636e;--border:#d1d9e0;--accent:#0969da;--accent-soft:#ddf4ff;--on-accent:#fff;--success:#1a7f37;--danger:#cf222e; + --sans:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; + font-family:var(--sans);font-size:13px;color:var(--ink);background:var(--canvas); +} +@media(prefers-color-scheme:dark){:root,.workbench{--canvas:#0d1117;--surface:#161b22;--surface-hover:#212830;--ink:#e6edf3;--muted:#919ba6;--border:#30363d;--accent:#4493f8;--accent-soft:#122b49;--on-accent:#fff;--success:#3fb950;--danger:#ff7b72;}} +[data-theme="dark"]{color-scheme:dark;--canvas:#0d1117;--surface:#161b22;--surface-hover:#212830;--ink:#e6edf3;--muted:#919ba6;--border:#30363d;--accent:#4493f8;--accent-soft:#122b49;--on-accent:#fff;--success:#3fb950;--danger:#ff7b72;} +[data-theme="light"]{color-scheme:light;--canvas:#fff;--surface:#f6f8fa;--surface-hover:#eef2f6;--ink:#1f2328;--muted:#59636e;--border:#d1d9e0;--accent:#0969da;--accent-soft:#ddf4ff;--on-accent:#fff;--success:#1a7f37;--danger:#cf222e;} +*{box-sizing:border-box}body{margin:0;background:var(--canvas);color:var(--ink)}button,input,textarea,select{font:inherit}button,a,input,select,summary,textarea{-webkit-tap-highlight-color:transparent}button,a,summary{touch-action:manipulation}button{cursor:pointer}button:disabled{cursor:default;opacity:.75}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}button:focus-visible,a:focus-visible,summary:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:2px solid var(--accent);outline-offset:3px}svg{width:18px;height:18px;flex-shrink:0}h1,h2,h3,p{margin:0}h1,h2,h3{text-wrap:balance}p{line-height:1.55;text-wrap:pretty}button{color:var(--ink)} +.workbench{display:flex;flex-direction:column;position:relative;min-height:540px;height:100%;isolation:isolate}.app-header{display:flex;align-items:center;justify-content:space-between;padding:18px 20px;border-bottom:1px solid var(--border);gap:8px;flex-shrink:0}.brand{display:flex;align-items:center;gap:10px}.brand-symbol{display:inline-flex;align-items:center;justify-content:center;background:var(--accent);color:#fff;width:29px;height:29px;border-radius:7px;font-size:19px;letter-spacing:-1px;font-weight:700}.brand-name{font-weight:650;font-size:14px;letter-spacing:-.2px}.header-tools{display:flex;gap:2px}.icon-button{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;border:0;border-radius:6px;background:transparent;color:var(--muted);padding:5px}.icon-button:hover{color:var(--ink);background:var(--surface-hover)}.workbench-body{overflow:auto;flex:1;min-height:0}.current-section{padding:22px 22px 18px;border-bottom:1px solid var(--border);background:var(--surface)}.context-kicker{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:12px}.context-label{font-size:12px;color:var(--muted)}.type-badge{font-size:11px;padding:2px 7px;border-radius:5px;border:1px solid var(--border);line-height:1.5}.type-issue{color:var(--success)}.type-pull{color:var(--accent)}.context-title{font-size:21px;font-weight:650;letter-spacing:-.025em;line-height:1.3;overflow-wrap:anywhere;max-height:84px;overflow:auto}.repo-name{font-size:12px;color:var(--muted);margin-top:7px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.current-actions{display:flex;gap:7px;margin-top:18px;flex-wrap:wrap}.button{display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:34px;padding:6px 11px;border:1px solid var(--border);border-radius:7px;background:var(--canvas);color:var(--ink);font-weight:550;font-size:12px;line-height:1.5;white-space:nowrap;text-decoration:none}.button:hover{text-decoration:none;background:var(--surface-hover)}.button svg{width:15px;height:15px}.primary{background:#0969da;border-color:#0969da;color:white}.primary:hover{background:#0757b8;border-color:#0757b8}.saved-button{color:var(--success);background:var(--canvas)}.compact{min-height:29px;padding:4px 10px;font-size:12px}.text-button{background:none;border:0;color:var(--accent);font-size:12px;padding:3px 0;text-align:left}.text-button:hover{text-decoration:underline}.copy-menu{position:relative}.copy-menu summary{list-style:none;cursor:pointer}.copy-menu summary::-webkit-details-marker{display:none}.menu-items{position:absolute;right:0;top:39px;background:var(--canvas);border:1px solid var(--border);border-radius:8px;padding:5px;min-width:165px;z-index:2}.menu-item{display:block;width:100%;border:0;background:none;padding:8px 10px;border-radius:4px;text-align:left;font-size:12px}.menu-item:hover{background:var(--surface-hover)}.repo-links{display:flex;gap:15px;flex-wrap:wrap;margin-top:16px;font-size:11px}.repo-links a{color:var(--muted)}.repo-links a:hover{color:var(--accent)}.note-editor{margin-top:16px}.note-label{font-size:12px;font-weight:550;display:block;margin-bottom:7px}textarea{display:block;width:100%;resize:vertical;min-height:82px;max-height:210px;background:var(--canvas);border:1px solid var(--border);border-radius:7px;padding:10px;color:var(--ink);line-height:1.5;font-size:13px}textarea::placeholder,input::placeholder{color:var(--muted);opacity:1}.note-actions{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:8px}.muted{color:var(--muted)}.small{font-size:11px}.saved-section{padding:22px 22px 10px}.section-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}.section-heading h2{font-size:14px;font-weight:650;display:flex;align-items:center;gap:8px}.count{font-size:11px;background:var(--surface-hover);padding:1px 6px;border-radius:5px;color:var(--muted)}.search-field{display:flex;gap:8px;align-items:center;background:var(--canvas);border:1px solid var(--border);border-radius:7px;padding:8px 10px;color:var(--muted)}.search-field:focus-within{outline:2px solid var(--accent);outline-offset:1px}.search-field svg{width:15px;height:15px}.search-field input{min-width:0;width:100%;border:0;outline:none;background:transparent;color:var(--ink);font-size:12px}.search-field input:focus-visible{outline:none}.filters{display:flex;gap:3px;margin:12px 0 3px}.filter{background:none;border:0;border-radius:5px;color:var(--muted);padding:5px 9px;font-size:11px}.filter:hover{background:var(--surface)}.filter[aria-pressed="true"]{background:var(--accent-soft);color:var(--accent);font-weight:650}.saved-row{display:flex;align-items:flex-start;gap:10px;padding:15px 0;border-bottom:1px solid var(--border)}.saved-row:last-child{border:0}.item-icon{padding-top:2px;color:var(--muted)}.saved-info{min-width:0;flex:1}.saved-title{color:var(--ink);font-size:12px;line-height:1.5;font-weight:600;display:block;overflow-wrap:anywhere}.saved-title:hover{color:var(--accent)}.saved-meta{font-size:10px;color:var(--muted);margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.note-preview{font-size:11px;color:var(--muted);margin-top:7px;white-space:pre-wrap;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;overflow-wrap:anywhere}.row-tools{display:flex;gap:0}.row-tools .icon-button{width:25px;height:27px}.row-tools svg{width:14px;height:14px}.row-tools [data-action="remove-item"]:hover{color:var(--danger)}.empty-state{text-align:center;padding:26px 14px 28px;color:var(--muted)}.empty-state>svg{width:26px;height:26px;margin-bottom:13px;color:var(--accent)}.empty-state h3{font-size:13px;font-weight:600;color:var(--ink);margin-bottom:7px}.empty-state p{font-size:12px;max-width:29ch;margin:0 auto}.empty-state button{margin-top:8px}.status{font-size:12px;line-height:1.5;padding:0 22px;color:var(--success);display:flex;align-items:center;justify-content:space-between;gap:12px}.status:not(:empty){padding-top:10px;padding-bottom:10px;border-top:1px solid var(--border)}.status.error{color:var(--danger)}.app-footer{display:flex;justify-content:space-between;align-items:center;padding:13px 22px;border-top:1px solid var(--border);color:var(--muted);flex-shrink:0;background:var(--canvas)}.privacy{display:flex;align-items:center;gap:6px;font-size:10px}.privacy svg{width:12px;height:12px}.app-footer .text-button{font-size:10px;color:var(--muted)}.welcome h1{font-size:24px;letter-spacing:-.03em;margin-bottom:10px}.welcome p{font-size:13px;max-width:34ch}.welcome .button{margin-top:18px}.loading{padding:24px;color:var(--muted)} +.command-overlay{position:absolute;inset:0;z-index:3;background:var(--canvas);display:flex;flex-direction:column;padding:20px;min-height:0}.command-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px}.command-heading h2{font-size:21px;letter-spacing:-.025em}.command-input{color:var(--ink);background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:12px;width:100%;font-size:13px;flex-shrink:0}.command-results{overflow:auto;margin-top:14px;flex:1}.command-option{width:100%;border:0;background:none;display:flex;flex-direction:column;gap:4px;text-align:left;padding:12px;border-radius:7px;font-size:13px;color:var(--ink);text-decoration:none}.command-option small{font-size:11px}.command-option[aria-selected="true"],.command-option:hover{background:var(--accent-soft);text-decoration:none}.command-hint{font-size:10px;color:var(--muted);border-top:1px solid var(--border);padding-top:12px;margin-top:12px} +@media(max-width:350px){.app-header{padding:14px}.brand-name{font-size:12px}.current-section,.saved-section{padding:17px 14px}.current-actions{gap:5px}.button{padding:6px 9px}.row-tools{flex-direction:column}.context-title{font-size:19px}} +@media(prefers-reduced-motion:no-preference){.button,.icon-button,.filter{transition:background-color 150ms ease-out,color 150ms ease-out}.command-overlay{animation:appear 130ms ease-out}@keyframes appear{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}} +[hidden]{display:none!important}.workspace-tabs{display:flex;gap:2px;padding:0 16px;border-bottom:1px solid var(--border);flex-shrink:0;background:var(--canvas)}.workspace-tab{flex:1;border:0;border-bottom:2px solid transparent;background:none;padding:13px 2px;color:var(--muted);font-size:11px;white-space:nowrap}.workspace-tab[aria-current="page"]{border-bottom-color:var(--accent);color:var(--ink);font-weight:650}.workspace-tab:hover{background:var(--surface)}.tool-section{padding:20px 22px;border-bottom:1px solid var(--border)}.tool-heading{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:12px}.tool-heading h2,.tool-section>h2{font-size:15px;font-weight:650;letter-spacing:-.2px}.tool-heading h3{font-size:13px}.tool-intro{font-size:12px;line-height:1.6;margin:12px 0 16px}.tool-filepath{font:12px/1.5 ui-monospace,SFMono-Regular,Consolas,monospace;overflow-wrap:anywhere;margin-bottom:5px}.tool-actions,.tool-choices{display:flex;flex-wrap:wrap;gap:8px;margin:14px 0}.tool-links{display:grid;grid-template-columns:1fr 1fr;gap:12px;font-size:12px;margin-top:20px}.tool-links a{line-height:1.4}.tool-pane .tool-section:last-child{border:0}.tool-pane .current-section{padding-top:18px}.tool-input{width:100%;background:var(--canvas);border:1px solid var(--border);border-radius:6px;padding:9px;color:var(--ink)} + +.workbench[data-view="tools"] .current-section{padding:14px 22px}.workbench[data-view="tools"] .context-title{font-size:16px;max-height:42px}.workbench[data-view="tools"] .context-kicker{margin-bottom:6px}.workbench[data-view="tools"] .current-actions{margin-top:10px}.workbench[data-view="tools"] .repo-links{display:none}.workbench[data-view="tools"] .repo-name{margin-top:4px} diff --git a/src/shared/ui.js b/src/shared/ui.js new file mode 100644 index 0000000..9fbc96b --- /dev/null +++ b/src/shared/ui.js @@ -0,0 +1,180 @@ +/* Shared extension-origin workbench. Page-derived content is always text. */ +(() => { + const G = globalThis.GHE; + const icons = { + mark: '', search: '', + close: '', settings: '', + note: '', copy: '', + arrow: '', repo:'', + issue:'', pull:'', + code:'', check:'', trash:'', + bolt:'', chevron:'', back:'', lock:'' + }; + function icon(name) { + const el = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + el.setAttribute('viewBox', '0 0 20 20'); el.setAttribute('aria-hidden', 'true'); + el.setAttribute('fill','none');el.setAttribute('stroke','currentColor');el.setAttribute('stroke-width','1.5');el.setAttribute('stroke-linecap','round');el.setAttribute('stroke-linejoin','round'); + el.innerHTML = icons[name] || icons.repo; // Only static, bundled SVG paths. + return el; + } + function node(tag, cls, text) { const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n; } + function button(label, action, glyph, cls='button') { + const b=node('button',cls);b.type='button';b.dataset.action=action; + if(glyph)b.append(icon(glyph));if(label)b.append(node('span','',label));return b; + } + function iconButton(label,action,glyph) {const b=button('',action,glyph,'icon-button');b.setAttribute('aria-label',label);b.title=label;return b;} + function kind(type) {return {repository:'Repository',issue:'Issue',pull:'Pull request',code:'Code',commit:'Commit',discussion:'Discussion'}[type]||'Page';} + function typeIcon(type) {return {repository:'repo',issue:'issue',pull:'pull',code:'code',commit:'code',discussion:'note'}[type]||'repo';} + function displayTitle(context) { + const title=context.title||context.repo||''; + const colon=title.indexOf(':'); + if(context.type==='repository'&&colon>0&&title.slice(0,colon).toLowerCase()===context.repo?.toLowerCase())return title.slice(0,colon); + return title; + } + function mountWorkbench(root, options) { + let context=options.context||null, state={settings:G.DEFAULT_SETTINGS,items:[],snippets:[],workspaces:[],reviews:[],templates:[]}, query='', filter='all', busy=false, editing=null; + const drafts=new Map();let noteOpen=false, undoItem=null, palette=null; + let pageData=options.pageData||{}, activeView=G.mountWorkspaces?'tools':'saved';const modules=[]; + const request=options.request; + root.classList.add('workbench'); + const header=node('header','app-header'); + const brand=node('div','brand');brand.append(node('span','brand-symbol','g+'),node('div','brand-name','GitHub Enhancer')); + const tools=node('div','header-tools');tools.append(iconButton('Search commands','commands','search'),iconButton('Settings','settings','settings')); + if(options.close)tools.append(iconButton('Close workbench','close','close')); + header.append(brand,tools); + const body=node('div','workbench-body'), current=node('section','current-section'); + const saved=node('section','saved-section');const savedHeading=node('div','section-heading'); + const title=node('h2','','Saved pages');const count=node('span','count','0');title.append(count);savedHeading.append(title); + const searchWrap=node('div','search-field');searchWrap.append(icon('search'));const search=node('input');search.type='search';search.placeholder='Find a page or a noteโ€ฆ';search.setAttribute('aria-label','Search saved pages');searchWrap.append(search); + const filters=node('div','filters');filters.setAttribute('aria-label','Filter saved pages'); + for(const [value,label] of [['all','All'],['repository','Repos'],['issue','Issues'],['pull','PRs'],['code','Code']]) {const b=button(label,`filter:${value}`,null,'filter');b.setAttribute('aria-pressed',String(value==='all'));filters.append(b);} + const list=node('div','saved-list');saved.append(savedHeading,searchWrap,filters,list); + const nav=node('nav','workspace-tabs');nav.setAttribute('aria-label','Workbench sections'); + const toolPane=node('section','tool-pane'),basketPane=node('section','basket-pane'),workspacePane=node('section','workspace-pane'),composerPane=node('section','composer-pane'); + if(G.mountWorkspaces){for(const [id,label] of [['tools','Tools'],['basket','Code basket'],['workspaces','Workspaces'],['write','Write'],['saved','Saved']]){const b=button(label,`view:${id}`,null,'workspace-tab');nav.append(b);}} + body.append(current,toolPane,basketPane,workspacePane,composerPane,saved); + const status=node('div','status');status.setAttribute('role','status');status.setAttribute('aria-live','polite'); + const footer=node('footer','app-footer');const privacy=node('span','privacy');privacy.append(icon('lock'),document.createTextNode('Only on this device'));footer.append(privacy,button('Commands','commands',null,'text-button')); + root.replaceChildren(header,nav,body,status,footer); + const moduleOptions={...options,getState:()=>state,getContext:()=>context,getPageData:()=>pageData,request,onState:setState,notify,pageAction:async action=>{if(!options.pageAction)throw new Error('Open this tool on a GitHub page.');return options.pageAction(action);}}; + const basketUI=G.mountBasket?.(basketPane,moduleOptions);const workspacesUI=G.mountWorkspaces?.(workspacePane,moduleOptions);const reviewRoot=node('div'); + const reviewUI=G.mountReview?.(reviewRoot,moduleOptions),conversationRoot=node('div'),conversationUI=G.mountConversation?.(conversationRoot,moduleOptions),composerUI=G.mountComposer?.(composerPane,moduleOptions);modules.push(...[basketUI,workspacesUI,reviewUI,conversationUI,composerUI].filter(Boolean)); + function switchView(view){activeView=view;root.dataset.view=view;current.hidden=!['tools','saved'].includes(view);toolPane.hidden=view!=='tools';basketPane.hidden=view!=='basket';workspacePane.hidden=view!=='workspaces';composerPane.hidden=view!=='write';saved.hidden=view!=='saved';for(const b of nav.children)b.setAttribute('aria-current',b.dataset.action===`view:${view}`?'page':'false');renderTools();for(const module of modules)module.render();} + function renderTools(){ + if(!G.mountWorkspaces){toolPane.replaceChildren();return;} + for(const child of [...toolPane.children])if(child!==reviewRoot&&child!==conversationRoot)child.remove(); + if(!pageData.review)reviewRoot.remove();if(!pageData.conversation)conversationRoot.remove(); + const section=node('div','tool-section');const heading=node('div','tool-heading');heading.append(node('h2','','Your page tools'));const refresh=button('Refresh page data','refresh-page',null,'text-button');heading.append(refresh);section.append(heading); + toolPane.prepend(section); + if(pageData.review){if(reviewRoot.parentElement!==toolPane)toolPane.append(reviewRoot);reviewUI?.render();} + if(pageData.code){const c=pageData.code;section.append(node('p','tool-filepath',c.path),node('p','muted small',`${c.lineCount} ${c.truncated?'loaded ':''}lines ยท ${(c.bytes/1024).toFixed(1)} KB`),node('p','tool-intro','Collect a line range with its source, then combine excerpts from other files.'),button('Collect a code excerpt','view:basket','code','button primary'));} + else if(!pageData.review&&!pageData.conversation){section.append(node('p','muted tool-intro','A workspace for the investigation, a basket for the evidence. Open a code file or PR changes to unlock its page tools.'));const choices=node('div','tool-choices');choices.append(button('Build a code basket','view:basket','code'),button('Resume a workspace','view:workspaces','repo'));section.append(choices);} + if(pageData.conversation){if(conversationRoot.parentElement!==toolPane)toolPane.append(conversationRoot);conversationUI?.render();} + if(context){const box=node('section','tool-section repo-toolbox');box.append(node('h2','','Repository toolbox'));const clone=node('div','tool-actions');clone.append(button('HTTPS clone','tool-clone-https',null),button('SSH clone','tool-clone-ssh',null),button('GitHub CLI','tool-clone-cli',null));box.append(clone);const links=node('div','tool-links');for(const [label,path] of [['Recent commits','/commits'],['Compare changes','/compare'],['Your pull requests','/pulls?q=is%3Apr+author%3A%40me'],['Issues assigned to you','/issues?q=is%3Aissue+assignee%3A%40me'],['Actions','/actions'],['Releases','/releases']]){const a=node('a','',label);a.href=`https://github.com/${context.repo}${path}`;a.target='_blank';a.rel='noopener noreferrer';links.append(a);}const editor=node('a','','Open browser editor');editor.href=`https://github.dev/${context.repo}`;editor.target='_blank';editor.rel='noopener noreferrer';links.append(editor);box.append(links);toolPane.append(box);} + } + function notify(text,error=false) { status.replaceChildren(node('span','',text));status.classList.toggle('error',error); } + function savedItem(url) {return state.items.find(i=>i.url===url);} + function target() {return editing||context;} + function setState(next) {state=next;root.dataset.theme=state.settings.theme||'auto';renderCurrent();renderList();renderTools();for(const module of modules)module.render();} + async function run(message,success) { + if(busy)return false;busy=true;root.setAttribute('aria-busy','true'); + try{const next=await request(message);setState(next);if(success)notify(success);return true;} + catch(error){notify(error.message||'Could not save. Please try again.',true);return false;} + finally{busy=false;root.removeAttribute('aria-busy');} + } + function renderCurrent() { + const previous=current.querySelector('textarea');const focused=previous===document.activeElement;const cursor=previous?.selectionStart; + current.replaceChildren();const c=target(); + if(!c){const welcome=node('div','welcome');welcome.append(node('h1','','Keep your place.'),node('p','muted','Open a repository, issue, or pull request to save it here with a private note.'));const a=node('a','button primary','Explore GitHub');a.href='https://github.com';a.target='_blank';a.rel='noopener noreferrer';welcome.append(a);current.append(welcome);return;} + const item=savedItem(c.url), top=node('div','context-kicker'); + top.append(node('span','context-label',editing?'Editing saved page':'On this page'),node('span',`type-badge type-${c.type}`,kind(c.type))); + if(editing)top.prepend(iconButton('Back to current page','back','back')); + const name=node('h1','context-title',displayTitle(c));name.dataset.contextTitle='';name.title=c.title||c.repo; + const repo=node('div','repo-name',c.repo);repo.title=c.url; + const actions=node('div','current-actions');const save=button(item?'Saved':'Save page','save',item?'check':'mark',`button ${item?'saved-button':'primary'}`);save.disabled=Boolean(item);actions.append(save,button(item?.note?'Edit note':'Add note','note','note')); + const menu=node('details','copy-menu');const summary=node('summary','button');summary.append(icon('copy'),document.createTextNode('Copy'));const menuItems=node('div','menu-items');menuItems.append(button('Page URL','copy-url',null,'menu-item'),button('Markdown link','copy-markdown',null,'menu-item'),button('Clone command','copy-clone',null,'menu-item'));menu.append(summary,menuItems);actions.append(menu); + current.append(top,name,repo,actions); + if(noteOpen||drafts.has(c.url)){ + const wrap=node('div','note-editor');const label=node('label','note-label','Private note');label.htmlFor='private-note'; + const note=node('textarea');note.id='private-note';note.rows=3;note.maxLength=10000;note.placeholder='What do you want to remember?';note.setAttribute('aria-label','Private note');note.value=drafts.has(c.url)?drafts.get(c.url):item?.note||''; + note.addEventListener('input',()=>{drafts.set(c.url,note.value);noteState.textContent='Unsaved changes';options.saveDraft?.(c.url,note.value).catch(()=>notify('Draft recovery unavailable. Save your note before closing.',true));}); + const bottom=node('div','note-actions');const noteState=node('span','muted small',drafts.has(c.url)?'Unsaved changes':'Stored only in this browser');bottom.append(noteState,button('Discard','discard-draft',null,'text-button'),button('Save note','save-note',null,'button compact primary'));wrap.append(label,note,bottom);current.append(wrap); + if(focused){note.focus();note.setSelectionRange(cursor,cursor);} + } + const links=node('nav','repo-links');links.setAttribute('aria-label','Repository shortcuts'); + for(const [label,path] of [['Code',''],['Issues','/issues'],['Pull requests','/pulls'],['Releases','/releases']]){const a=node('a','',label);a.href=`https://github.com/${c.repo}${path}`;a.target='_blank';a.rel='noopener noreferrer';links.append(a);} + current.append(links); + } + function renderList() { + count.textContent=state.items.length;list.replaceChildren(); + const items=G.filterItems(state.items,query).filter(i=>filter==='all'||i.type===filter||(filter==='code'&&i.type==='commit')); + if(!items.length){const empty=node('div','empty-state');empty.append(icon(query?'search':'mark'),node('h3','',state.items.length?'No matching pages':'A little context goes a long way.'),node('p','muted',state.items.length?'Try a different search or filter.':'Save a page you want to return to. Add a note so you remember why.'));if(state.items.length)empty.append(button('Clear filters','clear-filters',null,'text-button'));list.append(empty);return;} + for(const item of items){const row=node('article','saved-row');row.dataset.savedItem=item.url;const glyph=node('span',`item-icon type-${item.type}`);glyph.append(icon(typeIcon(item.type)));const info=node('div','saved-info'); + const a=node('a','saved-title',displayTitle(item));a.href=item.url;a.target='_blank';a.rel='noopener noreferrer';a.title=item.title||item.url; + const meta=node('div','saved-meta',item.repo);info.append(a,meta);if(item.note)info.append(node('p','note-preview',item.note)); + const edit=iconButton(`Edit note for ${item.title}`,'edit-item','note');edit.dataset.url=item.url;const remove=iconButton(`Remove ${item.title}`,'remove-item','trash');remove.dataset.url=item.url; + const rowTools=node('div','row-tools');rowTools.append(edit,remove);row.append(glyph,info,rowTools);list.append(row); + } + } + async function copy(text,label){try{await options.copy(text);notify(`${label} copied`);}catch{notify('Clipboard unavailable. Try opening the extension from the toolbar.',true);}current.querySelector('details')?.removeAttribute('open');} + function closePalette(){if(!palette)return;const focus=palette.focus;palette.el.remove();palette=null;focus?.focus();} + function openPalette() { + if(palette)return;const focus=document.activeElement;const overlay=node('section','command-overlay');overlay.setAttribute('role','dialog');overlay.setAttribute('aria-modal','true');overlay.setAttribute('aria-label','Enhancer commands'); + const heading=node('div','command-heading');heading.append(node('h2','','Jump back in'),iconButton('Close commands','close-commands','close')); + const input=node('input','command-input');input.placeholder='Search commands, notes and collected workโ€ฆ';input.setAttribute('aria-label','Search commands and saved pages');input.setAttribute('role','combobox');input.setAttribute('aria-controls','command-results');input.setAttribute('aria-expanded','true');input.setAttribute('aria-autocomplete','list'); + const results=node('div','command-results');results.id='command-results';results.setAttribute('role','listbox'); + const hint=node('div','command-hint','โ†‘ โ†“ to move ยท Enter to run ยท Esc to close');overlay.append(heading,input,results,hint);root.append(overlay);palette={el:overlay,focus,index:0,actions:[]}; + function render(){if(!palette)return;const q=input.value.trim().toLowerCase(), c=target();let actions=[]; + if(c)actions.push({label:savedItem(c.url)?'Edit private note':'Save this page',detail:c.repo,run:()=>{closePalette();root.querySelector(`[data-action="${savedItem(c.url)?'note':'save'}"]`)?.click();}}, {label:'Copy Markdown link',detail:c.repo,run:()=>{closePalette();copy(G.markdownLink(c),'Markdown link');}},{label:'Copy clone command',detail:c.repo,run:()=>{closePalette();copy(`git clone https://github.com/${c.repo}.git`,'Clone command');}}); + if(G.mountWorkspaces)for(const [view,label] of [['tools','Open page tools'],['basket','Open code basket'],['workspaces','Open workspaces'],['write','Write a reply draft'],['saved','Search saved pages']])actions.push({label,detail:context?.repo||'Local workbench',run:()=>{closePalette();switchView(view);if(view==='saved')search.focus();}}); + if(pageData.conversation)actions.push({label:'Search loaded comments',detail:context?.repo||'Conversation',run:()=>{closePalette();switchView('tools');conversationUI?.focusSearch();}}); + for(const [key,label] of [['exactDates','Exact dates'],['wide','Wide layout'],['focus','Focus mode']])actions.push({label:`${state.settings[key]?'Turn off':'Turn on'} ${label.toLowerCase()}`,detail:'Reading preference',run:()=>{closePalette();run({type:'SET_SETTINGS',patch:{[key]:!state.settings[key]}},`${label} updated`);}}); + actions=actions.filter(a=>`${a.label} ${a.detail}`.toLowerCase().includes(q)); + const matches=text=>text.toLowerCase().includes(q); + for(const workspace of (state.workspaces||[]).filter(w=>matches(`${w.title} ${w.note}`)).slice(0,8))actions.push({label:workspace.title,detail:'Workspace ยท '+(workspace.note||'Resume this investigation').slice(0,100),run:()=>{closePalette();switchView('workspaces');workspacesUI?.select?.(workspace.id);}}); + for(const snippet of (state.snippets||[]).filter(s=>matches(`${s.title} ${s.path} ${s.note} ${s.code}`)).slice(0,8))actions.push({label:snippet.title||snippet.path,detail:'Code excerpt ยท '+snippet.path,run:()=>{closePalette();switchView('basket');basketUI?.reveal?.(snippet.id);}}); + if(q)for(const review of state.reviews||[])for(const file of review.files||[]){if(file.note&&matches(`${review.prUrl} ${file.path} ${file.note}`))actions.push({label:file.path,detail:'Private PR note ยท '+file.note.slice(0,120),href:review.prUrl+'/files'});} + actions.push(...G.filterItems(state.items,q).map(item=>({label:item.title,detail:item.repo,href:item.url}))); + palette.actions=actions.slice(0,30);palette.index=0;results.replaceChildren(); + palette.actions.forEach((action,i)=>{const b=node(action.href?'a':'button','command-option');if(action.href){b.href=action.href;b.target='_blank';b.rel='noopener noreferrer';}else b.type='button';b.id=`command-${i}`;b.setAttribute('role','option');b.tabIndex=-1;b.append(node('span','',action.label),node('small','muted',action.detail));b.addEventListener('click',()=>{if(action.run)action.run();else closePalette();});results.append(b);}); + if(!actions.length)results.append(node('p','empty-state','No matching commands or pages.'));select(); + } + function select(){if(!palette)return;[...results.querySelectorAll('[role="option"]')].forEach((b,i)=>b.setAttribute('aria-selected',String(i===palette.index)));if(palette.actions.length)input.setAttribute('aria-activedescendant',`command-${palette.index}`);else input.removeAttribute('aria-activedescendant');} + input.addEventListener('input',render);overlay.addEventListener('keydown',event=>{if(event.key==='Escape'){event.preventDefault();closePalette();}else if(event.key==='ArrowDown'||event.key==='ArrowUp'){event.preventDefault();const n=palette.actions.length;palette.index=n?(palette.index+(event.key==='ArrowDown'?1:n-1))%n:0;select();results.children[palette.index]?.scrollIntoView?.({block:'nearest'});}else if(event.key==='Enter'&&document.activeElement===input){event.preventDefault();results.querySelectorAll('[role="option"]')[palette.index]?.click();}else if(event.key==='Tab'){event.preventDefault();if(document.activeElement===input)overlay.querySelector('button').focus();else input.focus();}}); + render();input.focus(); + } + root.addEventListener('keydown',event=>{ + if(!event.defaultPrevented&&state.settings.enabled&&state.settings.shortcut&&event.altKey&&event.shiftKey&&!event.ctrlKey&&!event.metaKey&&event.code==='KeyK'){ + event.preventDefault();event.stopPropagation();openPalette(); + } + }); + root.addEventListener('click',async event=>{ + const b=event.target.closest('[data-action]');if(!b)return;const action=b.dataset.action,c=target(); + if(action.startsWith('view:')){switchView(action.slice(5));return;} + if(action==='refresh-page'){try{const data=await options.refreshPage?.();if(data){pageData=data.pageData||{};if(context?.url!==data.context?.url){editing=null;noteOpen=false;}context=data.context||null;renderCurrent();renderTools();for(const module of modules)module.render();notify('Loaded page data refreshed');}else if(options.refreshPage)notify('Refreshing loaded page dataโ€ฆ');else notify('Reload the GitHub page to enable page tools.',true);}catch(e){notify(e.message||'Page tools unavailable. Reload GitHub.',true);}return;} + if(action.startsWith('tool-clone-')&&context){const command=action==='tool-clone-ssh'?`git clone git@github.com:${context.repo}.git`:action==='tool-clone-cli'?`gh repo clone ${context.repo}`:`git clone https://github.com/${context.repo}.git`;copy(command,'Clone command');return;} + if(action.startsWith('filter:')){filter=action.slice(7);for(const f of filters.children)f.setAttribute('aria-pressed',String(f===b));renderList();return;} + if(action==='settings')options.openOptions(); + else if(action==='close')options.close?.(); + else if(action==='commands')openPalette(); + else if(action==='close-commands')closePalette(); + else if(action==='clear-filters'){query='';filter='all';search.value='';for(const f of filters.children)f.setAttribute('aria-pressed',String(f.dataset.action==='filter:all'));renderList();} + else if(action==='back'){editing=null;noteOpen=false;renderCurrent();} + else if(action==='note'){if(current.hidden)switchView('saved');noteOpen=!noteOpen;renderCurrent();current.querySelector('textarea')?.focus();} + else if(action==='save'&&c){await run({type:'SAVE_ITEM',context:c},'Page saved to Saved pages');} + else if(action==='save-note'&&c){const value=current.querySelector('textarea').value;const ok=await run(savedItem(c.url)?{type:'UPDATE_ITEM',url:c.url,note:value}:{type:'SAVE_ITEM',context:c,note:value},'Private note saved');if(ok){if(drafts.get(c.url)===value){drafts.delete(c.url);try{await options.deleteDraft?.(c.url,value);}catch{notify('Note saved, but the temporary draft could not be cleared.',true);}}renderCurrent();}} + else if(action==='discard-draft'&&c){const expected=drafts.get(c.url);drafts.delete(c.url);try{await options.deleteDraft?.(c.url,expected);notify('Draft discarded');}catch{notify('Draft could not be cleared. Please try again.',true);}renderCurrent();} + else if(action==='copy-url'&&c)copy(c.url,'Page URL'); + else if(action==='copy-markdown'&&c)copy(G.markdownLink(c),'Markdown link'); + else if(action==='copy-clone'&&c)copy(`git clone https://github.com/${c.repo}.git`,'Clone command'); + else if(action==='edit-item'){switchView('saved');editing=savedItem(b.dataset.url);noteOpen=true;renderCurrent();current.querySelector('textarea')?.focus();current.scrollIntoView?.({block:'start'});} + else if(action==='remove-item'){const removed=savedItem(b.dataset.url);if(await run({type:'REMOVE_ITEM',url:removed.url},'Page removed')){undoItem=removed;if(editing?.url===removed.url)editing=null;const expected=drafts.get(removed.url);drafts.delete(removed.url);try{await options.deleteDraft?.(removed.url,expected);}catch{notify('Page removed. Temporary draft could not be cleared.',true);}renderCurrent();status.append(button('Undo','undo',null,'text-button'));}} + else if(action==='undo'&&undoItem){if(await run({type:'RESTORE_ITEM',item:undoItem},'Page restored'))undoItem=null;} + }); + search.addEventListener('input',()=>{query=search.value;renderList();}); + renderCurrent();switchView(activeView);list.append(node('p','loading','Loading your workspaceโ€ฆ')); + const ready=Promise.all([request({type:'GET_STATE'}),options.loadDrafts?options.loadDrafts():Promise.resolve([])]).then(([next,recovered])=>{for(const [url,note] of recovered){if(!drafts.has(url))drafts.set(url,note);}setState(next);return Promise.all(modules.map(module=>module.ready));}).catch(error=>{list.replaceChildren(node('p','empty-state','Your workspace could not be loaded. Reopen the extension to try again.'));notify(error.message,true);}); + return {ready, setContext(next,data){if(context?.url!==next?.url){editing=null;noteOpen=false;}context=next;if(data)pageData=data;renderCurrent();renderTools();for(const module of modules)module.render();},refresh:async()=>{try{setState(await request({type:'GET_STATE'}));}catch(e){notify(e.message,true);}},openPalette,hasDrafts:()=>drafts.size>0||modules.some(m=>m.hasDrafts?.()),notify,getState:()=>state}; + } + Object.assign(G,{mountWorkbench,uiNode:node,uiButton:button,uiIcon:icon}); +})(); diff --git a/src/shared/workspaces.css b/src/shared/workspaces.css new file mode 100644 index 0000000..06b10e6 --- /dev/null +++ b/src/shared/workspaces.css @@ -0,0 +1 @@ +.workspaces .workspace-create{display:flex;gap:8px;margin:14px 0}.workspace-create input,.workspace-create select{min-width:0;flex:1}.tool-input,.tool-select{padding:9px 10px;border:1px solid var(--border);border-radius:6px;background:var(--canvas);color:var(--ink);width:100%;font-size:12px}.workspaces .workspace-title{margin:22px 0 12px}.workspace-title h3{flex:1;overflow-wrap:anywhere}.workspaces textarea{margin-bottom:8px}.workspaces .tool-heading:not(:first-child){margin-top:22px}.workspace-row{display:flex;align-items:flex-start;gap:10px;padding:13px 0;border-bottom:1px solid var(--border)}.workspace-row-info{min-width:0;flex:1;overflow-wrap:anywhere}.workspace-row-info a{display:block;font-size:12px;font-weight:550;line-height:1.5}.workspace-row-info small{display:block;font-size:10px;margin-top:4px}.workspace-row .button{border:0;background:none;color:var(--muted);padding:2px;font-size:10px}.workspace-row .button:hover{color:var(--danger)}.workspaces>.tool-select{margin-top:6px}.workspaces>.button{margin-top:4px} diff --git a/src/shared/workspaces.js b/src/shared/workspaces.js new file mode 100644 index 0000000..80c176d --- /dev/null +++ b/src/shared/workspaces.js @@ -0,0 +1,82 @@ +(() => { + const G=globalThis.GHE; + const el=(tag,cls,text)=>{const n=document.createElement(tag);if(cls)n.className=cls;if(text!==undefined)n.textContent=text;return n;}; + const btn=(text,action)=>{const b=el('button','button compact',text);b.type='button';b.dataset.ws=action;return b;}; + const safeText=text=>String(text||'').replace(/&/g,'&').replace(//g,'>').replace(/([\\`*_{}\[\]()#+.!|~-])/g,'\\$1'); + function linkedReviewNotes(workspace,state){ + const linked=new Set(); + for(const url of workspace.itemUrls){try{linked.add(G.canonicalPrUrl(url));}catch{}} + const notes=new Map(); + for(const review of state.reviews||[]){let prUrl;try{prUrl=G.canonicalPrUrl(review.prUrl);}catch{continue;}if(!linked.has(prUrl))continue; + for(const file of review.files||[])if(typeof file.note==='string'&&file.note.trim())notes.set(prUrl+'\n'+file.path,{prUrl,path:file.path,note:file.note}); + } + return [...notes.values()]; + } + G.workspaceMarkdown=(workspace,state,options={})=>{ + const pages=workspace.itemUrls.map(url=>state.items.find(i=>i.url===url)||{url,title:'Saved page removed',note:''}); + const snippets=workspace.snippetIds.map(id=>state.snippets.find(s=>s.id===id)).filter(Boolean); + const missingSnippets=workspace.snippetIds.length-snippets.length; + const reviewNotes=options.includeReviewNotes?linkedReviewNotes(workspace,state):[]; + return [`# ${safeText(workspace.title)}`,workspace.note?`## Notes\n\n${workspace.note.split('\n').map(line=>'> '+safeText(line)).join('\n')}`:'',pages.length?'## Pages':'',...pages.map(p=>`${G.markdownLink(p)}${p.note?'\n\n'+p.note.split('\n').map(line=>'> '+safeText(line)).join('\n'):''}`),workspace.snippetIds.length?'## Code':'',missingSnippets?`> ${missingSnippets} linked code excerpt${missingSnippets===1?' is':'s are'} unavailable because the saved excerpt was removed. The remaining evidence follows.`:'',...snippets.map(s=>G.snippetMarkdown(s)),reviewNotes.length?'## Saved private PR file notes':'',...reviewNotes.map(file=>`### ${safeText(file.path)}\n\n${G.markdownLink({url:file.prUrl,title:'Source pull request'})}\n\n${file.note.split('\n').map(line=>'> '+safeText(line)).join('\n')}`)].filter(Boolean).join('\n\n')+'\n'; + }; + G.mountWorkspaces=(root,o)=>{ + let selected=null,busy=false,undo=null,createDraft='';const drafts=new Map(),renameDrafts=new Map(),touched=new Set(),reviewExports=new Set(); + const state=()=>o.getState(),workspace=()=>state().workspaces?.find(w=>w.id===selected); + function persist(key,value){touched.add(key);try{Promise.resolve(o.saveToolDraft?.('workspaces',key,value)).catch(()=>o.notify('Draft recovery unavailable. Save your workspace changes before closing.',true));}catch{o.notify('Draft recovery unavailable. Save your workspace changes before closing.',true);}} + async function clearRecovered(key,value){touched.add(key);try{await o.deleteToolDraft?.('workspaces',key,value);return true;}catch{return false;}} + function updateExportNotice(){const w=workspace(),cue=root.querySelector('[data-workspace-export-notice]');if(cue)cue.hidden=!w||!((drafts.has(w.id)&&drafts.get(w.id)!==w.note)||(renameDrafts.has(w.id)&&renameDrafts.get(w.id)!==w.title));} + function editRename(id,title){renameDrafts.set(id,title);persist('rename:'+id,{title});updateExportNotice();} + function picker(label,items){const s=el('select','tool-select');s.setAttribute('aria-label',label);const empty=el('option','','Chooseโ€ฆ');empty.value='';s.append(empty);for(const item of items){const option=el('option','',item.label);option.value=item.value;s.append(option);}return s;} + async function mutate(message){if(busy)return false;busy=true;try{const next=await o.request(message);o.onState(next);return next;}catch(e){o.notify(e.message||'Could not save this workspace.',true);return false;}finally{busy=false;}} + function linkedRow(title,detail,href,action,id){const row=el('div','workspace-row');const info=el('div','workspace-row-info');const a=el('a','',title);a.href=href;a.target='_blank';a.rel='noopener noreferrer';info.append(a,el('small','muted',detail));const remove=btn('Remove',action);remove.dataset.id=id;row.append(info,remove);return row;} + function render(){ + const active=document.activeElement;const field=root.contains(active)?active?.getAttribute('aria-label'):null,cursor=active?.selectionStart,end=active?.selectionEnd; + function restoreFocus(){if(!field||root.contains(active))return;const restore=[...root.querySelectorAll('[aria-label]')].find(n=>n.getAttribute('aria-label')===field);if(restore){restore.focus();if(typeof cursor==='number'&&typeof restore.setSelectionRange==='function')restore.setSelectionRange(cursor,typeof end==='number'?end:cursor);}} + root.replaceChildren();root.className='tool-section workspaces';const all=state().workspaces||[]; + const heading=el('div','tool-heading');heading.append(el('h2','','Workspaces'),el('span','count',String(all.length)));root.append(heading,el('p','muted tool-intro','Keep the pages, code and notes for one investigation together.')); + const creation=el('form','workspace-create');const name=el('input','tool-input');name.placeholder='e.g. Checkout performance';name.maxLength=100;name.value=createDraft;name.addEventListener('input',()=>{createDraft=name.value;persist('create',{title:createDraft});});name.setAttribute('aria-label','New workspace name');creation.append(name,btn('Create','create'));creation.addEventListener('submit',e=>{e.preventDefault();creation.querySelector('button').click();});root.append(creation); + if(all.length){const switcher=picker('Choose workspace',all.map(w=>({value:w.id,label:w.title})));switcher.value=selected||'';switcher.addEventListener('change',()=>{selected=switcher.value||null;undo=null;render();});root.append(switcher);} + const w=workspace(); + if(!w){root.append(el('p','empty-state',all.length?'Choose a workspace to resume its context.':'Create your first workspace, then add a page or a code excerpt.'));if(undo)root.append(btn('Undo removal','undo'));restoreFocus();return;} + const top=el('div','tool-heading workspace-title');top.append(el('h3','',w.title),btn('Rename','rename'),btn('Delete','delete'));root.append(top);if(renameDrafts.has(w.id)){const input=el('input','tool-input');input.value=renameDrafts.get(w.id);input.maxLength=100;input.setAttribute('aria-label','Rename workspace');input.addEventListener('input',()=>editRename(w.id,input.value));top.querySelector('[data-ws=rename]').replaceWith(input,btn('Save name','save-name'));} + const note=el('textarea');note.rows=3;note.maxLength=10000;note.placeholder='Goals, findings, next stepsโ€ฆ';note.setAttribute('aria-label','Workspace note');note.value=drafts.get(w.id)??w.note;const noteStatus=el('p','muted small',drafts.has(w.id)&&drafts.get(w.id)!==w.note?'Unsaved changes':'Stored only in this browser');noteStatus.dataset.workspaceNoteStatus='';const discard=btn('Discard changes','discard-note');discard.disabled=!drafts.has(w.id);note.addEventListener('input',()=>{drafts.set(w.id,note.value);persist('note:'+w.id,{note:note.value});noteStatus.textContent=note.value===w.note?'No unsaved changes':'Unsaved changes';discard.disabled=false;updateExportNotice();});root.append(note,noteStatus,btn('Save note','save-note'),discard); + const pageHeading=el('div','tool-heading');pageHeading.append(el('h3','',`Pages ยท ${w.itemUrls.length}`));if(o.getContext())pageHeading.append(btn('Add current page','add-current'));root.append(pageHeading); + const pagePicker=picker('Add a saved page',(state().items||[]).filter(p=>!w.itemUrls.includes(p.url)).map(p=>({value:p.url,label:p.title||p.repo})));const pageAdd=el('div','workspace-create');pageAdd.append(pagePicker,btn('Add','add-page'));root.append(pageAdd); + for(const url of w.itemUrls){const item=state().items.find(p=>p.url===url);root.append(linkedRow(item?.title||'Page removed from saved pages',item?.repo||url,url,'unlink-page',url));} + const snippetHeading=el('div','tool-heading');snippetHeading.append(el('h3','',`Code excerpts ยท ${w.snippetIds.length}`));root.append(snippetHeading); + const snippetPicker=picker('Add a saved snippet',(state().snippets||[]).filter(s=>!w.snippetIds.includes(s.id)).map(s=>({value:s.id,label:s.title||s.path})));const snippetAdd=el('div','workspace-create');snippetAdd.append(snippetPicker,btn('Add','add-snippet'));root.append(snippetAdd); + for(const id of w.snippetIds){const s=state().snippets?.find(s=>s.id===id);if(s)root.append(linkedRow(s.title||s.path,s.path,`${s.url.split('#')[0]}#L${s.lineStart}${s.lineEnd!==s.lineStart?'-L'+s.lineEnd:''}`,'unlink-snippet',id));else{const missing=el('div','workspace-row');const b=btn('Remove reference','unlink-snippet');b.dataset.id=id;missing.append(el('span','muted','Excerpt removed from basket'),b);root.append(missing);}} + const reviewNotes=linkedReviewNotes(w,state()); + if(reviewNotes.length){const label=el('label','muted small'),check=el('input');check.type='checkbox';check.dataset.workspaceReviewExport='';check.checked=reviewExports.has(w.id);check.addEventListener('change',()=>{if(check.checked)reviewExports.add(w.id);else reviewExports.delete(w.id);});label.append(check,document.createTextNode(` Include ${reviewNotes.length} saved private PR file note${reviewNotes.length===1?'':'s'} in Markdown`));root.append(label);} + const exportNotice=el('p','muted small','Export uses saved notes and titles. Save your edits to include them.');exportNotice.dataset.workspaceExportNotice='';root.append(exportNotice);updateExportNotice(); + const actions=el('div','tool-actions');actions.append(btn('Copy Markdown','copy'),btn('Download .md','download'));if(w.itemUrls.length&&o.openPages)actions.append(btn(`Open ${Math.min(w.itemUrls.length,10)} ${w.itemUrls.length===1?'page':'pages'}${w.itemUrls.length>10?' (first 10)':''}`,'open'));root.append(actions); + if(undo)root.append(btn('Undo removal','undo')); + restoreFocus(); + } + root.addEventListener('click',async e=>{ + const b=e.target.closest('[data-ws]');if(!b||busy)return;const action=b.dataset.ws,w=workspace(); + if(action==='create'){const input=root.querySelector('[aria-label="New workspace name"]');const submitted=input.value,title=submitted.trim();touched.add('create');if(!title){o.notify('Give this workspace a name.',true);input.focus();return;}const previous=new Set((state().workspaces||[]).map(w=>w.id));const next=await mutate({type:'CREATE_WORKSPACE',title});if(next){if(createDraft===submitted)createDraft='';const cleared=await clearRecovered('create',{title:submitted});selected=next.workspaces.find(w=>!previous.has(w.id))?.id;render();o.notify(cleared?'Workspace created':'Workspace created. The recovery draft could not be cleared.',!cleared);}return;} + if(action==='undo'&&undo){const pending=undo;if(await mutate(pending.message)){undo=null;if(pending.selected)selected=pending.selected;render();o.notify('Restored');}return;} + if(!w)return; + if(action==='save-note'){const value=root.querySelector('[aria-label="Workspace note"]').value;touched.add('note:'+w.id);if(await mutate({type:'UPDATE_WORKSPACE',id:w.id,patch:{note:value}})){if(drafts.get(w.id)===value)drafts.delete(w.id);const cleared=await clearRecovered('note:'+w.id,{note:value});render();o.notify(cleared?'Workspace note saved':'Workspace note saved. The recovery draft could not be cleared.',!cleared);}} + else if(action==='discard-note'){const value=drafts.get(w.id);drafts.delete(w.id);const cleared=await clearRecovered('note:'+w.id,{note:value});if(!cleared&&!drafts.has(w.id))drafts.set(w.id,value);render();o.notify(cleared?'Workspace note changes discarded':'Draft could not be cleared. Please try again.',!cleared);} + else if(action==='rename'){touched.add('rename:'+w.id);renameDrafts.set(w.id,w.title);const input=el('input','tool-input');input.value=w.title;input.maxLength=100;input.addEventListener('input',()=>editRename(w.id,input.value));input.setAttribute('aria-label','Rename workspace');const save=btn('Save name','save-name');b.replaceWith(input,save);input.focus();} + else if(action==='save-name'){const submitted=root.querySelector('[aria-label="Rename workspace"]').value,title=submitted.trim();touched.add('rename:'+w.id);if(title&&await mutate({type:'UPDATE_WORKSPACE',id:w.id,patch:{title}})){if(renameDrafts.get(w.id)===submitted)renameDrafts.delete(w.id);const cleared=await clearRecovered('rename:'+w.id,{title:submitted});render();o.notify(cleared?'Workspace renamed':'Workspace renamed. The recovery draft could not be cleared.',!cleared);}} + else if(action==='delete'){if(await mutate({type:'REMOVE_WORKSPACE',id:w.id})){undo={message:{type:'RESTORE_WORKSPACE',workspace:w},selected:w.id};selected=null;render();o.notify('Workspace removed. Saved pages and excerpts remain.');}} + else if(action==='add-current'){const context=o.getContext();if(!context)return;if(!state().items.some(i=>i.url===context.url)&&!await mutate({type:'SAVE_ITEM',context}))return;if(await mutate({type:'LINK_WORKSPACE_ITEM',id:w.id,url:context.url}))o.notify('Page added to workspace');} + else if(action==='add-page'){const url=root.querySelector('[aria-label="Add a saved page"]').value;if(url&&await mutate({type:'LINK_WORKSPACE_ITEM',id:w.id,url}))o.notify('Page added to workspace');} + else if(action==='add-snippet'){const snippetId=root.querySelector('[aria-label="Add a saved snippet"]').value;if(snippetId&&await mutate({type:'LINK_WORKSPACE_SNIPPET',id:w.id,snippetId}))o.notify('Excerpt added to workspace');} + else if(action==='unlink-page'||action==='unlink-snippet'){const page=action==='unlink-page';const message={type:page?'UNLINK_WORKSPACE_ITEM':'UNLINK_WORKSPACE_SNIPPET',id:w.id,[page?'url':'snippetId']:b.dataset.id};if(await mutate(message)){undo=(page?state().items.some(p=>p.url===b.dataset.id):state().snippets.some(s=>s.id===b.dataset.id))?{message:{...message,type:page?'LINK_WORKSPACE_ITEM':'LINK_WORKSPACE_SNIPPET'}}:null;render();o.notify('Removed from this workspace');}} + else if(action==='copy'||action==='download'){const markdown=G.workspaceMarkdown(w,{...state(),snippets:state().snippets||[]},{includeReviewNotes:reviewExports.has(w.id)});try{if(action==='copy')await o.copy(markdown);else{const url=URL.createObjectURL(new Blob([markdown],{type:'text/markdown;charset=utf-8'}));const a=el('a');a.href=url;a.download=w.title.replace(/[^a-z0-9-]/gi,'-').slice(0,70)+'.md';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}o.notify(action==='copy'?'Workspace Markdown copied':'Workspace download started');}catch{o.notify('Export unavailable. Try the toolbar popup.',true);}} + else if(action==='open'){try{await o.openPages(w.itemUrls.slice(0,10));o.notify('Workspace pages opened');}catch{o.notify('Could not open all pages. Use the source links below.',true);}} + }); + const ready=Promise.resolve().then(()=>o.loadToolDrafts?.('workspaces')||[]).then(entries=>{ + for(const [key,value] of entries){if(typeof key!=='string'||touched.has(key)||!value||typeof value!=='object')continue; + if(key==='create'&&typeof value.title==='string'&&value.title.length<=100)createDraft=value.title; + else if(key.startsWith('note:')&&typeof value.note==='string'&&value.note.length<=10000)drafts.set(key.slice(5),value.note); + else if(key.startsWith('rename:')&&typeof value.title==='string'&&value.title.length<=100)renameDrafts.set(key.slice(7),value.title); + }render(); + }).catch(()=>o.notify('Workspace draft recovery unavailable. Save your changes before closing.',true)); + return {render,ready,select(id){if(!(state().workspaces||[]).some(w=>w.id===id))return false;selected=id;undo=null;render();return true;},hasDrafts:()=>Boolean(createDraft.trim())||(state().workspaces||[]).some(w=>(drafts.has(w.id)&&drafts.get(w.id)!==w.note)||(renameDrafts.has(w.id)&&renameDrafts.get(w.id)!==w.title))}; + }; +})(); diff --git a/src/styles/content.css b/src/styles/content.css deleted file mode 100644 index c3cca7f..0000000 --- a/src/styles/content.css +++ /dev/null @@ -1,391 +0,0 @@ -/* Root Variables */ -:root { - /* Animation Timings */ - --gh-ext-transition-fast: 0.15s; - --gh-ext-transition-normal: 0.3s; - --gh-ext-transition-slow: 0.5s; - - /* Spacing */ - --gh-ext-spacing-xs: 4px; - --gh-ext-spacing-sm: 8px; - --gh-ext-spacing-md: 16px; - --gh-ext-spacing-lg: 24px; - - /* Component Sizes */ - --gh-ext-card-height: 80px; - --gh-ext-avatar-size: 60px; - --gh-ext-settings-width: 300px; - - /* Z-index Layers */ - --gh-ext-z-card: 1; - --gh-ext-z-settings: 9999; - --gh-ext-z-button: 10000; - - /* Animation Colors - Using GitHub theme colors */ - --gh-ext-gradient-1: var(--color-accent-subtle, #388bfd26); - --gh-ext-gradient-2: var(--color-success-subtle, #2ea04326); - --gh-ext-gradient-3: var(--color-attention-subtle, #d4a72c26); -} - -/* Modern Card Animation Keyframes */ -@keyframes cardShimmer { - 0% { - background-position: 200% 0; - } - 100% { - background-position: -200% 0; - } -} - -@keyframes pulseCard { - 0% { - box-shadow: 0 0 0 0 var(--color-accent-subtle); - } - 70% { - box-shadow: 0 0 0 10px transparent; - } - 100% { - box-shadow: 0 0 0 0 transparent; - } -} - -/* Contributor Card */ -.contributor-card { - position: relative; - display: flex; - align-items: flex-start; - background: var(--color-canvas-overlay); - border: 1px solid var(--color-border-default); - border-radius: 6px; - padding: var(--gh-ext-spacing-sm); - margin-bottom: var(--gh-ext-spacing-sm); - width: 100%; - height: var(--gh-ext-card-height); - box-sizing: border-box; - overflow: hidden; - z-index: var(--gh-ext-z-card); - transform: translateZ(0); - will-change: transform, height; - transition: all var(--gh-ext-transition-normal) ease; -} - -/* Card Background Animation */ -.contributor-card::before { - content: ''; - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - background: linear-gradient( - 120deg, - transparent 0%, - transparent 35%, - var(--gh-ext-gradient-1) 45%, - var(--gh-ext-gradient-2) 50%, - var(--gh-ext-gradient-3) 55%, - transparent 65%, - transparent 100% - ); - background-size: 200% 100%; - opacity: 0; - transition: opacity var(--gh-ext-transition-normal); - z-index: -1; -} - -.contributor-card:hover { - height: auto; - transform: translateY(-5px); - box-shadow: - 0 8px 24px rgba(0, 0, 0, 0.12), - 0 2px 8px rgba(0, 0, 0, 0.08); -} - -.contributor-card:hover::before { - opacity: 1; - animation: cardShimmer 3s linear infinite; -} - -.contributor-card:focus-within { - outline: 2px solid var(--color-accent-fg); - outline-offset: 2px; -} - -/* Avatar */ -.contributor-avatar { - width: var(--gh-ext-avatar-size); - height: var(--gh-ext-avatar-size); - border-radius: 50%; - border: 2px solid var(--color-border-default); - margin-right: var(--gh-ext-spacing-md); - transform: translateZ(0); - will-change: transform; - transition: all var(--gh-ext-transition-normal) cubic-bezier(0.34, 1.56, 0.64, 1); -} - -.contributor-card:hover .contributor-avatar { - transform: scale(1.1) rotate(8deg); - border-color: var(--color-accent-fg); - box-shadow: 0 0 15px var(--color-accent-muted); -} - -/* Details Section */ -.contributor-details { - flex: 1; - display: flex; - flex-direction: column; - overflow: hidden; -} - -.contributor-main-info { - transform: translateZ(0); - transition: transform var(--gh-ext-transition-normal) ease; -} - -.contributor-username { - font-weight: 600; - color: var(--color-accent-fg); - font-size: 1em; - margin-bottom: var(--gh-ext-spacing-xs); - transition: color var(--gh-ext-transition-normal) ease; -} - -.contributor-card:hover .contributor-username { - color: var(--color-accent-emphasis); -} - -.contributor-name { - font-weight: 600; - color: var(--color-fg-default); - font-size: 0.9em; - transition: color var(--gh-ext-transition-normal) ease; -} - -.contributor-card:hover .contributor-name { - color: var(--color-success-fg); -} - -.contributor-extra-info { - max-height: 0; - opacity: 0; - overflow: hidden; - transform: translateY(10px); - transition: all var(--gh-ext-transition-normal) cubic-bezier(0.4, 0, 0.2, 1); -} - -.contributor-card:hover .contributor-extra-info { - max-height: 500px; - opacity: 1; - transform: translateY(0); - margin-top: var(--gh-ext-spacing-sm); -} - -.contributor-info { - color: var(--color-fg-muted); - font-size: 0.85em; - margin-top: var(--gh-ext-spacing-xs); - padding: 4px 8px; - border-radius: 4px; - background: var(--color-canvas-subtle); - transform: translateX(-10px); - opacity: 0; - transition: all var(--gh-ext-transition-normal) cubic-bezier(0.4, 0, 0.2, 1); -} - -.contributor-card:hover .contributor-info { - transform: translateX(0); - opacity: 1; -} - -/* Staggered Animation */ -.contributor-card:hover .contributor-info:nth-child(1) { - transition-delay: 0.1s; -} -.contributor-card:hover .contributor-info:nth-child(2) { - transition-delay: 0.2s; -} -.contributor-card:hover .contributor-info:nth-child(3) { - transition-delay: 0.3s; -} - -/* Settings Panel */ -#github-extension-settings { - position: fixed; - bottom: var(--gh-ext-spacing-md); - left: var(--gh-ext-spacing-md); - background: var(--color-canvas-overlay); - border: 1px solid var(--color-border-default); - border-radius: 6px; - padding: var(--gh-ext-spacing-md); - width: var(--gh-ext-settings-width); - box-shadow: var(--color-shadow-medium); - z-index: var(--gh-ext-z-settings); - font-family: var(--font-family-sans); - backdrop-filter: blur(8px); - color: var(--color-fg-default); -} - -#github-extension-settings h2 { - margin: 0 0 var(--gh-ext-spacing-md) 0; - font-size: 16px; - font-weight: 600; - color: var(--color-fg-default); - border-bottom: 1px solid var(--color-border-muted); - padding-bottom: var(--gh-ext-spacing-sm); -} - -.settings-controls { - display: flex; - flex-direction: column; - gap: 12px; -} - -.settings-controls label { - display: flex; - align-items: center; - gap: var(--gh-ext-spacing-sm); - font-size: 14px; - cursor: pointer; -} - -.settings-controls input[type="checkbox"] { - margin: 0; - cursor: pointer; -} - -.settings-controls input[type="number"], -.settings-controls input[type="text"] { - padding: 4px 8px; - border: 1px solid var(--color-border-default); - border-radius: 4px; - background: var(--color-canvas-subtle); - color: var(--color-fg-default); - font-size: 14px; -} - -.settings-controls input[type="number"] { - width: 80px; -} - -.settings-controls input[type="text"] { - width: 120px; -} - -/* Settings Buttons */ -.settings-buttons { - display: flex; - gap: var(--gh-ext-spacing-sm); - margin-top: var(--gh-ext-spacing-md); - justify-content: flex-end; -} - -.settings-buttons button { - padding: 4px 12px; - border-radius: 6px; - border: 1px solid var(--color-border-default); - font-size: 14px; - font-weight: 500; - cursor: pointer; - transition: all var(--gh-ext-transition-fast) ease; -} - -.settings-buttons button.btn-primary { - background-color: var(--color-btn-primary-bg); - color: var(--color-btn-primary-text); - border-color: var(--color-btn-primary-border); -} - -.settings-buttons button:hover { - background-color: var(--color-btn-hover-bg); - transform: translateY(-1px); -} - -/* Settings Toggle Button */ -.github-extension-settings-button { - position: fixed; - bottom: var(--gh-ext-spacing-sm); - left: var(--gh-ext-spacing-sm); - background-color: var(--color-btn-bg); - color: var(--color-btn-text); - border: 1px solid var(--color-btn-border); - border-radius: 50%; - width: 30px; - height: 30px; - font-size: 16px; - cursor: pointer; - z-index: var(--gh-ext-z-button); - transition: all var(--gh-ext-transition-fast) ease; -} - -.github-extension-settings-button:hover { - background-color: var(--color-btn-hover-bg); - transform: scale(1.1); -} - -/* Enhanced Date Display */ -.enhanced-date { - font-size: 0.85em; - color: var(--color-fg-muted); - margin-top: var(--gh-ext-spacing-xs); -} - -/* Media Queries */ -@media (max-width: 768px) { - :root { - --gh-ext-avatar-size: 40px; - --gh-ext-settings-width: calc(100vw - 40px); - } - - .contributor-card { - padding: var(--gh-ext-spacing-xs); - } - - #github-extension-settings { - left: var(--gh-ext-spacing-sm); - right: var(--gh-ext-spacing-sm); - bottom: var(--gh-ext-spacing-sm); - width: auto; - } -} - -/* Accessibility */ -@media (prefers-reduced-motion: reduce) { - .contributor-card, - .contributor-card::before, - .contributor-avatar, - .contributor-extra-info, - .contributor-info, - .settings-buttons button { - transition: none !important; - animation: none !important; - } - - .contributor-card:hover .contributor-avatar { - transform: none; - } -} - -@media (prefers-contrast: high) { - .contributor-card { - border-width: 2px; - } - - .contributor-username, - .contributor-name { - text-shadow: none; - } -} - -/* Print Styles */ -@media print { - .contributor-card { - break-inside: avoid; - border: 1px solid #000; - box-shadow: none; - } - - .github-extension-settings-button, - #github-extension-settings { - display: none; - } -} \ No newline at end of file diff --git a/src/utils/api-utils.js b/src/utils/api-utils.js deleted file mode 100644 index 8250c42..0000000 --- a/src/utils/api-utils.js +++ /dev/null @@ -1,376 +0,0 @@ -/** - * API utility functions for GitHub Enhancer - * Handles GitHub API requests with rate limiting and error handling - */ - -const APIUtils = (() => { - const Logger = window.Logger || console; - const Storage = window.Storage; - - // Define constants locally - const API_CONFIG = { - GITHUB_API_BASE: 'https://api.github.com', - REQUEST_TIMEOUT: 10000, - RETRY_ATTEMPTS: 2, - RETRY_DELAY: 1000, - RATE_LIMIT_THRESHOLD: 5 - }; - - const ERROR_TYPES = { - NETWORK: 'NETWORK_ERROR', - RATE_LIMIT: 'RATE_LIMIT_ERROR', - AUTHENTICATION: 'AUTH_ERROR' - }; - - const STORAGE_KEYS = { - AUTH_TOKEN: 'github_enhancer_auth_token' - }; - - /** - * Custom error for API operations - */ - class APIError extends Error { - constructor(message, type = ERROR_TYPES.NETWORK, statusCode = null, originalError = null) { - super(message); - this.name = 'APIError'; - this.type = type; - this.statusCode = statusCode; - this.originalError = originalError; - } - } - - /** - * Rate limiting state - */ - const rateLimitState = { - remaining: 60, - reset: 0, - limit: 60, - isLimited: false - }; - - /** - * Request queue for rate limiting - */ - const requestQueue = { - items: [], - processing: false, - - add(requestFn) { - return new Promise((resolve, reject) => { - this.items.push({ requestFn, resolve, reject }); - this.process(); - }); - }, - - async process() { - if (this.processing || this.items.length === 0) { - return; - } - - this.processing = true; - - while (this.items.length > 0) { - if (rateLimitState.isLimited) { - const waitTime = rateLimitState.reset - Date.now(); - if (waitTime > 0) { - Logger.warn(`Rate limited, waiting ${waitTime}ms`); - await new Promise(resolve => setTimeout(resolve, waitTime)); - } - rateLimitState.isLimited = false; - } - - const { requestFn, resolve, reject } = this.items.shift(); - - try { - const result = await requestFn(); - resolve(result); - } catch (error) { - reject(error); - } - - // Small delay between requests - await new Promise(resolve => setTimeout(resolve, 100)); - } - - this.processing = false; - } - }; - - /** - * Update rate limit state from response headers - */ - const updateRateLimit = (response) => { - try { - const remaining = parseInt(response.headers.get('X-RateLimit-Remaining') || '60'); - const reset = parseInt(response.headers.get('X-RateLimit-Reset') || '0') * 1000; - const limit = parseInt(response.headers.get('X-RateLimit-Limit') || '60'); - - rateLimitState.remaining = remaining; - rateLimitState.reset = reset; - rateLimitState.limit = limit; - rateLimitState.isLimited = remaining <= API_CONFIG.RATE_LIMIT_THRESHOLD; - - Logger.debug(`Rate limit updated: ${remaining}/${limit}, resets at ${new Date(reset)}`); - } catch (error) { - Logger.warn('Failed to parse rate limit headers:', error); - } - }; - - /** - * Get authentication headers - */ - const getAuthHeaders = async () => { - try { - const token = await Storage.get(STORAGE_KEYS.AUTH_TOKEN); - if (token) { - return { 'Authorization': `token ${token}` }; - } - } catch (error) { - Logger.warn('Failed to get auth token:', error); - } - return {}; - }; - - /** - * Make HTTP request with retry logic - */ - const makeRequest = async (url, options = {}) => { - const { - method = 'GET', - headers = {}, - body = null, - timeout = API_CONFIG.REQUEST_TIMEOUT, - retries = API_CONFIG.RETRY_ATTEMPTS - } = options; - - const authHeaders = await getAuthHeaders(); - const requestHeaders = { - 'Accept': 'application/vnd.github.v3+json', - 'User-Agent': 'GitHub-Enhancer-Extension', - ...authHeaders, - ...headers - }; - - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeout); - - let lastError; - - for (let attempt = 0; attempt <= retries; attempt++) { - try { - const response = await fetch(url, { - method, - headers: requestHeaders, - body, - signal: controller.signal - }); - - clearTimeout(timeoutId); - updateRateLimit(response); - - if (!response.ok) { - if (response.status === 403 && response.headers.get('X-RateLimit-Remaining') === '0') { - rateLimitState.isLimited = true; - throw new APIError( - 'Rate limit exceeded', - ERROR_TYPES.RATE_LIMIT, - response.status - ); - } - - if (response.status === 401) { - throw new APIError( - 'Authentication required', - ERROR_TYPES.AUTHENTICATION, - response.status - ); - } - - throw new APIError( - `HTTP ${response.status}: ${response.statusText}`, - ERROR_TYPES.NETWORK, - response.status - ); - } - - return response; - } catch (error) { - lastError = error; - - if (error.name === 'AbortError') { - throw new APIError('Request timeout', ERROR_TYPES.NETWORK, null, error); - } - - if (error instanceof APIError) { - throw error; - } - - if (attempt < retries) { - const delay = API_CONFIG.RETRY_DELAY * Math.pow(2, attempt); - Logger.debug(`Request failed, retrying in ${delay}ms (attempt ${attempt + 1}/${retries + 1})`); - await new Promise(resolve => setTimeout(resolve, delay)); - } - } - } - - clearTimeout(timeoutId); - throw new APIError( - `Request failed after ${retries + 1} attempts`, - ERROR_TYPES.NETWORK, - null, - lastError - ); - }; - - /** - * GitHub API request wrapper - */ - const githubRequest = async (endpoint, options = {}) => { - const url = endpoint.startsWith('http') ? endpoint : `${API_CONFIG.GITHUB_API_BASE}${endpoint}`; - - return requestQueue.add(async () => { - Logger.debug(`Making GitHub API request: ${url}`); - const response = await makeRequest(url, options); - return response.json(); - }); - }; - - /** - * Get repository information from current URL - */ - const getRepoInfo = () => { - try { - const pathParts = window.location.pathname.split('/').filter(Boolean); - - if (pathParts.length >= 2) { - return { - owner: pathParts[0], - repo: pathParts[1], - path: pathParts.slice(2).join('/'), - branch: getBranchFromURL() - }; - } - - throw new Error('Unable to parse repository information from URL'); - } catch (error) { - Logger.logError(error, { context: 'Getting repo info', url: window.location.href }); - return null; - } - }; - - /** - * Get current branch from DOM or URL - */ - const getBranchFromURL = () => { - try { - // Try to get from branch selector - const branchElement = document.querySelector('[data-hotkey="w"] span'); - if (branchElement) { - return branchElement.textContent.trim(); - } - - // Fallback to URL parsing - const urlParams = new URLSearchParams(window.location.search); - return urlParams.get('ref') || 'main'; - } catch (error) { - Logger.warn('Failed to get branch, using default:', error); - return 'main'; - } - }; - - /** - * Cached API requests - */ - const cachedRequest = async (cacheKey, requestFn, ttl = null) => { - try { - // Try to get from cache - const cached = await Storage.cache.get(cacheKey); - if (cached) { - Logger.debug(`Cache hit for: ${cacheKey}`); - return cached; - } - - // Make request and cache result - Logger.debug(`Cache miss for: ${cacheKey}, making request`); - const result = await requestFn(); - - await Storage.cache.set(cacheKey, result, ttl); - return result; - } catch (error) { - Logger.logError(error, { context: 'Cached request', cacheKey }); - throw error; - } - }; - - /** - * Specific GitHub API methods - */ - const github = { - async getUser(username) { - return githubRequest(`/users/${username}`); - }, - - async getUserRepos(username, page = 1, perPage = 30) { - return githubRequest(`/users/${username}/repos?page=${page}&per_page=${perPage}&sort=updated`); - }, - - async getRepo(owner, repo) { - return githubRequest(`/repos/${owner}/${repo}`); - }, - - async getRepoContributors(owner, repo, page = 1, perPage = 30) { - return githubRequest(`/repos/${owner}/${repo}/contributors?page=${page}&per_page=${perPage}`); - }, - - async getRepoContents(owner, repo, path = '', ref = 'main') { - const endpoint = `/repos/${owner}/${repo}/contents/${path}`; - const params = ref !== 'main' ? `?ref=${ref}` : ''; - return githubRequest(`${endpoint}${params}`); - }, - - async getCommit(owner, repo, sha) { - return githubRequest(`/repos/${owner}/${repo}/commits/${sha}`); - }, - - async getUserOrgs(username) { - return githubRequest(`/users/${username}/orgs`); - }, - - async getRepoStats(owner, repo) { - return githubRequest(`/repos/${owner}/${repo}/stats/contributors`); - } - }; - - // Public API - return { - makeRequest, - githubRequest, - cachedRequest, - getRepoInfo, - getBranchFromURL, - github, - getRateLimit: () => ({ ...rateLimitState }), - APIError, - - // Utility methods - async clearCache() { - // Clear all API-related cache entries - Logger.info('Clearing API cache'); - // This would need to be implemented based on your cache structure - }, - - async testConnection() { - try { - await githubRequest('/rate_limit'); - return true; - } catch (error) { - Logger.logError(error, { context: 'Testing API connection' }); - return false; - } - } - }; -})(); - -// Global availability -window.APIUtils = APIUtils; \ No newline at end of file diff --git a/src/utils/constants.js b/src/utils/constants.js deleted file mode 100644 index 2877221..0000000 --- a/src/utils/constants.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Constants and configuration for GitHub Enhancer - */ - -// Extension configuration -const EXTENSION_CONFIG = { - NAME: 'GitHub Enhancer', - VERSION: '2.0.0', - DEBUG_PREFIX: '[GitHub Enhancer]', - PERFORMANCE_METRICS_ENABLED: true -}; - -// API Configuration -const API_CONFIG = { - GITHUB_API_BASE: 'https://api.github.com', - RATE_LIMIT_THRESHOLD: 10, - REQUEST_TIMEOUT: 5000, - RETRY_ATTEMPTS: 3, - RETRY_DELAY: 1000 -}; - -// UI Configuration -const UI_CONFIG = { - CARD_MIN_WIDTH: 200, - CARD_MAX_WIDTH: 400, - CARD_DEFAULT_WIDTH: 250, - MAX_CARDS_MIN: 5, - MAX_CARDS_MAX: 50, - MAX_CARDS_DEFAULT: 10, - ANIMATION_DURATION: 300, - DEBOUNCE_DELAY: 250 -}; - -// Storage Keys -const STORAGE_KEYS = { - SETTINGS: 'github_enhancer_settings', - AUTH_TOKEN: 'github_auth_token', - CACHE_PREFIX: 'github_enhancer_cache_', - USER_PREFERENCES: 'github_enhancer_preferences' -}; - -// Log Levels -const LOG_LEVELS = { - ERROR: 0, - WARN: 1, - INFO: 2, - DEBUG: 3 -}; - -// Default Settings -const DEFAULT_SETTINGS = { - enhanceContributors: true, - enhanceDateTimes: true, - enhanceFileSizes: true, - enableThemeEnhancements: true, - showCommitInfo: true, - showTeamInfo: true, - showOrgInfo: true, - cardWidth: UI_CONFIG.CARD_DEFAULT_WIDTH, - maxCards: UI_CONFIG.MAX_CARDS_DEFAULT, - locale: 'en-US', - theme: 'auto', // 'light', 'dark', 'auto' - animationsEnabled: true, - debugMode: false -}; - -// DOM Selectors -const SELECTORS = { - CONTRIBUTORS_SECTION: '.BorderGrid-row', - RELATIVE_TIME: 'relative-time', - FILE_ROWS: 'tr.react-directory-row', - REPOSITORY_CONTENT: '.repository-content', - COMMIT_INFO: '.commit-info', - BRANCH_SELECTOR: '[data-hotkey="w"] span' -}; - -// Error Types -const ERROR_TYPES = { - NETWORK: 'NETWORK_ERROR', - RATE_LIMIT: 'RATE_LIMIT_ERROR', - AUTHENTICATION: 'AUTH_ERROR', - PARSING: 'PARSING_ERROR', - DOM: 'DOM_ERROR', - STORAGE: 'STORAGE_ERROR', - GENERAL: 'GENERAL_ERROR' -}; - -// Event Types -const EVENT_TYPES = { - SETTINGS_CHANGED: 'github_enhancer_settings_changed', - ENHANCEMENT_COMPLETE: 'github_enhancer_enhancement_complete', - ERROR_OCCURRED: 'github_enhancer_error_occurred' -}; - -// Cache Settings -const CACHE_CONFIG = { - DEFAULT_TTL: 5 * 60 * 1000, // 5 minutes - MAX_ENTRIES: 100, - CLEANUP_INTERVAL: 10 * 60 * 1000 // 10 minutes -}; - -// Export all constants -window.GITHUB_ENHANCER_CONSTANTS = { - EXTENSION_CONFIG, - API_CONFIG, - UI_CONFIG, - STORAGE_KEYS, - LOG_LEVELS, - DEFAULT_SETTINGS, - SELECTORS, - ERROR_TYPES, - EVENT_TYPES, - CACHE_CONFIG -}; \ No newline at end of file diff --git a/src/utils/date-utils.js b/src/utils/date-utils.js deleted file mode 100644 index d6d9dfc..0000000 --- a/src/utils/date-utils.js +++ /dev/null @@ -1,343 +0,0 @@ -/** - * Date utility functions for GitHub Enhancer - * Provides date formatting and relative time calculations - */ - -const DateUtils = (() => { - const { Logger } = window; - const { ERROR_TYPES } = window.GITHUB_ENHANCER_CONSTANTS; - - /** - * Custom error for date operations - */ - class DateError extends Error { - constructor(message, type = ERROR_TYPES.PARSING, originalError = null) { - super(message); - this.name = 'DateError'; - this.type = type; - this.originalError = originalError; - } - } - - /** - * Format date/time with locale support - */ - const formatDateTime = (dateInput, locale = 'en-US', options = null) => { - try { - let date; - - if (dateInput instanceof Date) { - date = dateInput; - } else if (typeof dateInput === 'string' || typeof dateInput === 'number') { - date = new Date(dateInput); - } else { - throw new DateError('Invalid date input type'); - } - - if (isNaN(date.getTime())) { - throw new DateError('Invalid date value'); - } - - const defaultOptions = { - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - hour12: false - }; - - const formatOptions = options || defaultOptions; - return date.toLocaleString(locale, formatOptions); - } catch (error) { - Logger.logError(error, { - context: 'Formatting date', - input: dateInput, - locale, - options - }); - return dateInput ? dateInput.toString() : 'Invalid Date'; - } - }; - - /** - * Get relative time string using Intl.RelativeTimeFormat - */ - const getRelativeTimeString = (dateInput, locale = 'en-US', options = {}) => { - try { - const date = new Date(dateInput); - const now = new Date(); - - if (isNaN(date.getTime())) { - throw new DateError('Invalid date for relative time calculation'); - } - - const diffInSeconds = Math.floor((now - date) / 1000); - const rtfOptions = { numeric: 'auto', ...options }; - const rtf = new Intl.RelativeTimeFormat(locale, rtfOptions); - - // Time intervals in seconds - const intervals = [ - { unit: 'year', seconds: 31536000 }, - { unit: 'month', seconds: 2592000 }, - { unit: 'week', seconds: 604800 }, - { unit: 'day', seconds: 86400 }, - { unit: 'hour', seconds: 3600 }, - { unit: 'minute', seconds: 60 }, - { unit: 'second', seconds: 1 } - ]; - - for (const interval of intervals) { - const count = Math.floor(diffInSeconds / interval.seconds); - if (count >= 1 || interval.unit === 'second') { - return rtf.format(-count, interval.unit); - } - } - - return rtf.format(0, 'second'); - } catch (error) { - Logger.logError(error, { - context: 'Getting relative time string', - input: dateInput, - locale - }); - return 'some time ago'; - } - }; - - /** - * Parse GitHub's datetime format - */ - const parseGitHubDateTime = (dateTimeString) => { - try { - // GitHub typically uses ISO 8601 format - const date = new Date(dateTimeString); - - if (isNaN(date.getTime())) { - // Try alternative parsing methods - const cleanedString = dateTimeString.replace(/[^\d\-T:\.Z]/g, ''); - const alternativeDate = new Date(cleanedString); - - if (isNaN(alternativeDate.getTime())) { - throw new DateError(`Unable to parse GitHub datetime: ${dateTimeString}`); - } - - return alternativeDate; - } - - return date; - } catch (error) { - Logger.logError(error, { - context: 'Parsing GitHub datetime', - input: dateTimeString - }); - throw new DateError(`Failed to parse GitHub datetime: ${dateTimeString}`, ERROR_TYPES.PARSING, error); - } - }; - - /** - * Get time ago in human readable format (fallback for older browsers) - */ - const getTimeAgo = (dateInput, options = {}) => { - try { - const date = new Date(dateInput); - const now = new Date(); - - if (isNaN(date.getTime())) { - throw new DateError('Invalid date for time ago calculation'); - } - - const diffInSeconds = Math.floor((now - date) / 1000); - const { short = false } = options; - - const intervals = [ - { name: 'year', seconds: 31536000, shortName: 'y' }, - { name: 'month', seconds: 2592000, shortName: 'mo' }, - { name: 'week', seconds: 604800, shortName: 'w' }, - { name: 'day', seconds: 86400, shortName: 'd' }, - { name: 'hour', seconds: 3600, shortName: 'h' }, - { name: 'minute', seconds: 60, shortName: 'm' }, - { name: 'second', seconds: 1, shortName: 's' } - ]; - - for (const interval of intervals) { - const count = Math.floor(diffInSeconds / interval.seconds); - if (count >= 1) { - const unit = short ? interval.shortName : - count === 1 ? interval.name : `${interval.name}s`; - return short ? `${count}${unit}` : `${count} ${unit} ago`; - } - } - - return short ? '0s' : 'just now'; - } catch (error) { - Logger.logError(error, { - context: 'Getting time ago', - input: dateInput - }); - return 'some time ago'; - } - }; - - /** - * Check if date is today - */ - const isToday = (dateInput) => { - try { - const date = new Date(dateInput); - const today = new Date(); - - return date.getDate() === today.getDate() && - date.getMonth() === today.getMonth() && - date.getFullYear() === today.getFullYear(); - } catch (error) { - Logger.logError(error, { context: 'Checking if date is today', input: dateInput }); - return false; - } - }; - - /** - * Check if date is this week - */ - const isThisWeek = (dateInput) => { - try { - const date = new Date(dateInput); - const today = new Date(); - const weekStart = new Date(today.setDate(today.getDate() - today.getDay())); - const weekEnd = new Date(today.setDate(weekStart.getDate() + 6)); - - return date >= weekStart && date <= weekEnd; - } catch (error) { - Logger.logError(error, { context: 'Checking if date is this week', input: dateInput }); - return false; - } - }; - - /** - * Format date for different contexts - */ - const contextualFormat = (dateInput, context = 'default', locale = 'en-US') => { - try { - const date = new Date(dateInput); - - if (isNaN(date.getTime())) { - throw new DateError('Invalid date for contextual formatting'); - } - - const formats = { - short: { - year: 'numeric', - month: 'short', - day: 'numeric' - }, - long: { - weekday: 'long', - year: 'numeric', - month: 'long', - day: 'numeric', - hour: '2-digit', - minute: '2-digit' - }, - time: { - hour: '2-digit', - minute: '2-digit', - second: '2-digit' - }, - compact: { - month: '2-digit', - day: '2-digit', - year: '2-digit' - }, - iso: null // Special case for ISO string - }; - - if (context === 'iso') { - return date.toISOString(); - } - - const options = formats[context] || formats.short; - return date.toLocaleString(locale, options); - } catch (error) { - Logger.logError(error, { - context: 'Contextual date formatting', - input: dateInput, - formatContext: context - }); - return dateInput ? dateInput.toString() : 'Invalid Date'; - } - }; - - /** - * Create enhanced datetime element - */ - const createEnhancedDateElement = (originalDate, formattedDate, options = {}) => { - try { - const { - showRelative = true, - showTooltip = true, - className = 'github-enhancer-date', - updateInterval = null - } = options; - - const container = window.DOMUtils.createElement('span', { - classes: [className], - attributes: { - 'data-original-date': originalDate, - 'data-enhanced': 'true' - } - }); - - const mainDate = window.DOMUtils.createElement('span', { - classes: ['enhanced-date-main'], - textContent: formattedDate - }); - - container.appendChild(mainDate); - - if (showRelative) { - const relativeDate = window.DOMUtils.createElement('span', { - classes: ['enhanced-date-relative'], - textContent: ` (${getRelativeTimeString(originalDate)})` - }); - container.appendChild(relativeDate); - - // Auto-update relative time if interval is specified - if (updateInterval && updateInterval > 0) { - setInterval(() => { - relativeDate.textContent = ` (${getRelativeTimeString(originalDate)})`; - }, updateInterval); - } - } - - if (showTooltip) { - container.title = contextualFormat(originalDate, 'long'); - } - - return container; - } catch (error) { - Logger.logError(error, { - context: 'Creating enhanced date element', - originalDate, - formattedDate - }); - return window.DOMUtils.createElement('span', { textContent: formattedDate }); - } - }; - - // Public API - return { - formatDateTime, - getRelativeTimeString, - parseGitHubDateTime, - getTimeAgo, - isToday, - isThisWeek, - contextualFormat, - createEnhancedDateElement, - DateError - }; -})(); - -// Global availability -window.DateUtils = DateUtils; \ No newline at end of file diff --git a/src/utils/dom-utils.js b/src/utils/dom-utils.js deleted file mode 100644 index 0877a50..0000000 --- a/src/utils/dom-utils.js +++ /dev/null @@ -1,359 +0,0 @@ -/** - * DOM utility functions for GitHub Enhancer - * Provides safe DOM manipulation and element waiting functionality - */ - -const DOMUtils = (() => { - const { Logger } = window; - const { ERROR_TYPES } = window.GITHUB_ENHANCER_CONSTANTS; - - /** - * Custom error for DOM operations - */ - class DOMError extends Error { - constructor(message, type = ERROR_TYPES.DOM, originalError = null) { - super(message); - this.name = 'DOMError'; - this.type = type; - this.originalError = originalError; - } - } - - /** - * Safely create DOM elements with attributes and children - */ - const createElement = (tag, options = {}) => { - try { - const element = document.createElement(tag); - - const { - attributes = {}, - styles = {}, - classes = [], - children = [], - textContent = '', - innerHTML = '', - events = {} - } = options; - - // Set attributes - Object.entries(attributes).forEach(([key, value]) => { - if (value !== null && value !== undefined) { - element.setAttribute(key, value); - } - }); - - // Set styles - Object.entries(styles).forEach(([property, value]) => { - if (value !== null && value !== undefined) { - element.style[property] = value; - } - }); - - // Add classes - if (classes.length > 0) { - element.classList.add(...classes); - } - - // Set content - if (textContent) { - element.textContent = textContent; - } else if (innerHTML) { - element.innerHTML = innerHTML; - } - - // Append children - children.forEach(child => { - if (typeof child === 'string') { - element.appendChild(document.createTextNode(child)); - } else if (child instanceof Element) { - element.appendChild(child); - } - }); - - // Add event listeners - Object.entries(events).forEach(([event, handler]) => { - element.addEventListener(event, handler); - }); - - return element; - } catch (error) { - Logger.logError(error, { context: `Creating element: ${tag}` }); - throw new DOMError(`Failed to create element: ${tag}`, ERROR_TYPES.DOM, error); - } - }; - - /** - * Wait for an element to appear in the DOM - */ - const waitForElement = (selector, options = {}) => { - const { - timeout = 5000, - rootElement = document.body, - checkInterval = 100 - } = options; - - return new Promise((resolve, reject) => { - // Check if element already exists - const existingElement = rootElement.querySelector(selector); - if (existingElement) { - resolve(existingElement); - return; - } - - let timeoutId; - let intervalId; - let observer; - - const cleanup = () => { - if (timeoutId) clearTimeout(timeoutId); - if (intervalId) clearInterval(intervalId); - if (observer) observer.disconnect(); - }; - - // Set up timeout - timeoutId = setTimeout(() => { - cleanup(); - reject(new DOMError(`Element ${selector} not found within ${timeout}ms`)); - }, timeout); - - // Try MutationObserver first (more efficient) - if (window.MutationObserver) { - observer = new MutationObserver(() => { - const element = rootElement.querySelector(selector); - if (element) { - cleanup(); - resolve(element); - } - }); - - observer.observe(rootElement, { - childList: true, - subtree: true - }); - } else { - // Fallback to interval checking - intervalId = setInterval(() => { - const element = rootElement.querySelector(selector); - if (element) { - cleanup(); - resolve(element); - } - }, checkInterval); - } - }); - }; - - /** - * Wait for multiple elements - */ - const waitForElements = (selectors, options = {}) => { - const promises = selectors.map(selector => waitForElement(selector, options)); - return Promise.all(promises); - }; - - /** - * Safely query elements with error handling - */ - const safeQuery = (selector, rootElement = document) => { - try { - return rootElement.querySelector(selector); - } catch (error) { - Logger.logError(error, { context: `Querying selector: ${selector}` }); - return null; - } - }; - - const safeQueryAll = (selector, rootElement = document) => { - try { - return Array.from(rootElement.querySelectorAll(selector)); - } catch (error) { - Logger.logError(error, { context: `Querying all selector: ${selector}` }); - return []; - } - }; - - /** - * Check if element is visible - */ - const isVisible = (element) => { - if (!element) return false; - - const style = window.getComputedStyle(element); - return style.display !== 'none' && - style.visibility !== 'hidden' && - element.offsetParent !== null; - }; - - /** - * Get element position relative to viewport - */ - const getElementPosition = (element) => { - if (!element) return null; - - const rect = element.getBoundingClientRect(); - return { - top: rect.top, - left: rect.left, - bottom: rect.bottom, - right: rect.right, - width: rect.width, - height: rect.height, - inViewport: rect.top >= 0 && rect.left >= 0 && - rect.bottom <= window.innerHeight && - rect.right <= window.innerWidth - }; - }; - - /** - * Debounced scroll handler - */ - const createScrollHandler = (callback, delay = 100) => { - let timeoutId; - - return () => { - clearTimeout(timeoutId); - timeoutId = setTimeout(callback, delay); - }; - }; - - /** - * Throttled function execution - */ - const throttle = (func, limit) => { - let inThrottle; - return function(...args) { - if (!inThrottle) { - func.apply(this, args); - inThrottle = true; - setTimeout(() => inThrottle = false, limit); - } - }; - }; - - /** - * Debounced function execution - */ - const debounce = (func, wait, immediate = false) => { - let timeout; - return function(...args) { - const later = () => { - timeout = null; - if (!immediate) func.apply(this, args); - }; - const callNow = immediate && !timeout; - clearTimeout(timeout); - timeout = setTimeout(later, wait); - if (callNow) func.apply(this, args); - }; - }; - - /** - * Insert CSS dynamically - */ - const insertCSS = (css, id = null) => { - try { - const style = createElement('style', { - attributes: id ? { id } : {}, - textContent: css - }); - - document.head.appendChild(style); - return style; - } catch (error) { - Logger.logError(error, { context: 'Inserting CSS' }); - throw new DOMError('Failed to insert CSS', ERROR_TYPES.DOM, error); - } - }; - - /** - * Remove elements matching selector - */ - const removeElements = (selector) => { - const elements = safeQueryAll(selector); - elements.forEach(element => { - try { - element.remove(); - } catch (error) { - Logger.warn(`Failed to remove element: ${error.message}`); - } - }); - return elements.length; - }; - - /** - * Animation utilities - */ - const animate = { - fadeIn(element, duration = 300) { - return new Promise(resolve => { - element.style.opacity = '0'; - element.style.transition = `opacity ${duration}ms ease-in-out`; - - // Force reflow - element.offsetHeight; - - element.style.opacity = '1'; - - setTimeout(() => { - element.style.transition = ''; - resolve(); - }, duration); - }); - }, - - fadeOut(element, duration = 300) { - return new Promise(resolve => { - element.style.transition = `opacity ${duration}ms ease-in-out`; - element.style.opacity = '0'; - - setTimeout(() => { - element.style.transition = ''; - resolve(); - }, duration); - }); - }, - - slideDown(element, duration = 300) { - return new Promise(resolve => { - const initialHeight = element.style.height; - element.style.height = '0px'; - element.style.overflow = 'hidden'; - element.style.transition = `height ${duration}ms ease-in-out`; - - // Force reflow - element.offsetHeight; - - element.style.height = element.scrollHeight + 'px'; - - setTimeout(() => { - element.style.height = initialHeight; - element.style.overflow = ''; - element.style.transition = ''; - resolve(); - }, duration); - }); - } - }; - - // Public API - return { - createElement, - waitForElement, - waitForElements, - safeQuery, - safeQueryAll, - isVisible, - getElementPosition, - createScrollHandler, - throttle, - debounce, - insertCSS, - removeElements, - animate, - DOMError - }; -})(); - -// Global availability -window.DOMUtils = DOMUtils; \ No newline at end of file diff --git a/src/utils/logger.js b/src/utils/logger.js deleted file mode 100644 index 2278180..0000000 --- a/src/utils/logger.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Ultra-simple Logger for GitHub Enhancer Chrome Extension - */ - -const Logger = (() => { - const LOG_LEVELS = { - ERROR: 0, - WARN: 1, - INFO: 2, - DEBUG: 3 - }; - - const PREFIX = '[GitHub Enhancer]'; - let currentLogLevel = LOG_LEVELS.INFO; - - const shouldLog = (level) => currentLogLevel >= level; - - const formatMessage = (level, message) => { - const levelNames = ['ERROR', 'WARN', 'INFO', 'DEBUG']; - const levelName = levelNames[level] || 'LOG'; - return `${PREFIX} [${levelName}] ${message}`; - }; - - const safeLog = (level, message) => { - if (!shouldLog(level)) return; - - const formattedMessage = formatMessage(level, message); - - try { - switch (level) { - case LOG_LEVELS.ERROR: - console.error(formattedMessage); - break; - case LOG_LEVELS.WARN: - console.warn(formattedMessage); - break; - case LOG_LEVELS.INFO: - console.info(formattedMessage); - break; - case LOG_LEVELS.DEBUG: - console.debug(formattedMessage); - break; - default: - console.log(formattedMessage); - } - } catch (e) { - // Ultimate fallback - try { - console.log(formattedMessage); - } catch (e2) { - // If even console.log fails, do nothing - } - } - }; - - const logError = (error, context = {}) => { - const errorMessage = error?.message || String(error) || 'Unknown error'; - const contextStr = context?.context || 'Unknown context'; - - safeLog(LOG_LEVELS.ERROR, `${contextStr}: ${errorMessage}`); - - // Send to background script - try { - if (chrome?.runtime?.sendMessage) { - chrome.runtime.sendMessage({ - type: 'LOG_ERROR', - payload: { - message: errorMessage, - context: contextStr, - timestamp: Date.now() - } - }).catch(() => { - // Ignore if background script is not available - }); - } - } catch (e) { - // Ignore chrome runtime errors - } - }; - - // Public API - simplified to only accept strings - return { - error: (message) => safeLog(LOG_LEVELS.ERROR, String(message)), - warn: (message) => safeLog(LOG_LEVELS.WARN, String(message)), - info: (message) => safeLog(LOG_LEVELS.INFO, String(message)), - debug: (message) => safeLog(LOG_LEVELS.DEBUG, String(message)), - - logError, - - setLogLevel(level) { - if (Object.values(LOG_LEVELS).includes(level)) { - currentLogLevel = level; - this.info(`Log level set to: ${level}`); - } - }, - - getLogLevel() { - return currentLogLevel; - }, - - LOG_LEVELS, - - // Simplified stubs - performance: { - start: () => {}, - end: () => {}, - measure: (label, fn) => fn() - }, - - group: (label, fn) => fn() - }; -})(); - -// Make available globally -window.Logger = Logger; \ No newline at end of file diff --git a/src/utils/storage.js b/src/utils/storage.js deleted file mode 100644 index 1256b33..0000000 --- a/src/utils/storage.js +++ /dev/null @@ -1,387 +0,0 @@ -/** - * Storage utility for GitHub Enhancer - * Handles Chrome extension storage operations with proper error handling - */ - -const Storage = (() => { - // Define constants locally to avoid dependency issues - const STORAGE_KEYS = { - SETTINGS: 'github_enhancer_settings', - CACHE_PREFIX: 'github_enhancer_cache_' - }; - - const DEFAULT_SETTINGS = { - enhanceContributors: true, - enhanceDateTimes: true, - enhanceFileSizes: true, - enableThemeEnhancements: true, - showCommitInfo: true, - showTeamInfo: true, - showOrgInfo: true, - cardWidth: 250, - maxCards: 10, - locale: 'en-US', - theme: 'auto', - animationsEnabled: true, - debugMode: false - }; - - const ERROR_TYPES = { - STORAGE: 'STORAGE_ERROR' - }; - - const Logger = window.Logger || { - info: console.info.bind(console), - debug: console.debug.bind(console), - warn: console.warn.bind(console), - logError: console.error.bind(console) - }; - - /** - * Custom error for storage operations - */ - class StorageError extends Error { - constructor(message, type = ERROR_TYPES.STORAGE, originalError = null) { - super(message); - this.name = 'StorageError'; - this.type = type; - this.originalError = originalError; - } - } - - /** - * Promisify Chrome storage operations with safety checks - */ - const chromeStorageGet = (keys = null) => { - return new Promise((resolve, reject) => { - try { - if (!chrome?.storage?.sync) { - reject(new StorageError('Chrome storage API not available', ERROR_TYPES.STORAGE)); - return; - } - - chrome.storage.sync.get(keys, (result) => { - if (chrome.runtime.lastError) { - reject(new StorageError( - `Failed to get storage: ${chrome.runtime.lastError.message}`, - ERROR_TYPES.STORAGE, - chrome.runtime.lastError - )); - } else { - resolve(result || {}); - } - }); - } catch (error) { - reject(new StorageError('Extension context invalidated', ERROR_TYPES.STORAGE, error)); - } - }); - }; - - const chromeStorageSet = (items) => { - return new Promise((resolve, reject) => { - try { - if (!chrome?.storage?.sync) { - reject(new StorageError('Chrome storage API not available', ERROR_TYPES.STORAGE)); - return; - } - - chrome.storage.sync.set(items, () => { - if (chrome.runtime.lastError) { - reject(new StorageError( - `Failed to set storage: ${chrome.runtime.lastError.message}`, - ERROR_TYPES.STORAGE, - chrome.runtime.lastError - )); - } else { - resolve(items); - } - }); - } catch (error) { - reject(new StorageError('Extension context invalidated', ERROR_TYPES.STORAGE, error)); - } - }); - }; - - const chromeStorageRemove = (keys) => { - return new Promise((resolve, reject) => { - chrome.storage.sync.remove(keys, () => { - if (chrome.runtime.lastError) { - reject(new StorageError( - `Failed to remove storage: ${chrome.runtime.lastError.message}`, - ERROR_TYPES.STORAGE, - chrome.runtime.lastError - )); - } else { - resolve(); - } - }); - }); - }; - - const chromeStorageClear = () => { - return new Promise((resolve, reject) => { - chrome.storage.sync.clear(() => { - if (chrome.runtime.lastError) { - reject(new StorageError( - `Failed to clear storage: ${chrome.runtime.lastError.message}`, - ERROR_TYPES.STORAGE, - chrome.runtime.lastError - )); - } else { - resolve(); - } - }); - }); - }; - - /** - * Settings management - */ - const settings = { - async load() { - try { - const result = await chromeStorageGet(STORAGE_KEYS.SETTINGS); - const savedSettings = result[STORAGE_KEYS.SETTINGS]; - - if (!savedSettings) { - Logger.info('No saved settings found, using defaults'); - return { ...DEFAULT_SETTINGS }; - } - - // Merge with defaults to ensure all keys exist - const mergedSettings = { ...DEFAULT_SETTINGS, ...savedSettings }; - Logger.debug('Settings loaded successfully:', mergedSettings); - return mergedSettings; - } catch (error) { - Logger.logError(error, { context: 'Loading settings' }); - return { ...DEFAULT_SETTINGS }; - } - }, - - async save(newSettings) { - try { - // Validate settings structure - const validatedSettings = this.validate(newSettings); - - await chromeStorageSet({ - [STORAGE_KEYS.SETTINGS]: validatedSettings - }); - - Logger.info('Settings saved successfully'); - - // Notify other parts of the extension about settings change - if (chrome.runtime) { - chrome.runtime.sendMessage({ - type: 'SETTINGS_CHANGED', - payload: validatedSettings - }).catch(() => { - // Ignore if background script is not available - }); - } - - return validatedSettings; - } catch (error) { - Logger.logError(error, { context: 'Saving settings' }); - throw error; - } - }, - - validate(settings) { - const validated = { ...DEFAULT_SETTINGS }; - - // Validate each setting - Object.keys(DEFAULT_SETTINGS).forEach(key => { - if (settings.hasOwnProperty(key)) { - const value = settings[key]; - const defaultValue = DEFAULT_SETTINGS[key]; - - // Type validation - if (typeof value === typeof defaultValue) { - validated[key] = value; - } else { - Logger.warn(`Invalid type for setting ${key}, using default`); - validated[key] = defaultValue; - } - } - }); - - return validated; - }, - - async reset() { - try { - await chromeStorageRemove(STORAGE_KEYS.SETTINGS); - Logger.info('Settings reset to defaults'); - return { ...DEFAULT_SETTINGS }; - } catch (error) { - Logger.logError(error, { context: 'Resetting settings' }); - throw error; - } - } - }; - - /** - * Generic storage operations - */ - const generic = { - async get(key, defaultValue = null) { - try { - const result = await chromeStorageGet(key); - return result[key] !== undefined ? result[key] : defaultValue; - } catch (error) { - Logger.logError(error, { context: `Getting key: ${key}` }); - return defaultValue; - } - }, - - async set(key, value) { - try { - await chromeStorageSet({ [key]: value }); - Logger.debug(`Storage set: ${key}`); - return value; - } catch (error) { - Logger.logError(error, { context: `Setting key: ${key}` }); - throw error; - } - }, - - async remove(key) { - try { - await chromeStorageRemove(key); - Logger.debug(`Storage removed: ${key}`); - } catch (error) { - Logger.logError(error, { context: `Removing key: ${key}` }); - throw error; - } - }, - - async clear() { - try { - await chromeStorageClear(); - Logger.info('Storage cleared'); - } catch (error) { - Logger.logError(error, { context: 'Clearing storage' }); - throw error; - } - } - }; - - /** - * Cache management with TTL support - */ - const cache = { - async set(key, value, ttl = 3600000) { // 1 hour default TTL - const cacheKey = `${STORAGE_KEYS.CACHE_PREFIX}${key}`; - const cacheData = { - value, - timestamp: Date.now(), - ttl - }; - - try { - await generic.set(cacheKey, cacheData); - Logger.debug(`Cache set: ${key} (TTL: ${ttl}ms)`); - } catch (error) { - Logger.logError(error, { context: `Setting cache: ${key}` }); - } - }, - - async get(key) { - const cacheKey = `${STORAGE_KEYS.CACHE_PREFIX}${key}`; - - try { - const cacheData = await generic.get(cacheKey); - - if (!cacheData) { - return null; - } - - const { value, timestamp, ttl } = cacheData; - const now = Date.now(); - - if (now - timestamp > ttl) { - // Cache expired, remove it (but don't await to avoid blocking) - this.remove(key).catch(() => { - // Ignore removal errors - }); - Logger.debug(`Cache expired: ${key}`); - return null; - } - - Logger.debug(`Cache hit: ${key}`); - return value; - } catch (error) { - // If extension context is invalidated, just return null - if (error.message && error.message.includes('Extension context invalidated')) { - Logger.debug(`Extension context invalidated, returning null for cache: ${key}`); - return null; - } - Logger.logError(error, { context: `Getting cache: ${key}` }); - return null; - } - }, - - async remove(key) { - const cacheKey = `${STORAGE_KEYS.CACHE_PREFIX}${key}`; - try { - await generic.remove(cacheKey); - Logger.debug(`Cache removed: ${key}`); - } catch (error) { - Logger.logError(error, { context: `Removing cache: ${key}` }); - } - }, - - async cleanup() { - try { - const allData = await chromeStorageGet(); - const cacheKeys = Object.keys(allData).filter(key => - key.startsWith(STORAGE_KEYS.CACHE_PREFIX) - ); - - const now = Date.now(); - const expiredKeys = []; - - for (const cacheKey of cacheKeys) { - const cacheData = allData[cacheKey]; - if (cacheData && cacheData.timestamp && cacheData.ttl) { - if (now - cacheData.timestamp > cacheData.ttl) { - expiredKeys.push(cacheKey); - } - } - } - - if (expiredKeys.length > 0) { - await chromeStorageRemove(expiredKeys); - Logger.info(`Cleaned up ${expiredKeys.length} expired cache entries`); - } - } catch (error) { - Logger.logError(error, { context: 'Cache cleanup' }); - } - } - }; - - // Public API - return { - settings, - cache, - ...generic, - StorageError, - - // Utility methods - async getStorageUsage() { - try { - return new Promise((resolve) => { - chrome.storage.sync.getBytesInUse(null, (bytesInUse) => { - resolve(bytesInUse); - }); - }); - } catch (error) { - Logger.logError(error, { context: 'Getting storage usage' }); - return 0; - } - } - }; -})(); - -// Global availability -window.Storage = Storage; \ No newline at end of file diff --git a/tests/basket.test.cjs b/tests/basket.test.cjs new file mode 100644 index 0000000..6bdb4a5 --- /dev/null +++ b/tests/basket.test.cjs @@ -0,0 +1,172 @@ +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const {JSDOM}=require('jsdom'); +const tick=()=>new Promise(resolve=>setTimeout(resolve,0)); +const source={url:'https://github.com/owner/repo/blob/main/src/app.js',path:'src/app.js',text:'const one = 1;\nconst two = 2;\nconst three = 3;',language:'javascript',lineCount:3,bytes:49,truncated:false,selection:{start:2,end:3}}; +const saved={id:'snippet-1',url:source.url,title:'Investigate parser',path:source.path,language:'javascript',lineStart:2,lineEnd:3,code:'const two = 2;\nconst three = 3;',note:'Saved note',revision:null,createdAt:1,updatedAt:1}; +function setup({items=[],page=source,fail=false,draftOptions={},beforeRequest}={}){ + const dom=new JSDOM('
',{url:'https://extension.test',runScripts:'outside-only',pretendToBeVisual:true}); + const w=dom.window;w.TextEncoder=TextEncoder; + for(const file of ['src/shared/model.js','src/shared/basket.js'])if(fs.existsSync(file))w.eval(fs.readFileSync(file,'utf8')); + assert.equal(typeof w.GHE.mountBasket,'function','basket controller must exist'); + let state={snippets:structuredClone(items),workspaces:[]};let pageData=page?{code:page}:{};const messages=[],copies=[],notices=[]; + const ui=w.GHE.mountBasket(w.document.querySelector('#basket'),{ + ...draftOptions, + getState:()=>state,getContext:()=>page?{url:page.url,type:'code'}:null,getPageData:()=>pageData, + copy:async text=>copies.push(text),notify:(...args)=>notices.push(args),onState:next=>{state=next;ui.render();}, + request:async message=>{messages.push(structuredClone(message));if(beforeRequest)await beforeRequest(message);if(fail)throw new Error('Storage is full'); + if(message.type==='SAVE_SNIPPET')state.snippets.push({...message.snippet,id:'new-snippet',createdAt:1,updatedAt:1}); + if(message.type==='UPDATE_SNIPPET')Object.assign(state.snippets.find(item=>item.id===message.id),message.patch); + if(message.type==='REMOVE_SNIPPET')state.snippets=state.snippets.filter(item=>item.id!==message.id); + if(message.type==='RESTORE_SNIPPET')state.snippets.push(message.snippet); + return structuredClone(state); + } + });ui.render(); + return{dom,w,doc:w.document,ui,messages,copies,notices,get state(){return state},setPage:next=>{pageData=next?{code:next}:{};}}; +} +function input(x,selector,value){const el=x.doc.querySelector(selector);assert.ok(el,selector);el.value=value;el.dispatchEvent(new x.w.Event('input',{bubbles:true}));return el;} + +test('Markdown keeps source code inside a longer fence and escapes title path and note HTML',()=>{ + const x=setup();const text=x.w.GHE.snippetMarkdown({...saved,title:' [title]',path:'src/\n# Heading'}); + assert.match(text,/^## <img> \\\[title\\\]/); + assert.ok(text.includes('``````javascript\n```js\nalert(1)\n```\n`````\n``````')); + assert.ok(text.includes('src/<script>\\.js')); + assert.ok(text.includes('> <script>secret</script>')); + assert.match(text,/blob\/main\/src\/app\.js#L2-L3/); + assert.match(text,/branch or tag/i);x.dom.window.close(); +}); + +test('Markdown distinguishes a commit permalink from a mutable source and rejects unsafe URLs',()=>{ + const x=setup();const revision='a'.repeat(40);const permalink={...saved,url:`https://github.com/owner/repo/blob/${revision}/src/app.js`,revision}; + assert.match(x.w.GHE.snippetMarkdown(permalink),/Commit permalink/); + assert.match(x.w.GHE.snippetMarkdown({...saved,revision}),/branch or tag/i); + assert.throws(()=>x.w.GHE.snippetMarkdown({...saved,url:'javascript:alert(1)'}),/GitHub|source/i); + const bundle=x.w.GHE.basketMarkdown([saved,permalink],''); + assert.ok(bundle.startsWith('# <Workspace>\n'));assert.equal((bundle.match(/^## /gm)||[]).length,2);x.dom.window.close(); +}); + +test('composer saves precisely the chosen rendered lines and can copy an excerpt before saving',async()=>{ + const x=setup();assert.equal(x.doc.querySelector('[data-basket-field="start"]').value,'2'); + assert.equal(x.doc.querySelector('[data-basket-preview]').textContent,'const two = 2;\nconst three = 3;'); + input(x,'[data-basket-field="title"]','Two lines');input(x,'[data-basket-field="note"]','Check allocation'); + x.doc.querySelector('[data-basket-action="copy-excerpt"]').click();await tick();assert.match(x.copies[0],/Check allocation/); + x.doc.querySelector('[data-basket-action="save-excerpt"]').click();await tick(); + const message=x.messages.find(m=>m.type==='SAVE_SNIPPET');assert.equal(message.snippet.code,'const two = 2;\nconst three = 3;');assert.equal(message.snippet.lineStart,2);assert.equal(message.snippet.lineEnd,3);assert.equal(message.snippet.note,'Check allocation');assert.equal(message.snippet.revision,null); + assert.equal(x.doc.querySelectorAll('[data-basket-snippet]').length,1);x.dom.window.close(); +}); + +test('invalid or oversized ranges cannot silently save a truncated excerpt',()=>{ + const x=setup({page:{...source,text:'x'.repeat(20001),lineCount:1,selection:{start:1,end:1}}}); + assert.equal(x.doc.querySelector('[data-basket-action="save-excerpt"]').disabled,true); + assert.match(x.doc.querySelector('[data-basket-range-status]').textContent,/20,000|20000/); + x.setPage(source);x.ui.render();input(x,'[data-basket-field="start"]','0'); + assert.equal(x.doc.querySelector('[data-basket-action="save-excerpt"]').disabled,true);assert.equal(x.messages.length,0);x.dom.window.close(); +}); + +test('a source truncated midway through a line never saves that partial line as a complete excerpt',async()=>{ + const x=setup({page:{...source,text:'complete line\npart of next line',truncated:true,lineCount:2,selection:{start:1,end:2}}}); + assert.equal(x.doc.querySelector('[data-basket-action="save-excerpt"]').disabled,true); + assert.equal(x.doc.querySelector('[data-basket-field="end"]').value,'2'); + assert.match(x.doc.querySelector('[data-basket-range-status]').textContent,/loaded|available/i); + input(x,'[data-basket-field="end"]','1'); + x.doc.querySelector('[data-basket-action="save-excerpt"]').click();await tick(); + assert.equal(x.messages[0].snippet.code,'complete line');assert.equal(x.messages[0].snippet.lineEnd,1);x.dom.window.close(); +}); + +test('editing notes survives root refresh and failed writes without announcing success',async()=>{ + const x=setup({items:[saved],fail:true});x.doc.querySelector('[data-basket-action="edit-snippet"]').click(); + input(x,'[data-basket-edit="note"]','Unsaved investigation');x.ui.render(); + assert.equal(x.doc.querySelector('[data-basket-edit="note"]').value,'Unsaved investigation'); + x.doc.querySelector('[data-basket-action="save-snippet"]').click();await tick(); + assert.equal(x.doc.querySelector('[data-basket-edit="note"]').value,'Unsaved investigation');assert.equal(x.state.snippets[0].note,'Saved note'); + assert.ok(x.notices.some(([message,error])=>error&&/Storage is full/.test(message)));x.dom.window.close(); +}); + +test('saved note updates use the snippet ID and remove offers a working undo',async()=>{ + const x=setup({items:[saved]});x.doc.querySelector('[data-basket-action="edit-snippet"]').click(); + input(x,'[data-basket-edit="note"]','Updated');x.doc.querySelector('[data-basket-action="save-snippet"]').click();await tick(); + assert.equal(x.messages[0].type,'UPDATE_SNIPPET');assert.equal(x.messages[0].id,'snippet-1');assert.equal(x.state.snippets[0].note,'Updated'); + x.doc.querySelector('[data-basket-action="remove-snippet"]').click();await tick();assert.equal(x.state.snippets.length,0); + x.doc.querySelector('[data-basket-action="undo-remove"]').click();await tick();assert.equal(x.state.snippets[0].note,'Updated');x.dom.window.close(); +}); + +test('basket export uses committed snippets and starts a Markdown download',async()=>{ + const x=setup({items:[saved],page:null});let blob,download; + x.w.URL.createObjectURL=value=>{blob=value;return'blob:export'};x.w.URL.revokeObjectURL=()=>{}; + x.doc.addEventListener('click',event=>{if(event.target.matches('a[download]')){download=event.target.download;event.preventDefault();}}); + x.doc.querySelector('[data-basket-action="copy-basket"]').click();await tick();assert.match(x.copies[0],/Investigate parser/); + x.doc.querySelector('[data-basket-action="download-basket"]').click();await tick(); + assert.ok(blob);assert.match(download,/\.md$/);const text=await new Promise(resolve=>{const reader=new x.w.FileReader();reader.onload=()=>resolve(reader.result);reader.readAsText(blob)});assert.match(text,/Saved note/); + assert.match(x.doc.querySelector('[data-basket-composer]').textContent,/Open a code file/i);x.dom.window.close(); +}); + +test('draft tracking ignores untouched editors and clears only edits actually saved',async()=>{ + const x=setup({items:[saved]});assert.equal(typeof x.ui.hasDrafts,'function');assert.equal(x.ui.hasDrafts(),false); + x.doc.querySelector('[data-basket-action="edit-snippet"]').click();assert.equal(x.ui.hasDrafts(),false); + input(x,'[data-basket-edit="note"]','Changed note');assert.equal(x.ui.hasDrafts(),true); + x.doc.querySelector('[data-basket-action="save-snippet"]').click();await tick();assert.equal(x.ui.hasDrafts(),false); + input(x,'[data-basket-field="note"]','Composer draft');assert.equal(x.ui.hasDrafts(),true); + x.doc.querySelector('[data-basket-action="save-excerpt"]').click();await tick();assert.equal(x.ui.hasDrafts(),false); + input(x,'[data-basket-field="title"]','A new label');assert.equal(x.ui.hasDrafts(),true); + x.ui.render();assert.equal(x.ui.hasDrafts(),true);x.dom.window.close(); +}); + +function draftStorage(initial=[]){ + const values=new Map(initial);const writes=[]; + return{values,writes,options:{ + loadToolDrafts:async kind=>{assert.equal(kind,'basket');return structuredClone([...values]);}, + saveToolDraft:async(kind,key,value)=>{assert.equal(kind,'basket');const snapshot=structuredClone(value);writes.push(snapshot);values.set(key,snapshot);}, + deleteToolDraft:async(kind,key,expected)=>{assert.equal(kind,'basket');if(JSON.stringify(values.get(key))===JSON.stringify(expected))values.delete(key);} + }}; +} + +test('session recovery restores composer fields and saved snippet edits without storing source code',async()=>{ + const drafts=draftStorage();const x=setup({items:[saved],draftOptions:drafts.options});await x.ui.ready; + input(x,'[data-basket-field="start"]','1');input(x,'[data-basket-field="title"]','Recovered title');input(x,'[data-basket-field="note"]','Composer thought'); + x.doc.querySelector('[data-basket-action="edit-snippet"]').click();input(x,'[data-basket-edit="note"]','Unsaved saved-excerpt note');await tick(); + assert.equal(drafts.values.size,2);assert.ok(drafts.writes.every(value=>!('code' in value)&&!('text' in value)&&!('path' in value))); + x.dom.window.close();const reopened=setup({items:[saved],draftOptions:drafts.options});await reopened.ui.ready; + assert.equal(reopened.doc.querySelector('[data-basket-field="start"]').value,'1');assert.equal(reopened.doc.querySelector('[data-basket-field="note"]').value,'Composer thought'); + assert.equal(reopened.doc.querySelector('[data-basket-edit="note"]').value,'Unsaved saved-excerpt note');assert.equal(reopened.ui.hasDrafts(),true); + reopened.doc.querySelector('[data-basket-action="cancel-edit"]').click();await tick();assert.equal(drafts.values.has('snippet:'+saved.id),false); + reopened.doc.querySelector('[data-basket-action="save-excerpt"]').click();await tick();assert.equal(drafts.values.has('composer:'+source.url),false);reopened.dom.window.close(); +}); + +test('late recovery cannot overwrite a key edited or canceled during loading',async()=>{ + let resolve;const load=new Promise(done=>resolve=done);const drafts=draftStorage(); + const x=setup({items:[saved],draftOptions:{...drafts.options,loadToolDrafts:()=>load}}); + input(x,'[data-basket-field="note"]','New local thought');x.doc.querySelector('[data-basket-action="edit-snippet"]').click();input(x,'[data-basket-edit="note"]','Then cancel'); + x.doc.querySelector('[data-basket-action="cancel-edit"]').click(); + resolve([['composer:'+source.url,{start:'2',end:'3',title:'Old',note:'Old composer'}],['snippet:'+saved.id,{title:saved.title,note:'Old snippet'}]]);await x.ui.ready; + assert.equal(x.doc.querySelector('[data-basket-field="note"]').value,'New local thought');assert.equal(x.doc.querySelector('[data-basket-edit="note"]'),null);x.dom.window.close(); +}); + +test('saving an older editor cannot clear a newer session draft from another surface',async()=>{ + const key='snippet:'+saved.id;const drafts=draftStorage();let release;const pending=new Promise(resolve=>release=resolve); + const x=setup({items:[saved],draftOptions:drafts.options,beforeRequest:message=>message.type==='UPDATE_SNIPPET'?pending:undefined});await x.ui.ready; + x.doc.querySelector('[data-basket-action="edit-snippet"]').click();input(x,'[data-basket-edit="note"]','Submitted A');await tick(); + x.doc.querySelector('[data-basket-action="save-snippet"]').click();await tick(); + drafts.values.set(key,{title:saved.title,note:'Newer B'});release();await tick(); + assert.equal(x.state.snippets[0].note,'Submitted A');assert.equal(drafts.values.get(key).note,'Newer B');x.dom.window.close(); + const reopened=setup({items:[{...saved,note:'Submitted A'}],draftOptions:drafts.options});await reopened.ui.ready; + assert.equal(reopened.doc.querySelector('[data-basket-edit="note"]').value,'Newer B');reopened.dom.window.close(); +}); + +test('draft recovery failures are visible while the basket remains usable',async()=>{ + const x=setup({draftOptions:{loadToolDrafts:async()=>{throw new Error('session unavailable')},saveToolDraft:async()=>{throw new Error('session full')}}});await x.ui.ready; + assert.ok(x.notices.some(([message,error])=>error&&/recover|recovery/i.test(message))); + input(x,'[data-basket-field="note"]','Keep local');await tick();assert.equal(x.ui.hasDrafts(),true);assert.ok(x.notices.some(([message,error])=>error&&/Save.*before closing/i.test(message))); + assert.equal(x.doc.querySelector('[data-basket-action="save-excerpt"]').disabled,false);x.dom.window.close(); +}); + +test('an unavailable GitHub selection is never silently replaced and manual valid edits can recover',async()=>{ + const x=setup({page:{...source,selection:{start:90,end:91},selectionError:'Selected lines are not fully available in the loaded snapshot. Choose lines 1 to 3.'}});assert.equal(x.doc.querySelector('[data-basket-field="start"]').value,'90');assert.equal(x.doc.querySelector('[data-basket-field="end"]').value,'91');assert.equal(x.doc.querySelector('[data-basket-action="save-excerpt"]').disabled,true);assert.match(x.doc.querySelector('[data-basket-range-status]').textContent,/loaded snapshot/);input(x,'[data-basket-field="start"]','1');input(x,'[data-basket-field="end"]','2');assert.equal(x.doc.querySelector('[data-basket-action="save-excerpt"]').disabled,false);x.doc.querySelector('[data-basket-action="copy-excerpt"]').click();await tick();assert.match(x.copies[0],/#L1-L2/);x.doc.querySelector('[data-basket-action="use-selection"]').click();assert.equal(x.doc.querySelector('[data-basket-field="end"]').value,'91');assert.equal(x.doc.querySelector('[data-basket-action="save-excerpt"]').disabled,true);assert.equal(x.messages.length,0);x.dom.window.close(); +}); +test('reveal locates a saved excerpt even when current search excludes it',()=>{ + const x=setup({items:[saved]});input(x,'[aria-label="Search code basket"]','no match');assert.equal(x.ui.reveal(saved.id),true);const card=x.doc.querySelector('[data-basket-snippet]');assert.equal(card.dataset.basketSnippet,saved.id);assert.equal(x.doc.activeElement,card);assert.equal(x.ui.reveal('missing'),false);x.dom.window.close(); +}); + +test('basket export warns about unsaved annotations and copies only committed notes',async()=>{ + const x=setup({items:[saved]});await x.ui.ready;x.doc.querySelector('[data-basket-action="edit-snippet"]').click();input(x,'[data-basket-edit="note"]','Still drafting');const cue=x.doc.querySelector('[data-basket-export-notice]');assert.equal(cue.hidden,false);assert.match(cue.textContent,/Export uses saved notes/);x.doc.querySelector('[data-basket-action="copy-basket"]').click();await tick();assert.match(x.copies[0],/Saved note/);assert.doesNotMatch(x.copies[0],/Still drafting/);assert.equal(x.messages.length,0);x.doc.querySelector('[data-basket-action="cancel-edit"]').click();assert.equal(x.doc.querySelector('[data-basket-export-notice]').hidden,true);x.dom.window.close(); +}); diff --git a/tests/client.test.cjs b/tests/client.test.cjs new file mode 100644 index 0000000..9942830 --- /dev/null +++ b/tests/client.test.cjs @@ -0,0 +1,154 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const source = fs.readFileSync(require('node:path').join(__dirname,'../src/shared/client.js'),'utf8'); + +function requestClient(sendMessage) { + const context = vm.createContext({GHE:{},chrome:{runtime:{sendMessage}}}); + vm.runInContext(source,context); + return context.GHE.request; +} + +test('missing or malformed worker replies explain how to reconnect instead of returning unusable state',async()=>{ + for(const response of [undefined,null,{},[],{ok:'true',state:{}},{ok:true},{ok:true,state:null},{ok:true,state:[]}]) { + const request=requestClient(async()=>response); + await assert.rejects(request({type:'CREATE_TEMPLATE'}),error=>{ + assert.match(error.message,/Extension did not respond/); + assert.match(error.message,/Reload GitHub Enhancer in chrome:\/\/extensions, then reload this GitHub page/); + return true; + }); + } +}); + +test('worker validation errors remain distinct from transport and missing-response failures',async()=>{ + const request=requestClient(async()=>({ok:false,error:'Template limit reached.'})); + await assert.rejects(request({type:'CREATE_TEMPLATE'}),/Template limit reached\./); + const disconnected=requestClient(async()=>{throw new Error('Runtime unavailable');}); + await assert.rejects(disconnected({type:'GET_STATE'}),/Extension connection lost\. Reload this page and try again\./); + const state={items:[],templates:[]}; + assert.equal(await requestClient(async()=>({ok:true,state}))({type:'GET_STATE'}),state); +}); + +function setup() { + const data = {}; + // Chrome shares exclusive Web Locks across extension surfaces. Keep that + // boundary explicit: Node 22 has navigator, but does not have navigator.locks. + const queues = new Map(); + const locks = { + request(name, operation) { + const result = (queues.get(name) || Promise.resolve()).then(operation); + queues.set(name, result.catch(() => {})); + return result; + } + }; + const session = { + async get(keys) { + const snapshot = keys === null ? {...data} : Object.fromEntries((Array.isArray(keys)?keys:[keys]).filter(key=>Object.hasOwn(data,key)).map(key=>[key,data[key]])); + await new Promise(resolve=>setTimeout(resolve,5)); + return snapshot; + }, + async set(values) {Object.assign(data,values);}, + async remove(key) {delete data[key];} + }; + function client() { + const context = vm.createContext({GHE:{},navigator:{locks},chrome:{storage:{session}}}); + vm.runInContext(source,context); + return context.GHE.draftOptions; + } + return [client(),client()]; +} + +test('a delayed save acknowledgement cannot delete a newer draft from another surface', async () => { + const [panel,popup] = setup(); + const url = 'https://github.com/o/r/issues/1'; + await panel.saveDraft(url,'A'); + await popup.saveDraft(url,'B'); + await panel.deleteDraft(url,'A'); + const drafts = await popup.loadDrafts(); + assert.equal(drafts.length,1); + assert.equal(drafts[0][1],'B'); + await popup.deleteDraft(url,'B'); + assert.equal((await panel.loadDrafts()).length,0); +}); + +test('checking and removing an old draft is atomic with a concurrent newer draft save', async () => { + const [panel,popup] = setup(); + const url = 'https://github.com/o/r/issues/2'; + await panel.saveDraft(url,'A'); + await Promise.all([panel.deleteDraft(url,'A'),popup.saveDraft(url,'B')]); + const drafts = await popup.loadDrafts(); + assert.equal(drafts.length,1); + assert.equal(drafts[0][1],'B'); +}); + +test('toolkit recovery is isolated from page notes and protects newer cross-surface edits',async()=>{ + const [panel,popup]=setup();const key='note:workspace1'; + await panel.saveToolDraft('workspaces',key,{note:'A'}); + await popup.saveToolDraft('workspaces',key,{note:'B'}); + await panel.deleteToolDraft('workspaces',key,{note:'A'}); + assert.equal((await panel.loadDrafts()).length,0); + assert.equal((await panel.loadToolDrafts('review')).length,0); + assert.equal((await panel.loadToolDrafts('workspaces'))[0][1].note,'B'); + await popup.deleteToolDraft('workspaces',key,{note:'B'}); + assert.equal((await panel.loadToolDrafts('workspaces')).length,0); +}); +test('toolkit recovery snapshots input before async storage and rejects oversized drafts',async()=>{ + const [panel]=setup();const draft={note:'initial'};const saved=panel.saveToolDraft('review','file',draft);draft.note='mutated';await saved; + assert.equal((await panel.loadToolDrafts('review'))[0][1].note,'initial'); + await assert.rejects(async()=>panel.saveToolDraft('review','file',{note:'x'.repeat(23000)}),/too large/); +}); + +test('composer drafts share the session boundary without leaking into page or review drafts',async()=>{ + const [panel,popup]=setup(),key='https://github.com/o/r/pull/1'; + await panel.saveToolDraft('composer',key,{body:'First draft'});await popup.saveToolDraft('composer',key,{body:'Newer draft'});await panel.deleteToolDraft('composer',key,{body:'First draft'}); + assert.equal((await popup.loadToolDrafts('composer'))[0][1].body,'Newer draft');assert.equal((await popup.loadDrafts()).length,0);assert.equal((await popup.loadToolDrafts('review')).length,0); +}); + +function recoveryClient() { + const data={},writes=[]; + const session={get:async key=>key===null?{...data}:{[key]:data[key]},remove:async key=>{delete data[key];},set:values=>new Promise((resolve,reject)=>writes.push({resolve:()=>{Object.assign(data,values);resolve();},reject}))}; + const context=vm.createContext({GHE:{},navigator:{locks:{request:(_name,fn)=>fn()}},chrome:{storage:{session}}});vm.runInContext(source,context); + return {G:context.GHE,writes,data}; +} +test('only pending or failed session writes guard navigation, never recovered drafts',async()=>{ + const {G,writes,data}=recoveryClient();data['ghe:draft:'+encodeURIComponent('https://github.com/o/r/issues/1')]='Recovered note'; + await G.draftOptions.loadDrafts();assert.equal(G.hasUnprotectedDrafts(),false); + const saved=G.draftOptions.saveDraft('https://github.com/o/r/issues/2','New note');assert.equal(G.hasUnprotectedDrafts(),true); + writes.shift().resolve();await saved;assert.equal(G.hasUnprotectedDrafts(),false); + const failed=G.draftOptions.saveToolDraft('composer','global',{body:'Unsaved draft'});writes.shift().reject(new Error('Quota exceeded'));await assert.rejects(failed,/Quota/);assert.equal(G.hasUnprotectedDrafts(),true); + const retry=G.draftOptions.saveToolDraft('composer','global',{body:'Unsaved draft'});writes.shift().resolve();await retry;assert.equal(G.hasUnprotectedDrafts(),false); +}); +test('older successful recovery cannot clear a newer pending or failed edit',async()=>{ + const {G,writes}=recoveryClient();const drafts=G.draftOptions; + const old=drafts.saveToolDraft('basket','same',{note:'old'}),newer=drafts.saveToolDraft('basket','same',{note:'new'}); + writes[0].resolve();await old;assert.equal(G.hasUnprotectedDrafts(),true); + writes[1].reject(new Error('Disk'));await assert.rejects(newer,/Disk/);assert.equal(G.hasUnprotectedDrafts(),true); + const oldAgain=drafts.saveDraft('url','old'),newAgain=drafts.saveDraft('url','new'); + writes[3].reject(new Error('New failed'));await assert.rejects(newAgain,/New failed/);writes[2].resolve();await oldAgain;assert.equal(G.hasUnprotectedDrafts(),true); +}); +test('expected deletion clears matching failed recovery but preserves newer or other-key edits',async()=>{ + const {G,writes}=recoveryClient();const d=G.draftOptions; + const failed=d.saveDraft('url','latest');writes.shift().reject(new Error('Storage'));await assert.rejects(failed); + await d.deleteDraft('url','stale');assert.equal(G.hasUnprotectedDrafts(),true); + await d.deleteDraft('url','latest');assert.equal(G.hasUnprotectedDrafts(),false); + const first=d.saveToolDraft('review','file',{note:'A'});const second=d.saveToolDraft('review','file',{note:'B'}); + await d.deleteToolDraft('review','file',{note:'A'});assert.equal(G.hasUnprotectedDrafts(),true); + writes[0].resolve();await first;writes[1].reject(new Error('Storage'));await assert.rejects(second); + await d.deleteToolDraft('review','file',{note:'B'});assert.equal(G.hasUnprotectedDrafts(),false); +}); +test('a stale recovery failure cannot reinstate a warning after the newer snapshot succeeds',async()=>{ + const {G,writes}=recoveryClient();const old=G.draftOptions.saveDraft('url','old'),latest=G.draftOptions.saveDraft('url','latest'); + writes[1].resolve();await latest;assert.equal(G.hasUnprotectedDrafts(),false); + writes[0].reject(new Error('Old failure'));await assert.rejects(old);assert.equal(G.hasUnprotectedDrafts(),false); +}); +test('oversized recovery snapshots remain protected until a valid retry succeeds',async()=>{ + const {G,writes}=recoveryClient();assert.throws(()=>G.draftOptions.saveToolDraft('composer','global',{body:'x'.repeat(23000)}),/too large/);assert.equal(G.hasUnprotectedDrafts(),true); + const retry=G.draftOptions.saveToolDraft('composer','global',{body:'shorter'});writes.shift().resolve();await retry;assert.equal(G.hasUnprotectedDrafts(),false); +}); +test('clearing one recovery key never releases another failed edit',async()=>{ + const {G,writes}=recoveryClient();const a=G.draftOptions.saveDraft('a','A'),b=G.draftOptions.saveDraft('b','B'); + writes[0].reject(new Error('A failed'));writes[1].reject(new Error('B failed'));await Promise.allSettled([a,b]); + await G.draftOptions.deleteDraft('a','A');assert.equal(G.hasUnprotectedDrafts(),true); + await G.draftOptions.deleteDraft('b','B');assert.equal(G.hasUnprotectedDrafts(),false); +}); diff --git a/tests/code-tools.test.cjs b/tests/code-tools.test.cjs new file mode 100644 index 0000000..62f8f1d --- /dev/null +++ b/tests/code-tools.test.cjs @@ -0,0 +1,15 @@ +const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const {JSDOM}=require('jsdom'); +function setup(path='/owner/repo/blob/feature/nested/src/app.js',text='first\nsecond\nthird'){ + const d=new JSDOM('

app.js

2
',{url:'https://github.com'+path,runScripts:'outside-only'});d.window.GHE={};d.window.TextEncoder=TextEncoder;d.window.document.querySelector('textarea').value=text;d.window.eval(fs.readFileSync('src/content/code-tools.js','utf8'));return d; +} +test('code adapter reads visible source and breadcrumb path without guessing slash-containing refs',()=>{const d=setup();d.window.location.hash='#L2-L3';const c=d.window.GHE.collectCode(d.window.document,{});assert.equal(c.path,'src/app.js');assert.equal(c.language,'javascript');assert.equal(c.lineCount,3);assert.equal(c.text,'first\nsecond\nthird');assert.deepEqual(JSON.parse(JSON.stringify(c.selection)),{start:2,end:3});d.window.close();}); +test('code adapter bounds large source and never claims a partial file complete',()=>{const d=setup(undefined,'a'.repeat(310000));const c=d.window.GHE.collectCode(d.window.document,{});assert.equal(c.text.length,300000);assert.equal(c.truncated,true);d.window.close();}); +test('code tools ignore non-file routes and reject out-of-range jumps',()=>{const d=setup('/owner/repo/issues/1');assert.equal(d.window.GHE.collectCode(d.window.document,{}),null);assert.equal(d.window.GHE.codeAction(d.window.document,{type:'code-jump',line:2}),false);d.window.history.replaceState({},'','/owner/repo/blob/main/a.js');assert.equal(d.window.GHE.codeAction(d.window.document,{type:'code-jump',line:-1}),false);let jumped=false;d.window.document.querySelector('[data-line-number]').scrollIntoView=()=>jumped=true;assert.equal(d.window.GHE.codeAction(d.window.document,{type:'code-jump',line:2}),true);assert.equal(jumped,true);assert.equal(d.window.location.hash,'#L2');d.window.close();}); + +test('unavailable URL and textarea selections retain their requested lines instead of substituting a loaded range',()=>{ + const full='123456789\n'.repeat(90002),d=setup(undefined,full);d.window.location.hash='#L90001-L90002';let c=d.window.GHE.collectCode(d.window.document);assert.deepEqual(JSON.parse(JSON.stringify(c.selection)),{start:90001,end:90002});assert.match(c.selectionError,/loaded/i);assert.equal(c.lineCount,30000); + d.window.location.hash='';const area=d.window.document.querySelector('textarea');area.selectionStart=900000;area.selectionEnd=900019;c=d.window.GHE.collectCode(d.window.document);assert.deepEqual(JSON.parse(JSON.stringify(c.selection)),{start:90001,end:90002});assert.match(c.selectionError,/30000|30,000/);d.window.close(); +}); +test('a selected partial final line is unavailable while fully represented lines remain usable',()=>{ + const d=setup(undefined,'first\nsecond\n'+'a'.repeat(300000));d.window.location.hash='#L3';let c=d.window.GHE.collectCode(d.window.document);assert.equal(c.selection.start,3);assert.equal(c.lineCount,2);assert.match(c.selectionError,/fully|available/i);d.window.location.hash='#L2';c=d.window.GHE.collectCode(d.window.document);assert.equal(c.selectionError,null);d.window.close(); +}); diff --git a/tests/composer.test.cjs b/tests/composer.test.cjs new file mode 100644 index 0000000..f1f41b6 --- /dev/null +++ b/tests/composer.test.cjs @@ -0,0 +1,111 @@ +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const {JSDOM}=require('jsdom'); +const tick=()=>new Promise(resolve=>setTimeout(resolve,0)); +const template={id:'template-1',title:'Release check',body:'## Check\n\n- [ ] Verify the release',createdAt:1,updatedAt:1}; +const issue='https://github.com/owner/repo/issues/12'; +function setup({templates=[],draftOptions={},beforeRequest,context=issue}={}){ + const dom=new JSDOM('
',{url:'https://extension.test',runScripts:'outside-only',pretendToBeVisual:true}),w=dom.window;w.TextEncoder=TextEncoder; + for(const file of ['src/shared/model.js','src/shared/composer.js'])if(fs.existsSync(file))w.eval(fs.readFileSync(file,'utf8')); + assert.equal(typeof w.GHE.mountComposer,'function','composer controller must exist'); + let state={templates:structuredClone(templates)},current=context?w.GHE.parseContext(context,'Example thread'):null;const messages=[],copies=[],notices=[]; + const ui=w.GHE.mountComposer(w.document.querySelector('#composer'),{ + ...draftOptions,getState:()=>state,getContext:()=>current,onState:next=>{state=next;ui.render()},notify:(...args)=>notices.push(args),copy:async text=>copies.push(text), + request:async message=>{messages.push(structuredClone(message));await beforeRequest?.(message); + if(message.type==='CREATE_TEMPLATE')state.templates.push({id:'created-template',title:message.title,body:message.body,createdAt:2,updatedAt:2}); + if(message.type==='UPDATE_TEMPLATE')Object.assign(state.templates.find(item=>item.id===message.id),message.patch); + if(message.type==='REMOVE_TEMPLATE')state.templates=state.templates.filter(item=>item.id!==message.id); + if(message.type==='RESTORE_TEMPLATE')state.templates.push(message.template); + return structuredClone(state); + } + }); + return{dom,w,doc:w.document,ui,messages,copies,notices,get state(){return state},context(url){current=url?w.GHE.parseContext(url,'Next thread'):null;ui.render();}}; +} +function change(x,label,value,event='input'){const input=x.doc.querySelector(`[aria-label="${label}"]`);assert.ok(input,label);input.value=value;input.dispatchEvent(new x.w.Event(event,{bubbles:true}));return input;} +function click(x,action){const button=x.doc.querySelector(`[data-composer-action="${action}"]`);assert.ok(button,action);button.click();} +function recovery(initial=[]){const values=new Map(initial);return{values,options:{loadToolDrafts:async kind=>{assert.equal(kind,'composer');return structuredClone([...values])},saveToolDraft:async(kind,key,value)=>{assert.equal(kind,'composer');values.set(key,structuredClone(value));},deleteToolDraft:async(kind,key,value)=>{assert.equal(kind,'composer');if(JSON.stringify(values.get(key))===JSON.stringify(value))values.delete(key);}}};} + +test('drafts use canonical thread keys and remain independent across navigation',async()=>{ + const x=setup({context:'https://github.com/Owner/Repo/pull/7/files#diff-1'});await x.ui.ready;assert.equal(x.ui.hasDrafts(),false); + change(x,'Markdown draft','PR feedback');x.context('https://github.com/owner/repo/pull/7/commits#comment');assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'PR feedback'); + assert.equal(x.doc.querySelector('[data-composer-context-link]').href,'https://github.com/owner/repo/pull/7'); + x.context(issue+'#issuecomment-2');assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'');change(x,'Markdown draft','Issue investigation'); + x.context('https://github.com/owner/repo');change(x,'Markdown draft','General thought');x.context(null);assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'General thought'); + x.context(issue);assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'Issue investigation');assert.equal(x.ui.hasDrafts(),true);x.dom.window.close(); +}); + +test('choosing a template does not touch text until the explicit replacement action',async()=>{ + const x=setup({templates:[template]});await x.ui.ready;change(x,'Markdown draft','My existing draft'); + change(x,'Choose a template','saved:template-1','change');assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'My existing draft'); + assert.match(x.doc.querySelector('[data-composer-action="use-template"]').textContent,/Replace draft with template/); + click(x,'use-template');assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,template.body);assert.equal(x.doc.activeElement.getAttribute('aria-label'),'Markdown draft'); + assert.equal(x.messages.length,0);x.dom.window.close(); +}); + +test('copy keeps a private draft and page/template strings never become HTML',async()=>{ + const payload='\n\n**My Markdown**';const x=setup({templates:[{...template,title:'',body:payload}]});await x.ui.ready; + change(x,'Choose a template','saved:template-1','change');click(x,'use-template');click(x,'copy');await tick(); + assert.equal(x.copies[0],payload);assert.equal(x.doc.querySelector('img,script'),null);assert.equal(x.doc.querySelector('[data-composer-preview]').textContent,payload); + assert.equal(x.ui.hasDrafts(),true);assert.equal(x.messages.length,0);x.dom.window.close(); +}); + +test('templates can be created, edited, removed and restored through the persistence API',async()=>{ + const x=setup();await x.ui.ready;change(x,'Markdown draft','Reusable response');change(x,'New template name','Follow-up');click(x,'create-template');await tick(); + assert.equal(x.messages[0].type,'CREATE_TEMPLATE');assert.equal(x.state.templates[0].body,'Reusable response'); + change(x,'Choose a template','saved:created-template','change');click(x,'edit-template');change(x,'Template name','Updated follow-up');change(x,'Template body','Updated reusable text');x.ui.render(); + assert.equal(x.doc.querySelector('[aria-label="Template body"]').value,'Updated reusable text');click(x,'save-template');await tick();assert.equal(x.state.templates[0].title,'Updated follow-up'); + assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'Reusable response','editing the template must not replace the current draft'); + click(x,'remove-template');await tick();assert.equal(x.state.templates.length,0);click(x,'undo-template');await tick();assert.equal(x.state.templates[0].body,'Updated reusable text');x.dom.window.close(); +}); + +test('drafts recover after remount and discard clears only the matching context snapshot',async()=>{ + const drafts=recovery();const x=setup({draftOptions:drafts.options});await x.ui.ready;change(x,'Markdown draft','Remember this');await tick(); + assert.deepEqual(drafts.values.get(issue),{body:'Remember this'});x.dom.window.close(); + const y=setup({draftOptions:drafts.options});await y.ui.ready;assert.equal(y.doc.querySelector('[aria-label="Markdown draft"]').value,'Remember this'); + drafts.values.set(issue,{body:'Newer other window'});click(y,'discard');await tick();assert.equal(y.doc.querySelector('[aria-label="Markdown draft"]').value,'');assert.equal(drafts.values.get(issue).body,'Newer other window'); + assert.equal(y.ui.hasDrafts(),false);y.dom.window.close(); +}); + +test('late recovery does not overwrite fresh edits or restore a discarded draft',async()=>{ + let resolve;const load=new Promise(done=>resolve=done);const drafts=recovery();const x=setup({draftOptions:{...drafts.options,loadToolDrafts:()=>load}}); + change(x,'Markdown draft','Typed before recovery');x.context('https://github.com/owner/repo/pull/7');change(x,'Markdown draft','Discard me');click(x,'discard'); + resolve([[issue,{body:'Old issue'}],['https://github.com/owner/repo/pull/7',{body:'Old PR'}]]);await x.ui.ready; + assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'');x.context(issue);assert.equal(x.doc.querySelector('[aria-label="Markdown draft"]').value,'Typed before recovery');x.dom.window.close(); +}); + +test('failed template saves preserve editing and draft recovery failures remain visible',async()=>{ + const x=setup({templates:[template],beforeRequest:async()=>{throw new Error('Storage is full')},draftOptions:{loadToolDrafts:async()=>{throw new Error('Session unavailable')},saveToolDraft:async()=>{throw new Error('Session unavailable')}}});await x.ui.ready; + change(x,'Choose a template','saved:template-1','change');click(x,'edit-template');change(x,'Template body','Keep this unsaved edit');click(x,'save-template');await tick(); + assert.equal(x.doc.querySelector('[aria-label="Template body"]').value,'Keep this unsaved edit');assert.equal(x.state.templates[0].body,template.body); + change(x,'Markdown draft','Keep local too');await tick();assert.ok(x.notices.some(([text,error])=>error&&/Storage is full/.test(text)));assert.ok(x.notices.some(([text,error])=>error&&/recovery/i.test(text))); + const area=x.doc.querySelector('[aria-label="Markdown draft"]');area.focus();area.setSelectionRange(2,7);x.ui.render();assert.equal(x.doc.activeElement.getAttribute('aria-label'),'Markdown draft');assert.equal(x.doc.activeElement.selectionStart,2);assert.equal(x.doc.activeElement.selectionEnd,7);x.dom.window.close(); +}); + +test('template title/body edits and creation name recover after closing the surface',async()=>{ + const drafts=recovery(),x=setup({templates:[template],draftOptions:drafts.options});await x.ui.ready; + change(x,'Choose a template','saved:template-1','change');click(x,'edit-template');change(x,'Template name','Improved release check');change(x,'Template body','Keep this revised template');change(x,'New template name','Next template');await tick();x.dom.window.close(); + const y=setup({templates:[template],draftOptions:drafts.options});await y.ui.ready;assert.equal(y.doc.querySelector('[aria-label="New template name"]').value,'Next template');change(y,'Choose a template','saved:template-1','change'); + assert.equal(y.doc.querySelector('[aria-label="Template name"]').value,'Improved release check');assert.equal(y.doc.querySelector('[aria-label="Template body"]').value,'Keep this revised template');assert.equal(y.ui.hasDrafts(),true); + click(y,'save-template');await tick();assert.equal(y.state.templates[0].body,'Keep this revised template');assert.equal(drafts.values.has('templateedit:template-1'),false);assert.deepEqual(drafts.values.get('newtemplate'),{title:'Next template'}); + change(y,'Markdown draft','New template body');click(y,'create-template');await tick();assert.equal(drafts.values.has('newtemplate'),false);y.dom.window.close(); +}); +test('late template recovery cannot overwrite current edits or canceled edits',async()=>{ + let release;const pending=new Promise(resolve=>release=resolve),drafts=recovery(),x=setup({templates:[template],draftOptions:{...drafts.options,loadToolDrafts:()=>pending}}); + change(x,'Choose a template','saved:template-1','change');click(x,'edit-template');change(x,'Template body','Current body');click(x,'cancel-template');change(x,'New template name','Current name'); + release([['templateedit:template-1',{title:'Old recovered title',body:'Old recovered body'}],['newtemplate',{title:'Old creation name'}]]);await x.ui.ready;click(x,'edit-template'); + assert.equal(x.doc.querySelector('[aria-label="Template body"]').value,template.body);assert.equal(x.doc.querySelector('[aria-label="New template name"]').value,'Current name');x.dom.window.close(); +}); +test('template commit and cancel do not clear a newer edit from another surface',async()=>{ + let release;const pending=new Promise(resolve=>release=resolve),drafts=recovery(),x=setup({templates:[template],draftOptions:drafts.options,beforeRequest:()=>pending});await x.ui.ready; + change(x,'Choose a template','saved:template-1','change');click(x,'edit-template');change(x,'Template body','Submitted text');click(x,'save-template');change(x,'Template body','Newer local edit');await tick();drafts.values.set('templateedit:template-1',{title:template.title,body:'Other surface edit'});release();await tick(); + assert.equal(x.state.templates[0].body,'Submitted text');assert.equal(x.doc.querySelector('[aria-label="Template body"]').value,'Newer local edit');assert.equal(drafts.values.get('templateedit:template-1').body,'Other surface edit');click(x,'cancel-template');await tick();assert.equal(drafts.values.get('templateedit:template-1').body,'Other surface edit');x.dom.window.close(); +}); +test('failed template commit retains recovery and ignores damaged template metadata',async()=>{ + const drafts=recovery([['newtemplate',{title:8}],['templateedit:template-1',{title:'Bad',body:99}],['templateedit:unknown',{title:'No record',body:'Orphan'}]]),x=setup({templates:[template],draftOptions:drafts.options,beforeRequest:()=>{throw Error('Storage full')}});await x.ui.ready; + assert.equal(x.doc.querySelector('[aria-label="New template name"]').value,'');change(x,'Choose a template','saved:template-1','change');click(x,'edit-template');assert.equal(x.doc.querySelector('[aria-label="Template body"]').value,template.body);change(x,'Template body','Retain until saved');click(x,'save-template');await tick();assert.equal(drafts.values.get('templateedit:template-1').body,'Retain until saved');assert.equal(x.doc.querySelector('[aria-label="Template body"]').value,'Retain until saved');x.dom.window.close(); +}); +test('template recovery waits safely for the shared state to arrive later',async()=>{ + const drafts=recovery([['templateedit:template-1',{title:'Recovered name',body:'Recovered body'}]]),x=setup({draftOptions:drafts.options});await x.ui.ready; + x.state.templates.push(structuredClone(template));x.ui.render();change(x,'Choose a template','saved:template-1','change');assert.equal(x.doc.querySelector('[aria-label="Template body"]').value,'Recovered body');assert.equal(x.doc.querySelector('[aria-label="Template name"]').value,'Recovered name');x.dom.window.close(); +}); diff --git a/tests/conversation-tools.test.cjs b/tests/conversation-tools.test.cjs new file mode 100644 index 0000000..97d5eb8 --- /dev/null +++ b/tests/conversation-tools.test.cjs @@ -0,0 +1,63 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const { JSDOM } = require('jsdom'); +// Reduced observed structures: sandbox/pull/71 and sandbox/issues/136. +const legacy = (id, body = 'Visible text') => ``; +const modern = (id, body = '

First paragraph

Second

') => `
${body}
`; +function setup(html, pathname = '/refined-github/sandbox/issues/136') { + const dom = new JSDOM(html, { url: 'https://github.com' + pathname, runScripts: 'outside-only' }); + dom.window.GHE = {}; + if (fs.existsSync('src/content/conversation-tools.js')) dom.window.eval(fs.readFileSync('src/content/conversation-tools.js', 'utf8')); + assert.equal(typeof dom.window.GHE.collectConversation, 'function'); + return { dom, document: dom.window.document, api: dom.window.GHE, context: { url: dom.window.location.href, type: pathname.includes('/pull/') ? 'pull' : pathname.includes('/discussions/') ? 'discussion' : 'issue' } }; +} +function collect(x) { return x.api.collectConversation(x.document, x.context); } + +test('modern comment header owns its sibling Markdown body with no nested duplicates', () => { + const x = setup(modern('issuecomment-4406075459') + modern('issuecomment-4406075669')); + const before = x.document.body.innerHTML, result = collect(x); + assert.equal(result.comments.length, 2); + assert.deepEqual(JSON.parse(JSON.stringify(result.comments[0])), { id: 'issuecomment-4406075459', url: 'https://github.com/refined-github/sandbox/issues/136#issuecomment-4406075459', author: 'author', body: 'First paragraph\nSecond', kind: 'comment' }); + assert.equal(result.loadedOnly, true); assert.equal(result.truncated, false); + assert.equal(x.document.body.innerHTML, before); +}); + +test('legacy PR description and review comments retain verified source anchors and text', () => { + const x = setup(legacy('issue-1734285236', '<script>literal</script>') + legacy('discussion_r123', '

Review note

'), '/refined-github/sandbox/pull/71'); + const result = collect(x); + assert.deepEqual(Array.from(result.comments, c => c.kind), ['description', 'review']); + assert.equal(result.comments[0].body, ''); + assert.equal(result.comments[1].url, 'https://github.com/refined-github/sandbox/pull/71#discussion_r123'); +}); + +test('unsupported routes, previews, hidden/extension bodies and unverified permalinks are excluded', () => { + const x = setup(`
${legacy('issuecomment-1')}
${legacy('issuecomment-3')}
${legacy('issuecomment-new')}${legacy('event-5')}${legacy('issuecomment-6').replace('href="#issuecomment-6"','href="https://evil.test/#issuecomment-6"')}${legacy('issuecomment-7', '

Read me

')}`); + assert.deepEqual(Array.from(collect(x).comments, c => c.id), ['issuecomment-7']); + assert.equal(collect(x).comments[0].body, 'Read me'); + const diff = setup(legacy('issuecomment-8'), '/refined-github/sandbox/pull/71/changes'); + assert.equal(collect(diff), null); +}); + +test('comment count, individual body and total text are bounded and flagged', () => { + const x = setup(Array.from({ length: 201 }, (_, i) => legacy(`issuecomment-${i}`, 'short')).join('')); + assert.equal(collect(x).comments.length, 200); assert.equal(collect(x).truncated, true); + const large = setup(Array.from({ length: 40 }, (_, i) => legacy(`issuecomment-${i}`, 'x'.repeat(10001))).join('')); + const result = collect(large); + assert.equal(result.comments[0].body.length, 10000); + assert.equal(result.comments.reduce((sum, c) => sum + c.body.length, 0), 300000); + assert.equal(result.truncated, true); +}); + +test('jump revalidates an exact collected native anchor and never clicks or changes location', () => { + const x = setup(modern('issuecomment-1')); + const header = x.document.getElementById('issuecomment-1'); + let scrolled = 0, clicks = 0; header.scrollIntoView = () => scrolled++; header.addEventListener('click', () => clicks++); + const url = x.document.location.href; + assert.equal(x.api.conversationAction(x.document, { type: 'conversation-jump', id: 'issuecomment-1' }), true); + assert.equal(scrolled, 1); assert.equal(clicks, 0); + assert.equal(x.document.activeElement, header); assert.equal(header.hasAttribute('tabindex'), false); + assert.equal(x.document.location.href, url); + header.closest('.react-issue-comment').remove(); + assert.equal(x.api.conversationAction(x.document, { type: 'conversation-jump', id: 'issuecomment-1' }), false); +}); diff --git a/tests/conversation.test.cjs b/tests/conversation.test.cjs new file mode 100644 index 0000000..acdf91c --- /dev/null +++ b/tests/conversation.test.cjs @@ -0,0 +1,15 @@ +const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const {JSDOM}=require('jsdom'); +function setup(){const dom=new JSDOM('
',{url:'https://extension.test',runScripts:'outside-only'}),w=dom.window;w.eval(fs.readFileSync('src/shared/model.js','utf8'));w.eval(fs.readFileSync('src/shared/conversation.js','utf8'));let state={items:[]},context=w.GHE.parseContext('https://github.com/o/r/issues/1');let data={conversation:{loadedOnly:true,truncated:false,comments:[{id:'issuecomment-1',url:context.url+'#issuecomment-1',author:'alice',body:'Race condition ',kind:'comment'},{id:'issuecomment-2',url:context.url+'#issuecomment-2',author:'bob',body:'Tests cover empty input',kind:'comment'}]}};const calls=[],notices=[];let fail=false,ui;ui=w.GHE.mountConversation(w.document.querySelector('main'),{getState:()=>state,getContext:()=>context,getPageData:()=>data,request:async m=>{calls.push(m);if(fail)throw Error('Storage full');if(m.type==='SAVE_ITEM')state.items.push(m.context);return state;},onState:s=>{state=s;ui.render();},notify:(...x)=>notices.push(x),pageAction:async m=>calls.push(m)});ui.render();return{dom,w,ui,calls,notices,setFail:()=>fail=true,setData:x=>data=x,setContext:x=>context=x};} +const tick=()=>new Promise(r=>setTimeout(r,0));function input(x,label,value,event='input'){const el=x.w.document.querySelector(`[aria-label="${label}"]`);el.value=value;el.dispatchEvent(new x.w.Event(event));} +test('conversation searches loaded text and author, combines filters, and does not interpret HTML',()=>{const x=setup(),d=x.w.document;assert.match(d.body.textContent,/2 loaded/);assert.equal(d.querySelector('img'),null);input(x,'Search loaded comments','race');assert.equal(d.querySelectorAll('.conversation-card').length,1);input(x,'Filter comment author','bob','change');assert.equal(d.querySelectorAll('.conversation-card').length,0);input(x,'Search loaded comments','');assert.equal(d.querySelectorAll('.conversation-card').length,1);assert.match(d.body.textContent,/Tests cover/);x.dom.window.close();}); +test('important comment saves a verified permalink and jump only sends the native id',async()=>{const x=setup(),d=x.w.document;d.querySelector('[data-conversation="save"]').click();await tick();assert.equal(x.calls[0].type,'SAVE_ITEM');assert.equal(x.calls[0].context.url,'https://github.com/o/r/issues/1#issuecomment-1');assert.match(x.calls[0].context.title,/alice/);d.querySelector('[aria-label="Only saved comments"]').click();assert.equal(d.querySelectorAll('.conversation-card').length,1);d.querySelector('[data-conversation="jump"]').click();await tick();assert.equal(x.calls[1].id,'issuecomment-1');assert.equal(x.calls[1].type,'conversation-jump');x.dom.window.close();}); +test('failure never shows a comment as saved and refresh retains query focus',async()=>{const x=setup(),d=x.w.document;x.setFail();d.querySelector('[data-conversation="save"]').click();await tick();assert.equal(d.querySelector('[data-conversation="save"]').disabled,false);assert.match(x.notices.at(-1)[0],/Storage full/);const q=d.querySelector('[aria-label="Search loaded comments"]');q.focus();input(x,'Search loaded comments','alice');x.ui.render();assert.equal(d.activeElement.getAttribute('aria-label'),'Search loaded comments');assert.equal(d.activeElement.value,'alice');x.dom.window.close();}); +test('empty, capped and unsupported snapshots never imply a complete thread',()=>{const x=setup(),d=x.w.document;x.setData({conversation:{comments:[],loadedOnly:true,truncated:true}});x.ui.render();assert.match(d.body.textContent,/limit/i);assert.match(d.body.textContent,/No readable comments/);x.setData({});x.ui.render();assert.equal(d.querySelector('main').textContent,'');x.dom.window.close();}); +test('late search matches appear in a safe contextual excerpt',()=>{const x=setup(),d=x.w.document;const text='Opening context '.repeat(25)+' DECISION: keep the cache. Closing context';x.setData({conversation:{loadedOnly:true,truncated:false,comments:[{id:'issuecomment-3',url:'https://github.com/o/r/issues/1#issuecomment-3',author:'alice',body:text,kind:'comment'}]}});x.ui.render();input(x,'Search loaded comments','decision');const summary=d.querySelector('summary');assert.match(summary.textContent,/DECISION: keep the cache/);assert.equal(summary.querySelector('mark').textContent,'DECISION');assert.equal(d.querySelector('img'),null);assert.match(summary.textContent,/^โ€ฆ/);x.dom.window.close();}); +test('saving preserves expansion and moves focus to a usable action even after parent detaches root',async()=>{const x=setup(),d=x.w.document;const details=d.querySelector('details');details.open=true;const save=d.querySelector('[data-conversation=save]');save.focus();save.click();const root=d.querySelector('main');root.remove();d.body.append(root);x.ui.render();await tick();assert.equal(d.querySelector('details').open,true);assert.equal(d.activeElement.dataset.conversation,'jump');assert.equal(d.activeElement.dataset.id,'issuecomment-1');assert.equal(d.activeElement.disabled,false);x.dom.window.close();}); +test('failed save keeps expansion and returns focus to retry while query changes keep open state',async()=>{const x=setup(),d=x.w.document;x.setFail();d.querySelector('details').open=true;const save=d.querySelector('[data-conversation=save]');save.focus();save.click();await tick();assert.equal(d.querySelector('details').open,true);assert.equal(d.activeElement.dataset.conversation,'save');input(x,'Search loaded comments','race');assert.equal(d.querySelector('details').open,true);x.setContext(x.w.GHE.parseContext('https://github.com/o/r/issues/2'));x.ui.render();assert.equal(d.querySelector('details').open,false);x.dom.window.close();}); +test('search refresh preserves the complete selected text range',()=>{const x=setup(),d=x.w.document;input(x,'Search loaded comments','alice');const search=d.querySelector('[aria-label="Search loaded comments"]');search.focus();search.setSelectionRange(1,4);x.ui.render();assert.equal(d.activeElement.selectionStart,1);assert.equal(d.activeElement.selectionEnd,4);x.dom.window.close();}); +test('storage refresh after a successful save preserves comment action focus',async()=>{const x=setup(),d=x.w.document;const save=d.querySelector('[data-conversation=save]');save.focus();save.click();await tick();assert.equal(d.activeElement.dataset.conversation,'jump');x.ui.render();assert.equal(d.activeElement.dataset.conversation,'jump');assert.equal(d.activeElement.dataset.id,'issuecomment-1');assert.equal(d.activeElement.disabled,false);x.dom.window.close();}); +test('refresh does not take focus from outside the conversation',async()=>{const x=setup(),d=x.w.document;const outside=d.createElement('button');d.body.append(outside);outside.focus();x.ui.render();assert.equal(d.activeElement,outside);d.querySelector('[data-conversation=jump]').click();await tick();assert.equal(d.activeElement,outside);x.dom.window.close();}); +test('results refresh retains the focused action for its comment',()=>{const x=setup(),d=x.w.document;const jump=d.querySelector('[data-conversation=jump]');jump.focus();input(x,'Search loaded comments','race');assert.equal(d.activeElement.dataset.conversation,'jump');assert.equal(d.activeElement.dataset.id,'issuecomment-1');x.dom.window.close();}); +test('jump completion does not refocus the panel after source navigation',async()=>{const x=setup(),d=x.w.document;const jump=d.querySelector('[data-conversation=jump]');jump.focus();jump.click();const outside=d.createElement('button');d.body.append(outside);outside.focus();await tick();x.ui.render();assert.equal(d.activeElement,outside);x.dom.window.close();}); diff --git a/tests/lifecycle.test.cjs b/tests/lifecycle.test.cjs new file mode 100644 index 0000000..b657c9f --- /dev/null +++ b/tests/lifecycle.test.cjs @@ -0,0 +1,76 @@ +const {test}=require('node:test');const assert=require('node:assert/strict');const {JSDOM}=require('jsdom');const fs=require('node:fs'); +const flush=()=>new Promise(r=>setTimeout(r,70)); +function setup(){ + const dom=new JSDOM('
last year
',{url:'https://github.com/owner/repo',runScripts:'outside-only',pretendToBeVisual:true});const win=dom.window; + const listeners=[];const readingCalls=[];let settings={enabled:true,exactDates:true,theme:'auto',shortcut:true}; + win.chrome={runtime:{id:'test',getURL:p=>`chrome-extension://test/${p}`,sendMessage:async()=>({ok:true,state:{settings,items:[]}}),onMessage:{addListener:()=>{}}},storage:{onChanged:{addListener:f=>listeners.push(f)}}}; + win.GHE={parseContext:(url,title)=>({url,repo:new URL(url).pathname.split('/').slice(1,3).join('/'),type:'repository',title}),createReadingEnhancer:()=>({apply:(...args)=>readingCalls.push(args),destroy:()=>{}})}; + const loadingTimers=new Map();let nextTimer=100000;const nativeTimeout=win.setTimeout.bind(win),nativeClear=win.clearTimeout.bind(win); + win.setTimeout=(fn,delay,...args)=>{if(delay===8000){const id=nextTimer++;loadingTimers.set(id,()=>fn(...args));return id;}return nativeTimeout(fn,delay,...args);}; + win.clearTimeout=id=>{loadingTimers.delete(id);nativeClear(id);}; + win.eval(fs.readFileSync('src/content/main.js','utf8'));return{dom,win,listeners,readingCalls,loadingTimers,setSettings:s=>settings={...settings,...s}}; +} +test('runtime mounts only one launcher, opens isolated panel and follows SPA context',async()=>{ + const x=setup();await flush();assert.equal(x.win.document.querySelectorAll('[data-ghe-host]').length,1); + const host=x.win.document.querySelector('[data-ghe-host]');const root=host.shadowRoot;assert.ok(root.querySelector('button')); + root.querySelector('button').click();const iframe=root.querySelector('iframe');assert.ok(iframe);assert.equal(iframe.title,'GitHub Enhancer workspace'); + assert.equal(new URL(iframe.src).searchParams.get('url'),'https://github.com/owner/repo'); + x.win.history.pushState({},'', '/owner/second');x.win.document.body.append(x.win.document.createElement('div'));await flush(); + assert.equal(x.win.document.querySelectorAll('[data-ghe-host]').length,1); + x.win.eval(fs.readFileSync('src/content/main.js','utf8'));await flush();assert.equal(x.win.document.querySelectorAll('[data-ghe-host]').length,1);x.dom.window.close(); +}); +test('disabling hides UI and re-enabling does not duplicate it',async()=>{ + const x=setup();await flush();x.setSettings({enabled:false});x.listeners[0]({},'local');await flush(); + assert.equal(x.win.document.querySelector('[data-ghe-host]').hidden,true); + x.setSettings({enabled:true});x.listeners[0]({},'local');await flush();assert.equal(x.win.document.querySelector('[data-ghe-host]').hidden,false);assert.equal(x.win.document.querySelectorAll('[data-ghe-host]').length,1);x.dom.window.close(); +}); + +test('datetime-only mutations refresh reading enhancements',async()=>{ + const x=setup();await flush();const count=x.readingCalls.length; + x.win.document.querySelector('relative-time').setAttribute('datetime','2025-02-01T00:00:00Z');await flush(); + assert.ok(x.readingCalls.length>count,'attribute changes must schedule an update');x.dom.window.close(); +}); + +test('panel stays hidden until a matching readiness reply from its extension frame',async()=>{ + const x=setup();await flush();const root=x.win.document.querySelector('[data-ghe-host]').shadowRoot;root.querySelector('button').click();const frame=root.querySelector('iframe'); + assert.equal(frame.hidden,true);assert.equal(root.querySelector('[data-ghe-panel-status]')?.dataset.state,'loading'); + // jsdom does not create browsing contexts for frames inside a shadow root. + const sent=[];Object.defineProperty(frame,'contentWindow',{value:{postMessage:message=>sent.push(message)}});frame.dispatchEvent(new x.win.Event('load')); + assert.equal(sent.length,0,'load alone does not prove the extension document is the recipient'); + x.win.dispatchEvent(new x.win.MessageEvent('message',{origin:'chrome-extension://test',source:frame.contentWindow,data:{source:'ghe-panel',type:'HELLO'}})); + const ping=sent.find(message=>message.type==='PING');assert.ok(ping?.requestId); + function ready(origin,source,requestId){x.win.dispatchEvent(new x.win.MessageEvent('message',{origin,source,data:{source:'ghe-panel',type:'READY',requestId}}));} + ready('https://github.com',frame.contentWindow,ping.requestId);assert.equal(frame.hidden,true); + ready('chrome-extension://test',x.win,ping.requestId);assert.equal(frame.hidden,true); + ready('chrome-extension://test',frame.contentWindow,'old-request');assert.equal(frame.hidden,true); + ready('chrome-extension://test',frame.contentWindow,ping.requestId);assert.equal(frame.hidden,false);assert.equal(root.querySelector('[data-ghe-panel-status]').hidden,true);assert.equal(x.loadingTimers.size,0); + root.querySelector('button').click();root.querySelector('button').click();assert.equal(frame.hidden,true,'reopening must verify the current document is ready');x.dom.window.close(); +}); + +test('host never messages initial about blank or a frame invalidated by srcdoc navigation',async()=>{ + const x=setup();await flush();const root=x.win.document.querySelector('[data-ghe-host]').shadowRoot; + const create=x.win.document.createElement.bind(x.win.document);let frame,allowed=false,sent=0; + x.win.document.createElement=(tag,...args)=>{const el=create(tag,...args);if(tag==='iframe'){frame=el;Object.defineProperty(el,'contentWindow',{value:{postMessage(){assert.equal(allowed,true,'message sent before authenticated HELLO');sent++;}}});}return el;}; + root.querySelector('button').click();assert.equal(sent,0); + x.win.history.pushState({},'', '/owner/changed');x.win.document.body.append(create('div'));await flush();assert.equal(sent,0,'context updates wait for HELLO too'); + frame.dispatchEvent(new x.win.Event('load'));assert.equal(sent,0); + allowed=true;x.win.dispatchEvent(new x.win.MessageEvent('message',{origin:'chrome-extension://test',source:frame.contentWindow,data:{source:'ghe-panel',type:'HELLO'}}));assert.equal(sent,1); + allowed=false;frame.setAttribute('srcdoc','');frame.dispatchEvent(new x.win.Event('load'));await flush(); + const before=sent;x.win.history.pushState({},'', '/owner/again');x.win.document.body.append(create('div'));await flush();assert.equal(sent,before);assert.equal(frame.getAttribute('srcdoc'),'');x.dom.window.close(); +}); + +test('blocked panel loads have a bounded error state and preserve externally set srcdoc',async()=>{ + const x=setup();await flush();const root=x.win.document.querySelector('[data-ghe-host]').shadowRoot;root.querySelector('button').click();const frame=root.querySelector('iframe');frame.setAttribute('srcdoc','');const src=frame.src; + frame.dispatchEvent(new x.win.Event('load')); + assert.equal(x.loadingTimers.size,1); + for(const run of [...x.loadingTimers.values()])run(); + const status=root.querySelector('[data-ghe-panel-status]');assert.equal(status?.dataset.state,'error');assert.match(status.textContent,/Panel could not load/);assert.match(status.textContent,/Chrome toolbar/); + assert.equal(frame.hidden,true);assert.equal(frame.getAttribute('srcdoc'),'');assert.equal(frame.src,src);x.dom.window.close(); +}); + +test('reloading the extension leaves a clear page-reload action instead of an uncaught stale-context error',async()=>{ + const x=setup();await flush();const errors=[];x.win.addEventListener('error',e=>{errors.push(e.error);e.preventDefault();}); + x.win.chrome.runtime.getURL=()=>{throw new Error('Extension context invalidated.');}; + const root=x.win.document.querySelector('[data-ghe-host]').shadowRoot;root.querySelector('button').click(); + assert.equal(errors.length,0);assert.equal(root.querySelector('[data-ghe-panel-status]').hidden,false);assert.match(root.querySelector('[data-ghe-panel-status]').textContent,/Reload this GitHub page/);assert.equal(root.querySelector('iframe'),null);x.dom.window.close(); +}); diff --git a/tests/model.test.cjs b/tests/model.test.cjs new file mode 100644 index 0000000..477abfe --- /dev/null +++ b/tests/model.test.cjs @@ -0,0 +1,176 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +if (fs.existsSync(require('node:path').join(__dirname, '../src/shared/model.js'))) require('../src/shared/model.js'); +const model = () => globalThis.GHE || {}; + +test('canonical context rejects unsafe origins and GitHub application routes', () => { + assert.equal(typeof model().parseContext, 'function'); + for (const url of ['https://example.org/a/b', 'https://github.com.evil.test/a/b', 'http://github.com/a/b', 'https://u:p@github.com/a/b', 'https://github.com/settings/profile', 'https://github.com/orgs/openai', 'https://github.com/search?q=test', 'https://github.com/a', 'https://github.com/a/b/not-a-route', 'https://github.com/a%2Fb/c']) { + assert.equal(model().parseContext(url), null, url); + } +}); + +test('canonical context keeps code refs and discussion anchors without tracking', () => { + assert.equal(typeof model().parseContext, 'function'); + assert.deepEqual(model().parseContext('https://github.com/Owner/Repo/blob/feature/ui/src/a%20b.js?ref=feature%2Fui&utm_source=x#L3-L9', 'Code'), { + url: 'https://github.com/owner/repo/blob/feature/ui/src/a%20b.js?ref=feature%2Fui#L3-L9', owner: 'owner', name: 'repo', repo: 'owner/repo', type: 'code', title: 'Code' + }); + const issue = model().parseContext('https://github.com/O/R/issues/42?utm_source=a&ref=bad#issuecomment-123', ' Fix bug ยท GitHub '); + assert.equal(issue.url, 'https://github.com/o/r/issues/42#issuecomment-123'); + assert.equal(issue.type, 'issue'); + assert.equal(issue.title, 'Fix bug ยท GitHub'); + assert.equal(model().parseContext('https://github.com/O/R/').url, 'https://github.com/o/r'); + assert.equal(model().parseContext('https://github.com/o/r/pull/2/files').type, 'pull'); + assert.equal(model().parseContext('https://github.com/o/r/discussions/3').type, 'discussion'); + assert.equal(model().parseContext('https://github.com/o/r/commit/abcdef').type, 'commit'); +}); + +test('real github organization and encoded branch names remain valid repository contexts', () => { + assert.equal(model().parseContext('https://github.com/github/linguist')?.repo, 'github/linguist'); + assert.equal(model().parseContext('https://github.com/o/r/tree/feature%2Fui')?.type, 'code'); + assert.equal(model().parseContext('https://github.com/o/r/pull/2/files/unexpected'), null); +}); + +test('pull changes commit routes retain full revisions and reject ambiguous tails', () => { + const sha='a'.repeat(40); + const url=`https://github.com/O/R/pull/42/changes/${sha}?utm_source=test#diff-file`; + assert.equal(model().parseContext(url)?.type,'pull'); + assert.equal(model().parseContext(url)?.url,`https://github.com/o/r/pull/42/changes/${sha}#diff-file`); + assert.equal(model().canonicalPrUrl(url),'https://github.com/o/r/pull/42'); + for(const tail of ['main','abcdef',`${sha}/extra`])assert.equal(model().parseContext(`https://github.com/o/r/pull/42/changes/${tail}`),null); + assert.equal(model().parseContext(`https://github.com/o/r/pull/42/checks/${sha}`),null); +}); + +test('settings reject invalid values and migrate only relevant legacy preferences', () => { + assert.equal(typeof model().normalizeSettings, 'function'); + const settings = model().normalizeSettings({ enabled: false, wide: 'yes', focus: true, theme: 'neon', locale: 'bad!!!', timeZone: 'UTC', unknown: true }, {enhanceDateTimes: false}); + assert.equal(settings.enabled, false); + assert.equal(settings.wide, false); + assert.equal(settings.focus, true); + assert.equal(settings.exactDates, false); + assert.equal(settings.theme, 'auto'); + assert.equal(settings.locale, 'auto'); + assert.equal(settings.timeZone, 'UTC'); + assert.equal(Object.hasOwn(settings, 'unknown'), false); + assert.equal(model().normalizeSettings({exactDates:true}, {enhanceDateTimes:false}).exactDates, true); +}); + +test('imports validate bounds and canonicalize metadata instead of trusting caller', () => { + assert.equal(typeof model().validateImport, 'function'); + const item = {url:'https://github.com/O/R/issues/2?utm_source=x', title:'A', note:'', createdAt:10, updatedAt:20, repo:'fake/repo', type:'repository'}; + const result = model().validateImport(JSON.stringify({version:1, items:[item], settings:{focus:true}})); + assert.equal(result.items[0].repo, 'o/r'); + assert.equal(result.items[0].type, 'issue'); + assert.equal(result.items[0].url, 'https://github.com/o/r/issues/2'); + assert.equal(result.items[0].note, ''); + assert.equal(result.settings.focus, true); + for (const bad of ['null', '{}', '{', JSON.stringify({version:99,items:[]}), JSON.stringify({items:[{...item,url:'javascript:alert(1)'}]}), JSON.stringify({items:[{...item,note:'x'.repeat(10001)}]}), JSON.stringify({items:[{...item,title:'x'.repeat(301)}]}), JSON.stringify({items:[{...item,updatedAt:-1}]}), JSON.stringify({items:Array.from({length:501},()=>item)}), ' '.repeat(32*1024*1024+1)]) { + assert.throws(() => model().validateImport(bad)); + } +}); + +test('valid workspace backups larger than 2 MB round trip without dropping bounded notes', () => { + const items = Array.from({length:210}, (_,index)=>({url:`https://github.com/o/r/issues/${index+1}`,title:`Issue ${index+1}`,note:'x'.repeat(10000),createdAt:10,updatedAt:20})); + const backup = JSON.stringify({version:1,items},null,2); + assert.ok(Buffer.byteLength(backup)>2*1024*1024); + const imported = model().validateImport(backup); + assert.equal(imported.items.length,210); + assert.equal(imported.items[209].note,items[209].note); + assert.throws(()=>model().validateImport(' '.repeat(32*1024*1024+1)), /32 MB/); +}); + +test('search includes notes and returns recent matches without mutating input', () => { + assert.equal(typeof model().filterItems, 'function'); + const items = [{title:'Old',repo:'a/b',note:'review',type:'issue',updatedAt:1}, {title:'New',repo:'a/b',note:'review',type:'pull',updatedAt:3}, {title:'Other',repo:'x/y',note:'',type:'code',updatedAt:2}]; + assert.deepEqual(model().filterItems(items, 'REVIEW').map(x=>x.title), ['New','Old']); + assert.deepEqual(model().filterItems(items, 'pull').map(x=>x.title), ['New']); + assert.equal(items[0].title, 'Old'); +}); + +test('formatting handles UTC, invalid dates and markdown metacharacters safely', () => { + assert.equal(typeof model().formatDate, 'function'); + assert.match(model().formatDate('2026-01-02T13:04:00Z', {locale:'en-US',timeZone:'UTC'}), /Jan 2, 2026/); + assert.match(model().formatDate('2026-01-02T13:04:00Z', {locale:'en-US',timeZone:'UTC'}), /13:04/); + assert.equal(model().formatDate('not a date', {}), ''); + assert.equal(model().markdownLink({title:'A [b] \\ c\nnew',url:'https://github.com/o/r'}), '[A \\[b\\] \\\\ c new](https://github.com/o/r)'); +}); + +test('copied markdown renders titles as literal text rather than embedded HTML or emphasis', () => { + assert.equal(model().markdownLink({title:' *urgent* _a_ `code`',url:'https://github.com/o/r'}), '[\\ \\*urgent\\* \\_a\\_ \\`code\\`](https://github.com/o/r)'); +}); + +const snippetFixture = () => ({id:'snippet-1',url:'https://github.com/O/R/blob/feature/ui/file.js?utm_source=x#L2-L3',repo:'ignored/repo',title:'File selection',path:'src/file.js',language:'javascript',lineStart:2,lineEnd:3,code:'const one = 1;\nconst two = 2;',note:'Why it matters',revision:null,createdAt:1,updatedAt:2}); +const reviewFixture = () => ({prUrl:'https://github.com/O/R/pull/42/changes#diff-abc',repo:'ignored/repo',files:[{path:'src/file.js',note:'Check edge case',reviewed:true,reviewedRevision:'a'.repeat(40),reviewedAt:2,updatedAt:2}],lastFile:'src/file.js',createdAt:1,updatedAt:2}); + +test('version 2 backups round trip snippets, workspace references and review provenance', () => { + assert.equal(typeof model().exportBackup,'function'); + const state = {items:[],settings:model().DEFAULT_SETTINGS,snippets:[snippetFixture()],workspaces:[{id:'workspace-1',title:'Release',note:'Next steps',itemUrls:['https://github.com/O/R/issues/3#issuecomment-2'],snippetIds:['snippet-1'],createdAt:1,updatedAt:2}],reviews:[reviewFixture()]}; + const text = model().exportBackup(state); + assert.equal(JSON.parse(text).version,2); + const imported = model().validateImport(text); + assert.equal(imported.snippets[0].repo,'o/r'); + assert.equal(imported.snippets[0].code,state.snippets[0].code); + assert.equal(imported.workspaces[0].itemUrls[0],'https://github.com/o/r/issues/3#issuecomment-2'); + assert.equal(imported.reviews[0].prUrl,'https://github.com/o/r/pull/42'); + assert.equal(imported.reviews[0].files[0].reviewedRevision,'a'.repeat(40)); + assert.equal(model().parseContext('https://github.com/o/r/pull/42/changes').type,'pull'); +}); + +test('review status never verifies a marker without a matching known revision', () => { + assert.equal(typeof model().reviewStatus,'function'); + const file=reviewFixture().files[0]; + assert.equal(model().reviewStatus(file,'a'.repeat(40)),'verified'); + assert.equal(model().reviewStatus(file,'b'.repeat(40)),'changed'); + assert.equal(model().reviewStatus(file,null),'unverified'); + assert.equal(model().reviewStatus({...file,reviewedRevision:null},'a'.repeat(40)),'unverified'); + assert.equal(model().reviewStatus({...file,reviewed:false},'a'.repeat(40)),'unreviewed'); +}); + +test('extended imports reject invalid bounds and provenance before any data is used', () => { + const snippet=snippetFixture(),review=reviewFixture(); + const badSnippets=[{...snippet,code:'x'.repeat(20001)},{...snippet,note:'x'.repeat(10001)},{...snippet,revision:'main'},{...snippet,lineEnd:1},{...snippet,language:'js\nmalicious'},{...snippet,url:'https://example.org/a/b'},{...snippet,id:'../bad'}]; + for(const value of badSnippets)assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],snippets:[value]}))); + assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],snippets:Array.from({length:101},snippetFixture)}))); + assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],reviews:[{...review,prUrl:'https://github.com/o/r/issues/42'}]}))); + assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],reviews:[{...review,files:[{...review.files[0],reviewedRevision:'bad'}]}]}))); + assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],workspaces:[{id:'w',title:'x',note:'',itemUrls:['javascript:alert(1)'],snippetIds:[],createdAt:1,updatedAt:2}]}))); +}); + +test('an optional blank snippet title uses the captured path as its saved label',()=>{ + const item=model().validateSnippet({...snippetFixture(),title:''}); + assert.equal(item.title,'src/file.js'); +}); + +test('snippet imports require a blob citation with concrete source lines',()=>{ + const base=snippetFixture(); + for(const patch of [ + {url:'https://github.com/o/r/issues/1'}, + {url:'https://github.com/o/r/tree/main/src'}, + {lineStart:null,lineEnd:null},{lineStart:0},{lineEnd:null} + ])assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],snippets:[{...base,...patch}]}))); +}); + +test('snippet provenance is derived from the cited URL and rejects inconsistent claims',()=>{ + const base=snippetFixture(),sha='a'.repeat(40),url=`https://github.com/o/r/blob/${sha}/src/file.js#L2-L3`; + assert.equal(model().validateSnippet(base).revision,null); + assert.equal(model().validateSnippet({...base,url}).revision,sha); + assert.equal(model().validateSnippet({...base,url,revision:sha.toUpperCase()}).revision,sha); + for(const input of [{...base,revision:sha},{...base,url,revision:'b'.repeat(40)}])assert.throws(()=>model().validateSnippet(input),/revision/i); +}); + +const templateFixture=(id='template-1')=>({id,title:'Ask for a test',body:'Could you add a test for this case?\n\nThanks!',createdAt:1,updatedAt:2}); +test('v2 templates round trip and old backups provide an empty optional collection',()=>{ + const state={items:[],templates:[templateFixture()],settings:model().DEFAULT_SETTINGS}; + const backup=model().validateImport(model().exportBackup(state));assert.deepEqual(backup.templates,state.templates); + for(const version of [1,2])assert.deepEqual(model().validateImport(JSON.stringify({version,items:[]})).templates,[]); + assert.equal(model().validateTemplate({...templateFixture(),title:' Clarify\n behavior ',unexpected:'ignore'}).title,'Clarify behavior'); + assert.equal(Object.hasOwn(model().validateTemplate({...templateFixture(),unexpected:true}),'unexpected'),false); +}); +test('templates reject blank content, excessive lengths, unsafe IDs and invalid timestamps',()=>{ + for(const patch of [{title:''},{title:' '.repeat(2)},{title:'\u0000'},{title:'x'.repeat(101)},{body:'\n\t '},{body:'x'.repeat(10001)},{id:'../x'},{createdAt:3,updatedAt:2}]){ + assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],templates:[{...templateFixture(),...patch}]}))); + } + assert.throws(()=>model().validateImport(JSON.stringify({version:2,items:[],templates:Array.from({length:41},(_,i)=>templateFixture('t'+i))})),/40/); + assert.equal(model().validateTemplate({...templateFixture(),body:'x'.repeat(10000)}).body.length,10000); +}); diff --git a/tests/options.test.cjs b/tests/options.test.cjs new file mode 100644 index 0000000..98fc8c4 --- /dev/null +++ b/tests/options.test.cjs @@ -0,0 +1,138 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { JSDOM } = require('jsdom'); +const base = path.join(__dirname, '../src/options'); +const tick = () => new Promise(resolve => setTimeout(resolve, 10)); + +async function setup(handler) { + const htmlPath = path.join(base, 'options.html'); + const dom = new JSDOM(fs.existsSync(htmlPath) ? fs.readFileSync(htmlPath, 'utf8') : '', { runScripts: 'outside-only', url: 'https://extension.test/options.html' }); + dom.window.eval(fs.readFileSync(path.join(__dirname, '../src/shared/model.js'), 'utf8')); + dom.window.TextEncoder = TextEncoder; + dom.window.GHE.request = handler; + const scriptPath = path.join(base, 'options.js'); + if (fs.existsSync(scriptPath)) dom.window.eval(fs.readFileSync(scriptPath, 'utf8')); + assert.equal(typeof dom.window.GHE.createOptions, 'function', 'settings controller is available'); + const controller = dom.window.GHE.createOptions(dom.window.document); + await controller.ready; + return { dom, document: dom.window.document, controller }; +} + +function state(patch = {}) { + return { settings: { enabled: true, exactDates: true, wide: false, focus: false, theme: 'auto', locale: 'auto', timeZone: 'local', shortcut: true, ...patch }, items: [] }; +} + +test('settings load committed values and save only the changed field', async () => { + let current = state({ locale: 'tr-TR', wide: true }); + const messages = []; + const { document } = await setup(async message => { + messages.push(message); + if (message.type === 'SET_SETTINGS') current = state({ ...current.settings, ...message.patch }); + return current; + }); + assert.equal(document.querySelector('[name="locale"]').value, 'tr-TR'); + assert.equal(document.querySelector('[name="wide"]').checked, true); + const enabled = document.querySelector('[name="enabled"]'); + enabled.checked = false; + enabled.dispatchEvent(new document.defaultView.Event('change', { bubbles: true })); + await tick(); + assert.deepEqual(JSON.parse(JSON.stringify(messages[1])), { type: 'SET_SETTINGS', patch: { enabled: false } }); + assert.match(document.querySelector('#save-status').textContent, /saved/i); +}); + +test('failed setting writes restore the committed value and show the error', async () => { + const { document } = await setup(async message => { + if (message.type === 'SET_SETTINGS') throw new Error('Storage is full. Export a backup and remove unused items.'); + return state({ theme: 'light' }); + }); + const theme = document.querySelector('[name="theme"]'); + theme.value = 'dark'; + theme.dispatchEvent(new document.defaultView.Event('change', { bubbles: true })); + await tick(); + assert.equal(theme.value, 'light'); + assert.equal(document.documentElement.dataset.theme, 'light'); + assert.match(document.querySelector('#save-status').textContent, /Storage is full/); + assert.equal(theme.disabled, false); +}); + +test('initial load failure leaves controls disabled and offers a working retry', async () => { + let fail = true; + const { document } = await setup(async () => { if (fail) throw new Error('Connection lost.'); return state(); }); + assert.equal(document.querySelector('[name="enabled"]').disabled, true); + assert.match(document.querySelector('#save-status').textContent, /Connection lost/); + const retry = document.querySelector('#retry-load'); + assert.equal(retry.hidden, false); + fail = false; + retry.click(); + await tick(); + assert.equal(document.querySelector('[name="enabled"]').disabled, false); + assert.equal(retry.hidden, true); +}); + +test('import sends the file contents for backend validation and reports failure without replacing settings', async () => { + let imported; + const { document, dom } = await setup(async message => { + if (message.type === 'IMPORT_ITEMS') { imported = message.text; throw new Error('This file is not valid JSON.'); } + return state({ locale: 'tr-TR' }); + }); + const input = document.querySelector('#import-file'); + Object.defineProperty(input, 'files', { configurable: true, value: [new dom.window.File(['broken'], 'backup.json', { type: 'application/json' })] }); + input.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + await tick(); + await tick(); + assert.equal(imported, 'broken'); + assert.match(document.querySelector('#backup-status').textContent, /not valid JSON/); + assert.equal(document.querySelector('[name="locale"]').value, 'tr-TR'); +}); + +test('successful import applies the committed merged state', async () => { + const { document, dom } = await setup(async message => message.type === 'IMPORT_ITEMS' ? { ...state({ locale: 'tr-TR', theme: 'dark' }), items: [{ url: 'https://github.com/a/b' }] } : state()); + const input = document.querySelector('#import-file'); + Object.defineProperty(input, 'files', { configurable: true, value: [new dom.window.File(['{"version":1,"items":[]}'], 'backup.json')] }); + input.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + await tick(); + await tick(); + assert.equal(document.querySelector('[name="locale"]').value, 'tr-TR'); + assert.equal(document.documentElement.dataset.theme, 'dark'); + assert.match(document.querySelector('#backup-status').textContent, /imported/i); + assert.match(document.querySelector('#workspace-count').textContent, /1 saved page/); +}); + +test('oversized import is rejected before reading with the current limit in its error', async () => { + let imports = 0; + const { document, dom } = await setup(async message => { if (message.type === 'IMPORT_ITEMS') imports += 1; return state(); }); + const file = new dom.window.File(['{}'], 'oversized.json'); + Object.defineProperty(file, 'size', { value: 33 * 1024 * 1024 }); + const input = document.querySelector('#import-file'); + Object.defineProperty(input, 'files', { configurable: true, value: [file] }); + input.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + await tick(); + assert.equal(imports, 0); + assert.match(document.querySelector('#backup-status').textContent, /32 MB/); + assert.equal(document.querySelector('#import-button').disabled, false); +}); + +test('export downloads the latest committed workspace including notes and settings', async () => { + let calls = 0; + const item = { url: 'https://github.com/octocat/hello-world', title: 'Hello World', note: 'Private context',createdAt:1,updatedAt:1 }; + const { document, dom } = await setup(async () => { calls += 1; return calls > 1 ? { ...state({ locale: 'tr-TR' }), items: [item] } : state(); }); + let blob; + dom.window.URL.createObjectURL = value => { blob = value; return 'blob:backup'; }; + dom.window.URL.revokeObjectURL = () => {}; + document.addEventListener('click', event => { if (event.target.matches('a[download]')) event.preventDefault(); }); + document.querySelector('#export-button').click(); + await tick(); + assert.ok(blob, 'export creates a downloadable blob'); + const text = await new Promise((resolve, reject) => { + const reader = new dom.window.FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsText(blob); + }); + const backup = JSON.parse(text); + assert.equal(backup.version, 2); + assert.deepEqual(backup.snippets, []); + assert.deepEqual(backup.workspaces, []); + assert.deepEqual(backup.reviews, []); + assert.equal(backup.items[0].note, 'Private context'); + assert.equal(backup.settings.locale, 'tr-TR'); +}); diff --git a/tests/panel.test.cjs b/tests/panel.test.cjs new file mode 100644 index 0000000..ab70f08 --- /dev/null +++ b/tests/panel.test.cjs @@ -0,0 +1,28 @@ +const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const {JSDOM}=require('jsdom'); +test('panel acknowledges only parent probes after the workspace is ready',async()=>{ + const dom=new JSDOM('
',{url:'https://extension.test/?url=https://github.com/owner/repo',runScripts:'outside-only'});const w=dom.window;const messages=[];let finish; + const ready=new Promise(r=>finish=r);w.postMessage=(message,origin)=>messages.push({message,origin}); + w.GHE={parseContext:()=>({}),draftOptions:{},mountWorkbench:()=>({ready,getState:()=>({settings:{theme:'auto'}}),setContext:()=>{},hasDrafts:()=>false})};w.chrome={storage:{onChanged:{addListener:()=>{}}}}; + w.eval(fs.readFileSync('src/panel/panel.js','utf8')); + const ping=(origin,source,id)=>w.dispatchEvent(new w.MessageEvent('message',{origin,source,data:{source:'ghe-host',type:'PING',requestId:id}})); + ping('https://evil.test',w,'bad');ping('https://github.com',null,'wrong-source');ping('https://github.com',w,'probe-1');await Promise.resolve();assert.equal(messages.length,0); + finish();await new Promise(r=>setTimeout(r,0));assert.deepEqual(JSON.parse(JSON.stringify(messages.filter(entry=>entry.message.type==='READY'))),[{message:{source:'ghe-panel',type:'READY',requestId:'probe-1'},origin:'https://github.com'}]);dom.window.close(); +}); + +test('panel announces its extension document only on a task after window load',async()=>{ + const dom=new JSDOM('
',{url:'https://extension.test/',runScripts:'outside-only'});const w=dom.window;const messages=[],pending=[]; + w.postMessage=(message,origin)=>messages.push({message,origin});w.setTimeout=fn=>pending.push(fn); + w.GHE={parseContext:()=>({}),draftOptions:{},mountWorkbench:()=>({ready:Promise.resolve(),getState:()=>({settings:{theme:'auto'}}),setContext:()=>{},hasDrafts:()=>false})};w.chrome={storage:{onChanged:{addListener:()=>{}}}}; + w.eval(fs.readFileSync('src/panel/panel.js','utf8'));assert.equal(messages.length,0);assert.equal(pending.length,0); + w.dispatchEvent(new w.Event('load'));assert.equal(messages.length,0,'HELLO must not race the containing iframe load event');assert.equal(pending.length,1);pending.shift()(); + assert.deepEqual(JSON.parse(JSON.stringify(messages)),[{message:{source:'ghe-panel',type:'HELLO'},origin:'https://github.com'}]);await new Promise(resolve=>setImmediate(resolve));dom.window.close(); +}); + +for(const surface of ['panel','popup'])test(`${surface} allows recovered drafts and guards only unprotected recovery writes`,async()=>{ + const dom=new JSDOM('
',{url:'https://extension.test/',runScripts:'outside-only'}),w=dom.window;let unsafe=false; + w.postMessage=()=>{};w.GHE={parseContext:()=>null,draftOptions:{},hasUnprotectedDrafts:()=>unsafe,mountWorkbench:()=>({ready:Promise.resolve(),getState:()=>({settings:{theme:'auto'}}),hasDrafts:()=>true})}; + w.chrome={tabs:{query:async()=>[]},storage:{onChanged:{addListener:()=>{}}}};w.eval(fs.readFileSync(`src/${surface}/${surface}.js`,'utf8'));await new Promise(r=>setImmediate(r)); + const safe=new w.Event('beforeunload',{cancelable:true});w.dispatchEvent(safe);assert.equal(safe.defaultPrevented,false,'recovered drafts must not prompt'); + unsafe=true;const pending=new w.Event('beforeunload',{cancelable:true});w.dispatchEvent(pending);assert.equal(pending.defaultPrevented,true); + unsafe=false;const written=new w.Event('beforeunload',{cancelable:true});w.dispatchEvent(written);assert.equal(written.defaultPrevented,false);dom.window.close(); +}); diff --git a/tests/reading.test.cjs b/tests/reading.test.cjs new file mode 100644 index 0000000..01e4fb5 --- /dev/null +++ b/tests/reading.test.cjs @@ -0,0 +1,213 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { JSDOM } = require('jsdom'); + +const readingPath = path.join(__dirname, '../src/content/reading.js'); +const modelPath = path.join(__dirname, '../src/shared/model.js'); +const settings = { enabled: true, exactDates: true, wide: false, focus: false, locale: 'en-US', timeZone: 'UTC' }; + +function fixture(html) { + const dom = new JSDOM(html, { url: 'https://github.com/octocat/hello-world', runScripts: 'outside-only' }); + dom.window.eval(fs.readFileSync(modelPath, 'utf8')); + if (fs.existsSync(readingPath)) dom.window.eval(fs.readFileSync(readingPath, 'utf8')); + assert.equal(typeof dom.window.GHE.createReadingEnhancer, 'function', 'reading enhancer is exposed'); + const enhancer = dom.window.GHE.createReadingEnhancer(dom.window.document); + return { dom, document: dom.window.document, enhancer }; +} + +test('exact dates preserve the native timestamp and appear only once after repeated apply', () => { + const { document, enhancer } = fixture('yesterday'); + const time = document.querySelector('relative-time'); + const original = time.outerHTML; + enhancer.apply(settings, { type: 'repository' }); + enhancer.apply(settings, { type: 'repository' }); + assert.equal(time.outerHTML, original); + assert.equal(document.querySelectorAll('[data-ghe-date]').length, 1); + assert.equal(time.nextElementSibling.hasAttribute('data-ghe-date'), true); + assert.match(time.nextElementSibling.textContent, /2026/); + assert.match(time.nextElementSibling.title, /UTC/); +}); + +test('changing datetime updates the existing exact date and invalid values remove it', () => { + const { document, enhancer } = fixture('yesterday'); + enhancer.apply(settings, { type: 'repository' }); + const time = document.querySelector('time-ago'); + const span = time.nextElementSibling; + const oldText = span.textContent; + time.setAttribute('datetime', '2027-01-02T03:00:00Z'); + enhancer.apply(settings, { type: 'repository' }); + assert.equal(time.nextElementSibling, span); + assert.notEqual(span.textContent, oldText); + assert.match(span.textContent, /2027/); + time.setAttribute('datetime', 'not-a-date'); + enhancer.apply(settings, { type: 'repository' }); + assert.equal(document.querySelector('[data-ghe-date]'), null); +}); + +test('invalid or missing dates and dates inside extension hosts are left alone', () => { + const { document, enhancer } = fixture('todaytoday
today
'); + enhancer.apply(settings, { type: 'repository' }); + assert.equal(document.querySelector('[data-ghe-date]'), null); +}); + +test('turning dates off and master disable restore the original page', () => { + const { document, enhancer } = fixture('
today
About
'); + enhancer.apply({ ...settings, wide: true, focus: true }, { type: 'repository' }); + enhancer.apply({ ...settings, exactDates: false, wide: true, focus: true }, { type: 'repository' }); + assert.equal(document.querySelector('[data-ghe-date]'), null); + enhancer.apply({ ...settings, enabled: false, wide: true, focus: true }, { type: 'repository' }); + assert.equal(document.querySelector('.ghe-wide, .ghe-focus-sidebar, style[data-ghe-reading]'), null); + assert.equal(document.querySelector('relative-time').textContent, 'today'); +}); + +test('focus affects only the repository overview sidebar and restores it on PR navigation', () => { + const { document, enhancer } = fixture('
'); + enhancer.apply({ ...settings, focus: true }, { type: 'repository' }); + assert.equal(document.querySelector('#about').classList.contains('ghe-focus-sidebar'), true); + assert.equal(document.querySelector('#unrelated').classList.contains('ghe-focus-sidebar'), false); + enhancer.apply({ ...settings, focus: true }, { type: 'pull' }); + assert.equal(document.querySelector('.ghe-focus-sidebar'), null); + enhancer.apply({ ...settings, focus: true }, { type: 'issue' }); + assert.equal(document.querySelector('.ghe-focus-sidebar'), null); +}); + +test('wide changes known repository content without widening arbitrary main elements', () => { + const { document, enhancer } = fixture('
Repo
Files
'); + enhancer.apply({ ...settings, wide: true }, { type: 'repository' }); + assert.equal(document.querySelector('#global').classList.contains('ghe-wide'), false); + assert.equal(document.querySelector('.repository-content').classList.contains('ghe-wide'), true); + assert.equal(document.querySelector('[data-testid="repos-split-pane-content"]').classList.contains('ghe-wide'), true); + enhancer.apply({ ...settings, wide: false }, { type: 'repository' }); + assert.equal(document.querySelector('.ghe-wide'), null); +}); + +test('wide releases the modern repository layout limit while retaining README width', () => { + const { document, enhancer } = fixture('
README
Unrelated
'); + enhancer.apply({ ...settings, wide: true }, { type: 'repository' }); + assert.equal(document.querySelector('#layout').classList.contains('ghe-wide'), true); + assert.equal(document.querySelector('#readme').classList.contains('ghe-wide'), false); + assert.equal(document.querySelector('#other').classList.contains('ghe-wide'), false); + assert.equal(document.defaultView.getComputedStyle(document.querySelector('#layout')).maxWidth, 'none'); + enhancer.destroy(); + assert.equal(document.querySelector('#layout').classList.contains('ghe-wide'), false); +}); + +test('focus does not hide controls on repository subpages even when their context type is repository', () => { + const { document, dom, enhancer } = fixture('
'); + dom.window.history.replaceState({}, '', '/octocat/hello-world/issues'); + const context = dom.window.GHE.parseContext(document.location.href); + assert.equal(context.type, 'repository'); + enhancer.apply({ ...settings, focus: true }, context); + assert.equal(document.querySelector('.ghe-focus-sidebar'), null); +}); + +test('wide removes both modern content caps without changing the About pane or README', () => { + const { document, enhancer } = fixture(` + +
+
+
+
+
Files
+
README
+
+
+
About
+
+
+
`); + const styleOf = id => document.defaultView.getComputedStyle(document.getElementById(id)); + const originalAttributes = document.getElementById('content').outerHTML; + enhancer.apply({ ...settings, wide: true }, { type: 'repository' }); + for (const id of ['wrapper', 'content']) { + assert.equal(document.getElementById(id).classList.contains('ghe-wide'), true); + assert.equal(styleOf(id).maxWidth, 'none'); + assert.equal(styleOf(id).width, '100%'); + } + assert.equal(styleOf('readme').maxWidth, '1012px'); + assert.equal(styleOf('about').width, '320px'); + assert.equal(styleOf('unrelated').maxWidth, '1280px'); + assert.equal(document.getElementById('about').classList.contains('ghe-wide'), false); + enhancer.apply(settings, { type: 'repository' }); + assert.equal(styleOf('wrapper').maxWidth, '1280px'); + assert.equal(styleOf('content').maxWidth, '960px'); + assert.equal(document.getElementById('content').outerHTML, originalAttributes); + enhancer.apply({ ...settings, wide: true }, { type: 'repository' }); + enhancer.destroy(); + assert.equal(document.querySelector('.ghe-wide, [data-ghe-reading]'), null); + assert.equal(styleOf('content').maxWidth, '960px'); +}); + +test('modern focus hides only the identified About pane and removes its layout gap reversibly', () => { + const { document, enhancer } = fixture('
Files

Hakkฤฑnda

File tree
'); + enhancer.apply({ ...settings, focus: true }, { type: 'repository' }); + assert.equal(document.defaultView.getComputedStyle(document.querySelector('#about')).display, 'none'); + assert.equal(document.querySelector('#filetree').classList.contains('ghe-focus-sidebar'), false); + assert.equal(document.defaultView.getComputedStyle(document.querySelector('#layout')).display, 'block'); + assert.equal(document.querySelector('#layout').classList.contains('ghe-focus-layout'), true); + enhancer.apply({ ...settings, focus: true }, { type: 'pull', url: 'https://github.com/octocat/hello-world/pull/1' }); + assert.equal(document.querySelector('.ghe-focus-sidebar, .ghe-focus-layout'), null); + enhancer.apply({ ...settings, focus: true }, { type: 'repository' }); + enhancer.destroy(); + assert.equal(document.querySelector('.ghe-focus-sidebar, .ghe-focus-layout'), null); + assert.equal(document.querySelector('#about').getAttribute('data-position'), 'end'); +}); + +test('removed timestamps lose their owned spans and newly inserted timestamps are enhanced', () => { + const { document, enhancer } = fixture('
today
'); + enhancer.apply(settings, { type: 'repository' }); + document.querySelector('relative-time').remove(); + enhancer.apply(settings, { type: 'repository' }); + assert.equal(document.querySelector('[data-ghe-date]'), null); + document.querySelector('#row').innerHTML = 'tomorrow'; + enhancer.apply(settings, { type: 'repository' }); + assert.equal(document.querySelectorAll('[data-ghe-date]').length, 1); +}); + +test('destroy removes only owned additions and can be called repeatedly before reuse', () => { + const { document, enhancer } = fixture('
today
'); + enhancer.apply({ ...settings, wide: true, focus: true }, { type: 'repository' }); + enhancer.destroy(); + enhancer.destroy(); + assert.equal(document.querySelector('[data-ghe-date], .ghe-wide, .ghe-focus-sidebar, style[data-ghe-reading]'), null); + assert.ok(document.querySelector('#native')); + assert.ok(document.querySelector('.native-class')); + enhancer.apply(settings, { type: 'repository' }); + assert.equal(document.querySelectorAll('[data-ghe-date]').length, 1); + assert.equal(document.querySelectorAll('style[data-ghe-reading]').length, 1); +}); + +test('table dates show one compact date line while preserving native time and full tooltip', () => { + const { document, enhancer } = fixture('
2 days ago
'); + const time = document.querySelector('relative-time'); + const original = time.outerHTML; + enhancer.apply(settings, { type: 'repository' }); + const span = document.querySelector('[data-ghe-date]'); + assert.equal(span.textContent, 'Jan 2, 2026'); + assert.equal(span.hasAttribute('data-ghe-compact'), true); + assert.match(span.title, /13:04.*UTC/); + assert.equal(time.outerHTML, original); + const style = document.defaultView.getComputedStyle(span); + assert.equal(style.display, 'block'); + assert.equal(style.whiteSpace, 'nowrap'); + assert.equal(style.fontSize, '11px'); +}); + +test('compact dates inherit Turkish locale and UTC date boundaries and restore full text outside tables', () => { + const { document, enhancer } = fixture('
yesterday
'); + enhancer.apply({ ...settings, locale: 'tr-TR' }, { type: 'repository' }); + const span = document.querySelector('[data-ghe-date]'); + assert.equal(span.textContent, '3 Oca 2026'); + assert.match(span.title, /02:30.*UTC/); + document.querySelector('#conversation').append(document.querySelector('time-ago')); + enhancer.apply({ ...settings, locale: 'tr-TR' }, { type: 'issue' }); + assert.equal(span.hasAttribute('data-ghe-compact'), false); + assert.match(span.textContent, /02:30.*UTC/); +}); diff --git a/tests/review-tools.test.cjs b/tests/review-tools.test.cjs new file mode 100644 index 0000000..541bb2d --- /dev/null +++ b/tests/review-tools.test.cjs @@ -0,0 +1,137 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { JSDOM } = require('jsdom'); +const source = path.join(__dirname, '../src/content/review-tools.js'); + +// Reduced fixture from live Chrome on refined-github/sandbox/pull/71/changes, +// observed 2026-09-28. The native Viewed action is an aria-pressed button. +function modern(id, file, viewed = false) { + return `

โ€Ž${file}โ€Ž

Lines changed: 2 additions & 1 deletion
Visible source
`; +} + +function setup(html, suffix = 'pull/71/changes') { + const dom = new JSDOM(html, { runScripts: 'outside-only', url: `https://github.com/refined-github/sandbox/${suffix}` }); + dom.window.GHE = {}; + if (fs.existsSync(source)) dom.window.eval(fs.readFileSync(source, 'utf8')); + assert.equal(typeof dom.window.GHE.collectReview, 'function', 'review adapter is implemented'); + assert.equal(typeof dom.window.GHE.reviewAction, 'function'); + const context = { type: suffix.startsWith('commit/') ? 'commit' : 'pull', url: dom.window.location.href }; + return { dom, document: dom.window.document, api: dom.window.GHE, context }; +} + +test('modern PR files are identified from real diff regions, classified, and read without mutations', () => { + const x = setup(modern('aaa', 'tests/parser.test.ts', true) + modern('bbb', 'docs/usage.md') + '
Not a diff
'); + const before = x.document.body.innerHTML; + const result = x.api.collectReview(x.document, x.context); + assert.equal(result.loadedOnly, true); + assert.equal(result.revision, null); + assert.equal(result.files.length, 2); + assert.deepEqual(JSON.parse(JSON.stringify(result.files[0])), { id: 'diff-aaa', path: 'tests/parser.test.ts', group: 'tests', folder: 'tests', extension: '.ts', viewed: true, viewedKnown: true, additions: 2, deletions: 1, lockfile: false, generated: false }); + assert.equal(result.files[1].group, 'docs'); + assert.equal(x.document.body.innerHTML, before); +}); + +test('legacy file headers use explicit data paths and current native checkbox state', () => { + const x = setup('
Source
', 'pull/71/files'); + let result = x.api.collectReview(x.document, x.context); + assert.equal(result.files[0].path, '.github/workflows/test.yml'); + assert.equal(result.files[0].group, 'config'); + assert.equal(result.files[0].viewed, true); + x.document.querySelector('input').checked = false; + result = x.api.collectReview(x.document, x.context); + assert.equal(result.files[0].viewed, false); +}); + +test('renamed modern files use the visible destination path without duplicate accessibility text', () => { + const x = setup(''); + const file = x.api.collectReview(x.document, x.context).files[0]; + assert.equal(file.path, 'src/new.ts'); + assert.equal(file.group, 'source'); + assert.equal(file.viewedKnown, false); +}); + +test('review collection rejects other pages, empty diff shells, and extension-owned content', () => { + const x = setup(modern('aaa', 'src/main.js'), 'pull/71'); + assert.equal(x.api.collectReview(x.document, x.context), null); + const empty = setup('
' + modern('owned', 'private.js') + '
'); + assert.equal(empty.api.collectReview(empty.document, empty.context), null); +}); + +test('only explicit commit routes identify revision and heuristic labels remain separate from source group', () => { + const sha = '3348bd65c87a77c86615c410c6a1acc138ef5c66'; + const x = setup(modern('a', 'package-lock.json') + modern('b', 'dist/bundle.min.js'), `commit/${sha}`); + const result = x.api.collectReview(x.document, x.context); + assert.equal(result.revision, sha); + assert.equal(result.files[0].lockfile, true); + assert.equal(result.files[0].group, 'config'); + assert.equal(result.files[1].generated, true); + assert.equal(result.files[1].group, 'source'); + const pr = setup(modern('a', 'main.js'), `pull/71/changes/${sha}`); + assert.equal(pr.api.collectReview(pr.document, pr.context).revision, sha); +}); + +test('loaded snapshots are bounded and clearly report truncation', () => { + const x = setup(Array.from({ length: 205 }, (_, i) => modern(String(i), `src/file${i}.js`)).join('')); + const result = x.api.collectReview(x.document, x.context); + assert.equal(result.files.length, 200); + assert.equal(result.truncated, true); + assert.equal(result.loadedOnly, true); +}); + +test('jump focuses and scrolls the actual diff without toggling Viewed or changing the page URL', () => { + const x = setup(modern('aaa', 'main.js')); + const container = x.document.getElementById('diff-aaa'); + let scrolled = 0, clicked = 0; + container.scrollIntoView = () => { scrolled += 1; }; + container.querySelector('button').addEventListener('click', () => { clicked += 1; }); + const original = x.document.location.href; + assert.equal(x.api.reviewAction(x.document, { type: 'review-jump', id: 'diff-aaa' }), true); + assert.equal(scrolled, 1); + assert.equal(x.document.activeElement, container); + assert.equal(clicked, 0); + assert.equal(container.querySelector('button').getAttribute('aria-pressed'), 'false'); + assert.equal(container.hasAttribute('tabindex'), false); + assert.equal(x.document.location.href, original); + assert.equal(x.api.reviewAction(x.document, { type: 'review-jump', id: 'diff-missing' }), false); + assert.equal(x.api.reviewAction(x.document, { type: 'submit-review', id: 'diff-aaa' }), false); +}); + +test('explicit collapse hides only observed diff tables and reset restores owned changes', () => { + const x = setup(modern('aaa', 'package-lock.json')); + const container = x.document.getElementById('diff-aaa'); + const table = container.querySelector('table'); + assert.equal(x.api.reviewAction(x.document, { type: 'review-collapse', id: container.id, collapsed: true }), true); + assert.equal(x.document.defaultView.getComputedStyle(table).display, 'none'); + assert.notEqual(x.document.defaultView.getComputedStyle(container.querySelector('[data-diff-header-wrapper]')).display, 'none'); + assert.equal(container.querySelector('button').getAttribute('aria-pressed'), 'false'); + assert.equal(x.api.collectReview(x.document, x.context).files[0].collapsed, true); + x.api.resetReviewTools(x.document); + assert.equal(table.classList.contains('ghe-review-collapsed-body'), false); + assert.equal(x.document.querySelector('[data-ghe-review-style]'), null); +}); + +test('abbreviated route hashes and arbitrary commit links never verify aggregate review revision', () => { + const short = setup(modern('a', 'main.js'), 'pull/71/changes/3348bd6'); + assert.equal(short.api.collectReview(short.document, short.context).revision, null); + const aggregate = setup(`Latest commit` + modern('a', 'main.js')); + assert.equal(aggregate.api.collectReview(aggregate.document, aggregate.context).revision, null); +}); + +test('deleted-file deferred placeholder collapses without loading its diff or hiding comments', () => { + // Captured on /refined-github/sandbox/pull/71/changes: file 5854 has no table. + const x = setup(`

5854

This file was deleted.
`); + let clicks = 0; x.document.querySelector('#placeholder button').addEventListener('click', () => clicks++); + assert.equal(x.api.reviewAction(x.document, { type: 'review-collapse', id: 'diff-deleted', collapsed: true }), true); + assert.equal(x.document.defaultView.getComputedStyle(x.document.getElementById('placeholder')).display, 'none'); + assert.notEqual(x.document.defaultView.getComputedStyle(x.document.getElementById('comment')).display, 'none'); + assert.equal(x.document.querySelector('textarea').value, 'Unsaved comment'); + assert.equal(x.document.querySelector('[aria-pressed]').getAttribute('aria-pressed'), 'false'); + assert.equal(clicks, 0); + assert.equal(x.api.collectReview(x.document, x.context).files[0].collapsed, true); + assert.equal(x.api.reviewAction(x.document, { type: 'review-collapse', id: 'diff-deleted', collapsed: false }), true); + assert.notEqual(x.document.defaultView.getComputedStyle(x.document.getElementById('placeholder')).display, 'none'); + x.document.getElementById('placeholder').setAttribute('data-diff-anchor', 'diff-other'); + assert.equal(x.api.reviewAction(x.document, { type: 'review-collapse', id: 'diff-deleted', collapsed: true }), false); +}); diff --git a/tests/review-ui.test.cjs b/tests/review-ui.test.cjs new file mode 100644 index 0000000..1608428 --- /dev/null +++ b/tests/review-ui.test.cjs @@ -0,0 +1,235 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const { JSDOM } = require('jsdom'); +const flush = () => new Promise(resolve => setTimeout(resolve, 0)); +const sha = 'a'.repeat(40); +function setup(overrides = {}) { + const dom = new JSDOM('
', { runScripts: 'outside-only' }); + dom.window.eval(fs.readFileSync('src/shared/model.js', 'utf8')); + if (fs.existsSync('src/shared/review.js')) dom.window.eval(fs.readFileSync('src/shared/review.js', 'utf8')); + assert.equal(typeof dom.window.GHE.mountReview, 'function'); + let state = { reviews: [] }, context = { type: 'pull', repo: 'owner/repo', url: 'https://github.com/owner/repo/pull/3/changes' }; + let snapshot = { review: { revision: null, loadedOnly: true, files: [ + { id: 'diff-a', path: 'src/a.js', folder: 'src', group: 'source', viewed: true }, + { id: 'diff-b', path: 'tests/a.test.js', folder: 'tests', group: 'tests', viewed: false }, + { id: 'diff-c', path: 'package-lock.json', folder: '', group: 'config', lockfile: true } + ] } }; + const calls = [], actions = [], notices = []; + let fail = false; + const root = dom.window.document.getElementById('root'); + const controller = dom.window.GHE.mountReview(root, { + getState: () => state, getContext: () => context, getPageData: () => snapshot, + request: async message => { calls.push(message); if (fail) throw new Error('Disk full'); return state; }, + onState: next => { state = next; }, notify: (...args) => notices.push(args), + pageAction: async action => { actions.push(action); return true; }, ...overrides + }); + return { dom, root, controller, calls, actions, notices, + state(value) { state = value; }, snapshot(value) { snapshot = value; }, context(value) { context = value; }, fail(value) { fail = value; } }; +} +function click(x, action) { const node = x.root.querySelector(`[data-review-action="${action}"]`); assert.ok(node, action); node.click(); } +function input(x, selector, value) { const node = x.root.querySelector(selector); node.value = value; node.dispatchEvent(new x.dom.window.Event('input', { bubbles: true })); } + +test('review shows loaded-only counts, unknown revision and local marks separate from native Viewed', () => { + const x = setup(); + assert.match(x.root.textContent, /3 loaded files/); + assert.match(x.root.textContent, /Revision not verified/); + assert.equal(x.root.querySelector('input[type=checkbox]').checked, false); + assert.match(x.root.textContent, /Native Viewed/); + assert.equal(x.calls.length, 0); +}); + +test('file path and type filtering supports focused keyboard navigation and resume', async () => { + const x = setup(); + const type = x.root.querySelector('[data-review-filter="type"]'); type.value = 'tests'; type.dispatchEvent(new x.dom.window.Event('change')); + assert.equal(x.root.querySelectorAll('[data-review-file]').length, 1); + assert.match(x.root.querySelector('[data-review-file]').textContent, /tests\/a.test.js/); + click(x, 'jump'); await flush(); + assert.equal(x.actions[0].id, 'diff-b'); + assert.equal(x.calls[0].type, 'SET_REVIEW_LAST_FILE'); + assert.equal(x.calls[0].prUrl, 'https://github.com/owner/repo/pull/3'); + x.state({ reviews: [{ prUrl: 'https://github.com/owner/repo/pull/3', lastFile: 'src/a.js', files: [] }] }); + x.controller.render(); click(x, 'resume'); await flush(); + assert.equal(x.actions.at(-1).id, 'diff-a'); +}); + +test('private note draft survives state refresh and file changes; failed save preserves it', async () => { + const x = setup(); + input(x, 'textarea', 'Unsaved private note'); + x.controller.render(); + assert.equal(x.root.querySelector('textarea').value, 'Unsaved private note'); + x.root.querySelectorAll('[data-review-file]')[1].click(); + input(x, 'textarea', 'Second note'); + x.root.querySelectorAll('[data-review-file]')[0].click(); + assert.equal(x.root.querySelector('textarea').value, 'Unsaved private note'); + x.fail(true); click(x, 'save-note'); await flush(); + assert.equal(x.root.querySelector('textarea').value, 'Unsaved private note'); + assert.match(x.notices.at(-1)[0], /Disk full/); + assert.deepEqual(JSON.parse(JSON.stringify(x.calls[0])), { type: 'UPDATE_REVIEW_FILE', prUrl: 'https://github.com/owner/repo/pull/3', path: 'src/a.js', revision: null, patch: { note: 'Unsaved private note' } }); +}); + +test('local check sends only reviewed patch and revision is never inferred from native Viewed', async () => { + const x = setup(); + x.root.querySelector('input[type=checkbox]').click(); await flush(); + assert.equal(x.calls[0].revision, null); + assert.deepEqual(JSON.parse(JSON.stringify(x.calls[0].patch)), { reviewed: true }); + assert.equal(x.actions.length, 0); + x.state({ reviews: [{ prUrl: 'https://github.com/owner/repo/pull/3', files: [{ path: 'src/a.js', reviewed: true, reviewedRevision: sha }] }] }); + x.controller.render(); + assert.match(x.root.textContent, /Needs confirmation/); + assert.doesNotMatch(x.root.textContent, /1 verified/); +}); + +test('empty or mismatched context cannot write a review and page strings remain text', () => { + const x = setup(); + x.snapshot({ review: { revision: sha, files: [{ id: 'diff-x', path: '', group: 'source' }], loadedOnly: true } }); + x.controller.render(); assert.equal(x.root.querySelector('img'), null); + x.context({ type: 'repository', url: 'https://github.com/owner/repo' }); x.controller.render(); + assert.equal(x.root.querySelector('textarea'), null); + assert.match(x.root.textContent, /Open a pull request/); +}); + +test('collapse is an explicit reversible page action, never a storage review mark', async () => { + const x = setup(); click(x, 'collapse'); await flush(); + assert.deepEqual(JSON.parse(JSON.stringify(x.actions[0])), { type: 'review-collapse', id: 'diff-a', collapsed: true }); + click(x, 'collapse'); await flush(); + assert.equal(x.actions[1].collapsed, false); + assert.equal(x.calls.length, 0); +}); + +test('changed marks can be reconfirmed directly and keyboard stays scoped to file list', async () => { + const x = setup(); + x.state({ reviews: [{ prUrl: 'https://github.com/owner/repo/pull/3', files: [{ path: 'src/a.js', reviewed: true, reviewedRevision: 'b'.repeat(40) }] }] }); + x.snapshot({ review: { revision: sha, loadedOnly: true, files: [ + { id: 'diff-a', path: 'src/a.js', group: 'source' }, { id: 'diff-b', path: 'src/b.js', group: 'source' } + ] } }); + x.controller.render(); click(x, 'confirm-mark'); await flush(); + assert.equal(x.calls[0].revision, sha); assert.equal(x.calls[0].patch.reviewed, true); + const first = x.root.querySelector('[data-review-file]'); first.focus(); + first.dispatchEvent(new x.dom.window.KeyboardEvent('keydown', { key: 'j', bubbles: true })); + assert.equal(x.dom.window.document.activeElement.dataset.reviewFile, 'src/b.js'); + const note = x.root.querySelector('textarea'); note.focus(); note.dispatchEvent(new x.dom.window.KeyboardEvent('keydown', { key: 'k', bubbles: true })); + assert.equal(x.dom.window.document.activeElement, note); +}); + +test('navigation guard detects only changed drafts and preserves drafts on other files', async () => { + const x = setup(); + assert.equal(x.controller.hasDrafts(), false); + input(x, 'textarea', 'draft'); assert.equal(x.controller.hasDrafts(), true); + input(x, 'textarea', ''); assert.equal(x.controller.hasDrafts(), false); + input(x, 'textarea', 'retained'); + x.root.querySelectorAll('[data-review-file]')[1].click(); + assert.equal(x.controller.hasDrafts(), true); + x.root.querySelectorAll('[data-review-file]')[0].click(); + click(x, 'save-note'); await flush(); assert.equal(x.controller.hasDrafts(), false); +}); + +test('batch collapse targets only loaded lock or generated files and expand restores loaded bodies', async () => { + const x = setup(); + click(x, 'collapse-generated'); await flush(); + assert.deepEqual(x.actions.map(a => a.id), ['diff-c']); + assert.equal(x.actions[0].collapsed, true); + click(x, 'expand-all'); await flush(); + assert.deepEqual(x.actions.slice(1).map(a => a.id), ['diff-a', 'diff-b', 'diff-c']); + assert.ok(x.actions.slice(1).every(a => a.collapsed === false)); + assert.equal(x.calls.length, 0); +}); + +function sessionDrafts() { + const records = new Map(); + return { records, options: { + loadToolDrafts: async kind => { assert.equal(kind, 'review'); return [...records]; }, + saveToolDraft: async (kind, key, value) => { assert.equal(kind, 'review'); records.set(key, { ...value }); }, + deleteToolDraft: async (kind, key, expected) => { assert.equal(kind, 'review'); if (records.get(key)?.note === expected.note) records.delete(key); } + } }; +} + +test('review notes recover after close and remount, and successful save clears their recovery copy', async () => { + const session = sessionDrafts(); + const first = setup(session.options); await first.controller.ready; + input(first, 'textarea', 'Recover this note'); await flush(); + assert.match(first.root.textContent, /Unsaved note/); + first.controller.destroy(); + const second = setup(session.options); await second.controller.ready; + assert.equal(second.root.querySelector('textarea').value, 'Recover this note'); + assert.equal(second.controller.hasDrafts(), true); + click(second, 'save-note'); await flush(); + assert.equal(session.records.size, 0); + assert.equal(second.controller.hasDrafts(), false); +}); + +test('delayed recovery never overwrites edits entered before loading completes', async () => { + let resolveLoad; + const x = setup({ loadToolDrafts: () => new Promise(resolve => { resolveLoad = resolve; }) }); + input(x, 'textarea', 'New local edit'); + resolveLoad([['https://github.com/owner/repo/pull/3\nsrc/a.js', { note: 'Old recovery' }]]); + await x.controller.ready; + assert.equal(x.root.querySelector('textarea').value, 'New local edit'); +}); + +test('saving an older note cannot remove a newer recovery draft entered during persistence', async () => { + const session = sessionDrafts(); let acknowledge; + const x = setup({ ...session.options, request: () => new Promise(resolve => { acknowledge = resolve; }) }); + await x.controller.ready; + input(x, 'textarea', 'Old snapshot'); await flush(); + click(x, 'save-note'); + input(x, 'textarea', 'Newer edit'); await flush(); + acknowledge({ reviews: [{ prUrl: 'https://github.com/owner/repo/pull/3', files: [{ path: 'src/a.js', note: 'Old snapshot' }] }] }); + await flush(); + assert.equal([...session.records.values()][0].note, 'Newer edit'); + assert.equal(x.root.querySelector('textarea').value, 'Newer edit'); + assert.equal(x.controller.hasDrafts(), true); +}); + +test('draft persistence errors leave the note editable and visibly unsaved', async () => { + const x = setup({ saveToolDraft: async () => { throw new Error('Session storage full'); } }); + await x.controller.ready; + input(x, 'textarea', 'Keep me'); await flush(); + assert.match(x.notices.at(-1)[0], /Session storage full/); + assert.equal(x.root.querySelector('textarea').value, 'Keep me'); + assert.match(x.root.textContent, /Unsaved note/); +}); + +test('grouped file navigation follows visible order and preserves selection across regrouping', async () => { + const x = setup(); await x.controller.ready; + x.snapshot({review:{revision:null,files:[ + {id:'diff-a',path:'src/a.js',group:'source'}, + {id:'diff-test',path:'tests/a.js',group:'tests'}, + {id:'diff-b',path:'src/b.js',group:'source'} + ]}}); x.controller.render(); + assert.deepEqual([...x.root.querySelectorAll('[data-review-file]')].map(n=>n.dataset.reviewFile), ['src/a.js','src/b.js','tests/a.js']); + const first=x.root.querySelector('[data-review-file]'); first.focus(); + first.dispatchEvent(new x.dom.window.KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true})); + assert.equal(x.dom.window.document.activeElement.dataset.reviewFile,'src/b.js'); + click(x,'next'); await flush(); assert.equal(x.actions.at(-1).id,'diff-test'); + click(x,'previous'); await flush(); assert.equal(x.actions.at(-1).id,'diff-b'); + const group=x.root.querySelector('[data-review-filter="group"]');group.value='type';group.dispatchEvent(new x.dom.window.Event('change')); + assert.equal(x.root.querySelector('[data-review-file][aria-pressed="true"]').dataset.reviewFile,'src/b.js'); + x.dom.window.close(); +}); + +test('local progress counts loaded marks independently of revision verification', async () => { + const x=setup(); await x.controller.ready; + x.state({reviews:[{prUrl:'https://github.com/owner/repo/pull/3',files:[ + {path:'src/a.js',reviewed:true,reviewedRevision:sha}, + {path:'not-loaded.js',reviewed:true,reviewedRevision:sha} + ]}]});x.controller.render(); + assert.match(x.root.querySelector('.review-summary').textContent,/1 locally marked of 3 loaded files/); + assert.match(x.root.querySelector('.review-revision').textContent,/Revision not verified/); + assert.doesNotMatch(x.root.querySelector('.review-summary').textContent,/verified/); + const search=x.root.querySelector('[data-review-focus="search"]');search.value='src';search.dispatchEvent(new x.dom.window.Event('input')); + assert.match(x.root.querySelector('.review-summary').textContent,/1 locally marked of 3 loaded files/); + x.dom.window.close(); +}); + +test('review refresh preserves the full selected search text and filter focus', async () => { + const x=setup(); await x.controller.ready; + input(x,'[data-review-focus="search"]','src'); + const search=x.root.querySelector('[data-review-focus="search"]');search.focus();search.setSelectionRange(0,2); + x.controller.render(); + assert.equal(x.dom.window.document.activeElement.dataset.reviewFocus,'search'); + assert.equal(x.dom.window.document.activeElement.selectionStart,0); + assert.equal(x.dom.window.document.activeElement.selectionEnd,2); + const filter=x.root.querySelector('[data-review-filter="type"]');filter.focus();filter.value='source';filter.dispatchEvent(new x.dom.window.Event('change')); + assert.equal(x.dom.window.document.activeElement.dataset.reviewFilter,'type');x.dom.window.close(); +}); diff --git a/tests/store.test.cjs b/tests/store.test.cjs new file mode 100644 index 0000000..9c24b2f --- /dev/null +++ b/tests/store.test.cjs @@ -0,0 +1,212 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +for (const file of ['../src/shared/model.js','../src/background/store.js']) { + const full = require('node:path').join(__dirname, file); + if (fs.existsSync(full)) require(full); +} + +// Only the external Chrome storage boundary is replaced; all mutation logic is real. +function area(initial = {}) { + let data = structuredClone(initial); + return { + fail: false, + async get(keys) { await new Promise(resolve=>setImmediate(resolve)); return keys == null ? structuredClone(data) : Object.fromEntries((Array.isArray(keys)?keys:[keys]).filter(key=>Object.hasOwn(data,key)).map(key=>[key,structuredClone(data[key])])); }, + async set(values) { if(this.fail) throw new Error('Disk full'); await new Promise(resolve=>setImmediate(resolve)); Object.assign(data, structuredClone(values)); }, + async remove(keys) { if(this.fail) throw new Error('Disk full'); for(const key of Array.isArray(keys)?keys:[keys]) delete data[key]; } + }; +} +function factory(local = area(), sync = area()) { + assert.equal(typeof globalThis.GHE?.createStore, 'function'); + return globalThis.GHE.createStore(local, sync); +} +const context = {url:'https://github.com/Owner/Repo/issues/3?utm_source=hi',title:'Fix login',repo:'untrusted/repo',type:'repository'}; + +test('state migrates relevant sync settings once and retains local settings on restart', async () => { + const local = area(); const sync = area({github_enhancer_settings:{enhanceDateTimes:false,locale:'tr-TR',enableThemeEnhancements:true}}); + const store = factory(local,sync); + const state = await store.dispatch({type:'GET_STATE'}); + assert.equal(state.settings.exactDates,false); + assert.equal(state.settings.locale,'tr-TR'); + assert.deepEqual(state.items,[]); + await store.dispatch({type:'SET_SETTINGS',patch:{exactDates:true}}); + assert.equal((await factory(local,sync).dispatch({type:'GET_STATE'})).settings.exactDates,true); +}); + +test('concurrent saves serialize without losing items or overwriting notes on duplicate save', async () => { + const local = area(); const store = factory(local); + await Promise.all([store.dispatch({type:'SAVE_ITEM',context,note:'Keep this'}), store.dispatch({type:'SAVE_ITEM',context:{url:'https://github.com/other/project',title:'Other'}})]); + let state = await store.dispatch({type:'SAVE_ITEM',context:{...context,title:'Updated title'}}); + assert.equal(state.items.length,2); + const item = state.items.find(item=>item.repo==='owner/repo'); + assert.equal(item.note,'Keep this'); assert.equal(item.type,'issue'); + state = await factory(local).dispatch({type:'GET_STATE'}); + assert.equal(state.items.length,2); +}); + +test('update refuses missing items; remove and restore preserve a record', async () => { + const store = factory(); + await assert.rejects(store.dispatch({type:'UPDATE_ITEM',url:context.url,note:'Lost'}), /not found|no longer/i); + const saved = await store.dispatch({type:'SAVE_ITEM',context,note:'Draft'}); + const item = saved.items[0]; + const removed = await store.dispatch({type:'REMOVE_ITEM',url:item.url}); + assert.equal(removed.items.length,0); + const restored = await store.dispatch({type:'RESTORE_ITEM',item}); + assert.equal(restored.items[0].note,'Draft'); + assert.equal(restored.items[0].createdAt,item.createdAt); +}); + +test('failed write never becomes committed state and does not poison mutation queue', async () => { + const local = area(); const store = factory(local); + await store.dispatch({type:'GET_STATE'}); + local.fail = true; + await assert.rejects(store.dispatch({type:'SAVE_ITEM',context,note:'Unsaved'}), /Disk full/); + local.fail = false; + assert.equal((await store.dispatch({type:'GET_STATE'})).items.length,0); + assert.equal((await store.dispatch({type:'SAVE_ITEM',context})).items.length,1); +}); + +test('import preserves newer local edits, merges settings and validates all records first', async () => { + const store = factory(); + await store.dispatch({type:'SAVE_ITEM',context,note:'Newer local note'}); + const text = JSON.stringify({version:1,items:[{...context,note:'Stale import',createdAt:1,updatedAt:2},{url:'https://github.com/fresh/repo',title:'New',note:'Imported',createdAt:1,updatedAt:2}],settings:{wide:true}}); + const result = await store.dispatch({type:'IMPORT_ITEMS',text}); + assert.equal(result.items.length,2); + assert.equal(result.items.find(item=>item.repo==='owner/repo').note,'Newer local note'); + assert.equal(result.settings.wide,true); + await assert.rejects(store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({items:[{url:'https://evil.test/a/b'}]})})); + assert.equal((await store.dispatch({type:'GET_STATE'})).items.length,2); + await assert.rejects(store.dispatch({type:'SET_SETTINGS',patch:{enabled:'false'}}), /setting/i); + await assert.rejects(store.dispatch({type:'SAVE_ITEM',context,note:'x'.repeat(10001)}), /note/i); + await assert.rejects(store.dispatch({type:'UNKNOWN'}), /message|operation/i); +}); + +test('worker rejects foreign senders and unknown messages and returns structured mutation errors', async () => { + const vm = require('node:vm'); + const path = require('node:path'); + let listener; + const runtime = {id:'our-extension',onMessage:{addListener(fn){listener=fn;}},onInstalled:{addListener(){}}}; + const sandbox = vm.createContext({URL,TextEncoder,console:{log(){},warn(){},error(){}},chrome:{runtime,storage:{local:area(),sync:area()}}}); + sandbox.importScripts = (...files) => files.forEach(file=>vm.runInContext(fs.readFileSync(path.join(__dirname,'../src/background',file),'utf8'),sandbox)); + vm.runInContext(fs.readFileSync(path.join(__dirname,'../src/background/service-worker.js'),'utf8'),sandbox); + assert.equal(listener({type:'GET_STATE'},{id:'another-extension'},()=>{}),false); + assert.equal(listener({type:'UNKNOWN'},{id:'our-extension'},()=>{}),false); + let response; + await new Promise(resolve=>{ + assert.equal(listener({type:'UPDATE_ITEM',url:context.url,note:'Missing'},{id:'our-extension'},value=>{response=value;resolve();}),true); + }); + assert.equal(response.ok,false); + assert.match(response.error,/not found/i); +}); + +const sampleSnippet = (id) => ({...(id?{id}:{}),url:'https://github.com/o/r/blob/main/src/a.js#L1-L2',title:'A.js',path:'src/a.js',language:'javascript',lineStart:1,lineEnd:2,code:'one();\ntwo();',note:'Initial',revision:null}); +const fullSnippet = id => ({...sampleSnippet(id),repo:'o/r',createdAt:1,updatedAt:2}); + +test('schema upgrade adds empty collections without losing existing saved pages or notes', async()=>{ + const oldItem={url:'https://github.com/o/r',title:'Original',note:'Keep forever',createdAt:1,updatedAt:2}; + const local=area({'ghe:schemaVersion':1,'ghe:settings':{enabled:false},['ghe:item:'+encodeURIComponent(oldItem.url)]:oldItem}); + const state=await factory(local).dispatch({type:'GET_STATE'}); + assert.deepEqual(state.snippets,[]);assert.deepEqual(state.workspaces,[]);assert.deepEqual(state.reviews,[]); + assert.equal(state.items[0].note,'Keep forever');assert.equal(state.settings.enabled,false); +}); + +test('snippet metadata patches serialize and captured source is immutable across surfaces',async()=>{ + const local=area(),store=factory(local); + let state=await store.dispatch({type:'SAVE_SNIPPET',snippet:sampleSnippet()});const id=state.snippets[0].id; + await Promise.all([store.dispatch({type:'UPDATE_SNIPPET',id,patch:{title:'Renamed'}}),store.dispatch({type:'UPDATE_SNIPPET',id,patch:{note:'Updated'}})]); + state=await factory(local).dispatch({type:'GET_STATE'}); + assert.equal(state.snippets[0].title,'Renamed');assert.equal(state.snippets[0].note,'Updated');assert.equal(state.snippets[0].code,'one();\ntwo();'); + await assert.rejects(store.dispatch({type:'UPDATE_SNIPPET',id,patch:{code:'replace source'}}),/patch|field/i); + const snippet=state.snippets[0];await store.dispatch({type:'REMOVE_SNIPPET',id}); + await assert.rejects(store.dispatch({type:'UPDATE_SNIPPET',id,patch:{note:'Missing'}}),/not found/i); + state=await store.dispatch({type:'RESTORE_SNIPPET',snippet});assert.equal(state.snippets[0].note,'Updated'); +}); + +test('workspace links and notes merge independently and deletion with undo preserves membership',async()=>{ + const store=factory();let state=await store.dispatch({type:'CREATE_WORKSPACE',title:'Release',note:'Plan'});const id=state.workspaces[0].id; + await store.dispatch({type:'SAVE_ITEM',context});state=await store.dispatch({type:'SAVE_SNIPPET',snippet:sampleSnippet()});const snippet=state.snippets[0]; + await Promise.all([store.dispatch({type:'LINK_WORKSPACE_ITEM',id,url:context.url}),store.dispatch({type:'LINK_WORKSPACE_SNIPPET',id,snippetId:snippet.id}),store.dispatch({type:'UPDATE_WORKSPACE',id,patch:{note:'Next'}})]); + state=await store.dispatch({type:'GET_STATE'});const workspace=state.workspaces[0]; + assert.deepEqual(workspace.itemUrls,['https://github.com/owner/repo/issues/3']);assert.deepEqual(workspace.snippetIds,[snippet.id]);assert.equal(workspace.note,'Next'); + await store.dispatch({type:'REMOVE_SNIPPET',id:snippet.id});state=await store.dispatch({type:'RESTORE_SNIPPET',snippet});assert.deepEqual(state.workspaces[0].snippetIds,[snippet.id]); + await store.dispatch({type:'REMOVE_WORKSPACE',id});state=await store.dispatch({type:'RESTORE_WORKSPACE',workspace});assert.equal(state.workspaces[0].note,'Next');assert.equal(state.items.length,1); + state=await store.dispatch({type:'UNLINK_WORKSPACE_ITEM',id,url:context.url});assert.deepEqual(state.workspaces[0].itemUrls,[]); + await assert.rejects(store.dispatch({type:'LINK_WORKSPACE_SNIPPET',id,snippetId:'missing'}),/not found/i); +}); + +test('review notes do not renew markers and changed or unknown revisions require reconfirmation',async()=>{ + const store=factory(),prUrl='https://github.com/O/R/pull/5/changes',revision='a'.repeat(40); + await Promise.all([store.dispatch({type:'UPDATE_REVIEW_FILE',prUrl,path:'a.js',revision,patch:{reviewed:true}}),store.dispatch({type:'UPDATE_REVIEW_FILE',prUrl,path:'b.js',revision:null,patch:{note:'Check this',reviewed:true}})]); + const before=(await store.dispatch({type:'GET_STATE'})).reviews[0].files.find(file=>file.path==='a.js'); + let state=await store.dispatch({type:'UPDATE_REVIEW_FILE',prUrl,path:'a.js',revision:'b'.repeat(40),patch:{note:'New note'}}); + let review=state.reviews[0];assert.equal(review.prUrl,'https://github.com/o/r/pull/5');assert.equal(review.files.length,2); + let file=review.files.find(file=>file.path==='a.js');assert.equal(file.reviewedRevision,revision);assert.equal(globalThis.GHE.reviewStatus(file,'b'.repeat(40)),'changed'); + assert.equal(file.reviewedAt,before.reviewedAt);assert.ok(file.updatedAt>before.updatedAt); + assert.equal(globalThis.GHE.reviewStatus(review.files.find(file=>file.path==='b.js'),revision),'unverified'); + state=await store.dispatch({type:'UPDATE_REVIEW_FILE',prUrl,path:'a.js',revision:'b'.repeat(40),patch:{reviewed:true}});file=state.reviews[0].files.find(file=>file.path==='a.js');assert.equal(globalThis.GHE.reviewStatus(file,'b'.repeat(40)),'verified'); + state=await store.dispatch({type:'SET_REVIEW_LAST_FILE',prUrl,path:'b.js'});assert.equal(state.reviews[0].lastFile,'b.js'); +}); + +test('v2 merge retains newer local records and independent review-file notes while v1 leaves extensions intact',async()=>{ + const store=factory(),prUrl='https://github.com/o/r/pull/5'; + await store.dispatch({type:'SAVE_SNIPPET',snippet:sampleSnippet('snippet-a')}); + await store.dispatch({type:'UPDATE_REVIEW_FILE',prUrl,path:'local.js',revision:null,patch:{note:'Local'}}); + const review={prUrl,files:[{path:'imported.js',note:'Imported',reviewed:false,reviewedRevision:null,reviewedAt:null,updatedAt:2}],lastFile:'imported.js',createdAt:1,updatedAt:2}; + let state=await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],snippets:[{...fullSnippet('snippet-a'),note:'Stale'}],reviews:[review]})}); + assert.equal(state.snippets[0].note,'Initial');assert.deepEqual(state.reviews[0].files.map(file=>file.path).sort(),['imported.js','local.js']); + state=await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:1,items:[]})});assert.equal(state.snippets.length,1);assert.equal(state.reviews.length,1); +}); + +test('collection caps and storage failures reject whole mutations without dropping existing content',async()=>{ + const local=area(),store=factory(local); + const snippets=Array.from({length:100},(_,i)=>fullSnippet('s-'+i)); + await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],snippets})}); + await assert.rejects(store.dispatch({type:'SAVE_SNIPPET',snippet:sampleSnippet()}),/100/); + await assert.rejects(store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],snippets:[fullSnippet('overflow')]})}),/100/); + local.fail=true;await assert.rejects(store.dispatch({type:'UPDATE_SNIPPET',id:'s-0',patch:{note:'Unsaved'}}),/Disk full/);local.fail=false; + const state=await store.dispatch({type:'GET_STATE'});assert.equal(state.snippets.length,100);assert.equal(state.snippets.find(item=>item.id==='s-0').note,'Initial'); +}); + +test('workspace and review union limits reject imports without partial writes',async()=>{ + const store=factory(); + const workspaces=Array.from({length:40},(_,i)=>({id:'w-'+i,title:'Workspace '+i,note:'',itemUrls:[],snippetIds:[],createdAt:1,updatedAt:2})); + const files=Array.from({length:500},(_,i)=>({path:`file-${i}.js`,note:'',reviewed:false,reviewedRevision:null,reviewedAt:null,updatedAt:2})); + const reviews=Array.from({length:50},(_,i)=>({prUrl:`https://github.com/o/r/pull/${i+1}`,files:i===0?files:[],lastFile:null,createdAt:1,updatedAt:2})); + await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],workspaces,reviews})}); + await assert.rejects(store.dispatch({type:'CREATE_WORKSPACE',title:'Overflow'}),/40/); + await assert.rejects(store.dispatch({type:'SET_REVIEW_LAST_FILE',prUrl:'https://github.com/o/r/pull/51',path:'a.js'}),/50/); + const newFile={...files[0],path:'extra.js'}; + await assert.rejects(store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],snippets:[fullSnippet('partial-write')],reviews:[{...reviews[0],files:[newFile]}]})}),/500/); + const state=await store.dispatch({type:'GET_STATE'});assert.equal(state.snippets.length,0);assert.equal(state.reviews.find(review=>review.prUrl.endsWith('/1')).files.length,500); +}); + +const fullTemplate=id=>({id,title:'Question',body:'Could you explain this?',createdAt:1,updatedAt:2}); +test('templates use serialized independent patches and survive removal, undo and restart',async()=>{ + const local=area({'ghe:schemaVersion':2}),store=factory(local); + assert.deepEqual((await store.dispatch({type:'GET_STATE'})).templates,[]); + let state=await store.dispatch({type:'CREATE_TEMPLATE',title:'Question',body:'Initial body'});const initial=state.templates[0],id=initial.id; + await Promise.all([store.dispatch({type:'UPDATE_TEMPLATE',id,patch:{title:'Updated title'}}),store.dispatch({type:'UPDATE_TEMPLATE',id,patch:{body:'Updated body'}})]); + state=await factory(local).dispatch({type:'GET_STATE'});const template=state.templates[0];assert.equal(template.title,'Updated title');assert.equal(template.body,'Updated body');assert.equal(template.createdAt,initial.createdAt);assert.ok(template.updatedAt>initial.updatedAt); + await assert.rejects(store.dispatch({type:'UPDATE_TEMPLATE',id,patch:{createdAt:1}}),/patch|field/); + await store.dispatch({type:'REMOVE_TEMPLATE',id});await assert.rejects(store.dispatch({type:'UPDATE_TEMPLATE',id,patch:{title:'No recreation'}}),/not found/); + state=await store.dispatch({type:'RESTORE_TEMPLATE',template});assert.deepEqual(state.templates[0],template); + await store.dispatch({type:'RESTORE_TEMPLATE',template:initial});assert.deepEqual((await store.dispatch({type:'GET_STATE'})).templates[0],template); + assert.ok(Object.hasOwn(await local.get(null),'ghe:template:'+id)); +}); +test('template imports merge newest edits and older backups leave local templates intact',async()=>{ + const store=factory();let state=await store.dispatch({type:'CREATE_TEMPLATE',title:'Local',body:'New local body'});const local=state.templates[0]; + state=await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],templates:[{...fullTemplate(local.id),body:'Stale'},fullTemplate('imported')]})}); + assert.equal(state.templates.find(t=>t.id===local.id).body,'New local body');assert.equal(state.templates.length,2); + for(const version of [1,2]){state=await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version,items:[]})});assert.equal(state.templates.length,2);} + state=await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],templates:[{...local,body:'New import',updatedAt:local.updatedAt+1}]})});assert.equal(state.templates.find(t=>t.id===local.id).body,'New import'); +}); +test('template capacity, invalid content and storage failures never commit partial changes',async()=>{ + const local=area(),store=factory(local),templates=Array.from({length:40},(_,i)=>fullTemplate('t'+i)); + await store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],templates})}); + await assert.rejects(store.dispatch({type:'CREATE_TEMPLATE',title:'Overflow',body:'Body'}),/40/); + await assert.rejects(store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],templates:[fullTemplate('extra')],settings:{wide:true}})}),/40/); + await assert.rejects(store.dispatch({type:'IMPORT_ITEMS',text:JSON.stringify({version:2,items:[],templates:[{...fullTemplate('t0'),body:' '}],settings:{wide:true}})})); + local.fail=true;await assert.rejects(store.dispatch({type:'UPDATE_TEMPLATE',id:'t0',patch:{body:'Unsaved'}}),/Disk full/);local.fail=false; + const state=await store.dispatch({type:'GET_STATE'});assert.equal(state.templates.length,40);assert.equal(state.templates.find(t=>t.id==='t0').body,'Could you explain this?');assert.equal(state.settings.wide,false); + assert.equal((await store.dispatch({type:'UPDATE_TEMPLATE',id:'t0',patch:{body:'Works again'}})).templates.find(t=>t.id==='t0').body,'Works again'); +}); diff --git a/tests/toolkit-integration.test.cjs b/tests/toolkit-integration.test.cjs new file mode 100644 index 0000000..e310b33 --- /dev/null +++ b/tests/toolkit-integration.test.cjs @@ -0,0 +1,110 @@ +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const {JSDOM}=require('jsdom'); + +// Replace only Chrome's external persistence boundary. Validation, serialized +// mutations, view controllers, and Markdown generation are the production code. +function storageArea(){ + let values={}; + return{ + async get(keys){await new Promise(resolve=>setImmediate(resolve));return keys==null?structuredClone(values):Object.fromEntries((Array.isArray(keys)?keys:[keys]).filter(key=>Object.hasOwn(values,key)).map(key=>[key,structuredClone(values[key])]));}, + async set(next){await new Promise(resolve=>setImmediate(resolve));Object.assign(values,structuredClone(next));}, + async remove(keys){await new Promise(resolve=>setImmediate(resolve));for(const key of Array.isArray(keys)?keys:[keys])delete values[key];} + }; +} +const firstCode={path:'src/first.js',text:'const label = "first";\nexport { label };',language:'javascript',lineCount:2,bytes:40,truncated:false,selection:{start:1,end:2},url:'https://github.com/owner/repo/blob/main/src/first.js'}; +const secondCode={...firstCode,path:'src/second.js',text:'export const second = 2;',lineCount:1,selection:{start:1,end:1},url:'https://github.com/owner/repo/blob/main/src/second.js'}; +async function setup(local=storageArea(),code=firstCode){ + const dom=new JSDOM('
',{url:'https://extension.test',runScripts:'outside-only',pretendToBeVisual:true}); + const w=dom.window;w.TextEncoder=TextEncoder; + for(const file of ['src/shared/model.js','src/background/store.js','src/shared/basket.js','src/shared/review.js','src/shared/workspaces.js','src/shared/conversation.js','src/shared/composer.js','src/shared/ui.js'])w.eval(fs.readFileSync(file,'utf8')); + const store=w.GHE.createStore(local,storageArea());const copies=[],actions=[],pending=new Set(); + const request=message=>{const operation=store.dispatch(message);pending.add(operation);operation.then(()=>pending.delete(operation),()=>pending.delete(operation));return operation;}; + const context=code?w.GHE.parseContext(code.url,'Example source'):null; + const ui=w.GHE.mountWorkbench(w.document.querySelector('#app'),{context,pageData:code?{code}:{},request,copy:async text=>copies.push(text),openOptions(){},pageAction:async action=>{actions.push(action);return true;},openPages:async()=>{}}); + await ui.ready; + async function settle(){for(let i=0;i<12;i++){await Promise.allSettled([...pending]);await new Promise(resolve=>setImmediate(resolve));if(!pending.size){await new Promise(resolve=>setImmediate(resolve));if(!pending.size)return;}}throw new Error('UI storage actions did not settle');} + return{dom,w,doc:w.document,ui,local,store,copies,actions,settle}; +} +function click(x,selector){const element=x.doc.querySelector(selector);assert.ok(element,`Control exists: ${selector}`);element.click();} +function change(x,selector,value,event='input'){const element=x.doc.querySelector(selector);assert.ok(element,`Field exists: ${selector}`);element.value=value;element.dispatchEvent(new x.w.Event(event,{bubbles:true}));return element;} + +test('real basket, workspace, and storage modules complete a multi-file export and remount without data loss',async()=>{ + const x=await setup(); + assert.equal(x.ui.hasDrafts(),false,'mounting the toolkit must not manufacture unsaved edits'); + click(x,'[data-action="view:basket"]');change(x,'[data-basket-field="title"]','First evidence');change(x,'[data-basket-field="note"]','Check first allocation'); + click(x,'[data-basket-action="save-excerpt"]');await x.settle();assert.equal(x.ui.getState().snippets.length,1); + const firstId=x.ui.getState().snippets[0].id; + x.ui.setContext(x.w.GHE.parseContext(secondCode.url,'Second source'),{code:secondCode}); + assert.equal(x.doc.querySelector('[data-basket-preview]').textContent,'export const second = 2;'); + change(x,'[data-basket-field="title"]','Second evidence');click(x,'[data-basket-action="save-excerpt"]');await x.settle(); + assert.equal(x.ui.getState().snippets.length,2);const secondId=x.ui.getState().snippets.find(s=>s.id!==firstId).id; + click(x,'[data-action="view:workspaces"]');change(x,'[aria-label="New workspace name"]','Allocation investigation');click(x,'[data-ws="create"]');await x.settle(); + assert.equal(x.ui.getState().workspaces.length,1);const workspaceId=x.ui.getState().workspaces[0].id; + click(x,'[data-ws="add-current"]');await x.settle(); + for(const id of [firstId,secondId]){change(x,'[aria-label="Add a saved snippet"]',id,'change');click(x,'[data-ws="add-snippet"]');await x.settle();} + change(x,'[aria-label="Workspace note"]','Compare both allocation paths.');click(x,'[data-ws="save-note"]');await x.settle(); + assert.equal(x.ui.hasDrafts(),false,'successful saves clear the drafts reported by the main workbench'); + click(x,'[data-ws="copy"]');await x.settle(); + const markdown=x.copies.at(-1);assert.match(markdown,/Allocation investigation/);assert.match(markdown,/src\/first\\\.js/);assert.match(markdown,/src\/second\\\.js/);assert.match(markdown,/Check first allocation/);assert.match(markdown,/Compare both allocation paths/);assert.match(markdown,/#L1-L2/); + const persisted=x.ui.getState();assert.equal(persisted.items.length,1);assert.equal(persisted.workspaces[0].itemUrls[0],secondCode.url);assert.equal(persisted.workspaces[0].snippetIds.length,2); + x.dom.window.close();const reopened=await setup(x.local,null);assert.equal(reopened.ui.getState().snippets.length,2); + click(reopened,'[data-action="view:workspaces"]');change(reopened,'[aria-label="Choose workspace"]',workspaceId,'change');click(reopened,'[data-ws="copy"]');await reopened.settle(); + assert.equal(reopened.copies.at(-1),markdown);reopened.dom.window.close(); +}); + +test('context navigation keeps basket edits while real review notes and revision markers persist independently',async()=>{ + const x=await setup();click(x,'[data-action="view:basket"]');click(x,'[data-basket-action="save-excerpt"]');await x.settle(); + click(x,'[data-basket-action="edit-snippet"]');change(x,'[data-basket-edit="note"]','Unsaved basket context'); + assert.equal(x.ui.hasDrafts(),true,'the main workbench detects a child basket draft'); + const prUrl='https://github.com/owner/repo/pull/7';const revision='a'.repeat(40); + const review={revision,files:[{id:'diff-first',path:'src/first.js',group:'source',folder:'src',viewedKnown:true,viewed:false}],truncated:false}; + x.ui.setContext(x.w.GHE.parseContext(prUrl+'/files','Review allocation'),{review});click(x,'[data-action="view:tools"]'); + assert.equal(x.doc.querySelector('[data-basket-edit="note"]').value,'Unsaved basket context'); + assert.match(x.doc.querySelector('[data-basket-composer]').textContent,/Open a code file/); + change(x,'[aria-label="Private file note"]','Check the null branch');click(x,'[data-review-action="save-note"]');await x.settle(); + const checkbox=x.doc.querySelector('.review-check input');checkbox.checked=true;checkbox.dispatchEvent(new x.w.Event('change',{bubbles:true}));await x.settle(); + let record=x.ui.getState().reviews[0];assert.equal(record.files[0].note,'Check the null branch');assert.equal(record.files[0].reviewedRevision,revision);assert.match(x.doc.querySelector('.review-mark-status').textContent,/Verified/); + click(x,'[data-review-action="jump"]');await x.settle();assert.equal(x.ui.getState().reviews[0].lastFile,'src/first.js');assert.equal(x.actions.at(-1).type,'review-jump'); + assert.equal(x.ui.getState().snippets[0].note,'','unsaved basket note is not silently committed by a review write'); + click(x,'[data-action="view:basket"]');assert.equal(x.doc.querySelector('[data-basket-edit="note"]').value,'Unsaved basket context');click(x,'[data-basket-action="save-snippet"]');await x.settle(); + assert.equal(x.ui.getState().snippets[0].note,'Unsaved basket context'); + assert.equal(x.ui.hasDrafts(),false); + x.ui.setContext(x.w.GHE.parseContext(prUrl+'/files'),{review:{...review,revision:'b'.repeat(40)}});click(x,'[data-action="view:tools"]');assert.match(x.doc.querySelector('.review-mark-status').textContent,/Revision changed/); + x.dom.window.close();const reopened=await setup(x.local,null);record=reopened.ui.getState().reviews[0];assert.equal(record.files[0].reviewedRevision,revision);assert.equal(record.lastFile,'src/first.js');assert.equal(reopened.ui.getState().snippets[0].note,'Unsaved basket context');reopened.dom.window.close(); +}); + +test('important conversation evidence becomes a workspace source and survives reopen',async()=>{ + const x=await setup(),url='https://github.com/owner/repo/issues/12',comment={id:'issuecomment-123',url:url+'#issuecomment-123',author:'maintainer',body:'The root cause is a stale callback.',kind:'comment'}; + x.ui.setContext(x.w.GHE.parseContext(url,'Investigate callback'),{conversation:{comments:[comment],loadedOnly:true,truncated:false}}); + click(x,'[data-action="view:tools"]');click(x,'[data-conversation="save"]');await x.settle(); + assert.equal(x.ui.getState().items[0].url,comment.url); + click(x,'[data-action="view:workspaces"]');change(x,'[aria-label="New workspace name"]','Callback investigation');click(x,'[data-ws="create"]');await x.settle(); + change(x,'[aria-label="Add a saved page"]',comment.url,'change');click(x,'[data-ws="add-page"]');await x.settle(); + click(x,'[data-ws="copy"]');await x.settle();assert.match(x.copies.at(-1),/#issuecomment-123/);assert.match(x.copies.at(-1),/stale callback/); + const id=x.ui.getState().workspaces[0].id;x.dom.window.close();const y=await setup(x.local,null);assert.equal(y.ui.getState().workspaces.find(w=>w.id===id).itemUrls[0],comment.url);y.dom.window.close(); +}); + +test('command search retrieves private workspace intent, code evidence and PR notes',async()=>{ + const x=await setup();await x.store.dispatch({type:'CREATE_WORKSPACE',title:'Callback investigation'});let next=await x.store.dispatch({type:'GET_STATE'});const id=next.workspaces[0].id; + await x.store.dispatch({type:'UPDATE_WORKSPACE',id,patch:{note:'Investigate the midnight regression'}}); + await x.ui.refresh();x.ui.openPalette();change(x,'[aria-label="Search commands and saved pages"]','midnight'); + const option=x.doc.querySelector('.command-option');assert.ok(option);assert.match(option.textContent,/Callback investigation/);option.click();assert.equal(x.doc.querySelector('[aria-label="Choose workspace"]').value,id); + click(x,'[data-action="view:basket"]');change(x,'[data-basket-field="note"]','Evidence of allocator mismatch');click(x,'[data-basket-action="save-excerpt"]');await x.settle(); + x.ui.openPalette();change(x,'[aria-label="Search commands and saved pages"]','allocator mismatch');assert.match(x.doc.querySelector('.command-option').textContent,/Code excerpt/);x.doc.querySelector('.command-option').click();assert.equal(x.doc.querySelector('#app').dataset.view,'basket'); + await x.store.dispatch({type:'UPDATE_REVIEW_FILE',prUrl:'https://github.com/owner/repo/pull/9',path:'src/pool.js',revision:null,patch:{note:'An allocation survives cancellation'}});await x.ui.refresh();x.ui.openPalette();change(x,'[aria-label="Search commands and saved pages"]','survives cancellation');assert.match(x.doc.querySelector('.command-option').textContent,/Private PR note/);assert.equal(x.doc.querySelector('.command-option').href,'https://github.com/owner/repo/pull/9/files'); + x.dom.window.close(); +}); + +test('Write templates use real persistence, remain private, and are restored by backups',async()=>{ + const x=await setup();click(x,'[data-action="view:write"]');change(x,'[aria-label="Markdown draft"]','Please include a minimal reproduction.');change(x,'[aria-label="New template name"]','Reproduction request');click(x,'[data-composer-action="create-template"]');await x.settle();assert.equal(x.ui.getState().templates.length,1); + click(x,'[data-composer-action="copy"]');await x.settle();assert.equal(x.copies.at(-1),'Please include a minimal reproduction.');assert.equal(x.actions.length,0,'drafting does not touch the host page'); + const backup=x.w.GHE.exportBackup(x.ui.getState());assert.equal(JSON.parse(backup).templates[0].title,'Reproduction request'); + x.dom.window.close();const y=await setup(x.local,null);assert.equal(y.ui.getState().templates[0].body,'Please include a minimal reproduction.');y.dom.window.close(); +}); + +test('whole-workbench refresh preserves conversation search focus and selection',async()=>{ + const x=await setup(),url='https://github.com/owner/repo/issues/12';x.ui.setContext(x.w.GHE.parseContext(url),{conversation:{comments:[{id:'issuecomment-1',url:url+'#issuecomment-1',author:'alice',body:'hello world',kind:'comment'}],loadedOnly:true,truncated:false}}); + click(x,'[data-action="view:tools"]');const input=change(x,'[aria-label="Search loaded comments"]','hello');input.focus();input.setSelectionRange(1,4);await x.ui.refresh();const current=x.doc.activeElement;assert.equal(current.getAttribute('aria-label'),'Search loaded comments');assert.equal(current.selectionStart,1);assert.equal(current.selectionEnd,4);x.dom.window.close(); +}); diff --git a/tests/ui.test.cjs b/tests/ui.test.cjs new file mode 100644 index 0000000..885059f --- /dev/null +++ b/tests/ui.test.cjs @@ -0,0 +1,131 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { JSDOM } = require('jsdom'); +const fs = require('node:fs'); +const flush = () => new Promise(resolve => setTimeout(resolve, 0)); +function setup({ fail = false, draftStore = {} } = {}) { + const dom = new JSDOM('
', { url: 'https://extension.test', runScripts: 'outside-only', pretendToBeVisual: true }); + const win = dom.window; + const state = { settings: { enabled: true, shortcut: true, exactDates: true, wide: false, focus: false, theme: 'auto' }, items: [] }; + const api = async message => { + if (fail && message.type !== 'GET_STATE') throw new Error('Storage is full'); + if (message.type === 'SAVE_ITEM') state.items = [{ ...message.context, note: message.note || '', createdAt: 1, updatedAt: 1 }]; + if (message.type === 'UPDATE_ITEM') state.items[0].note = message.note; + if (message.type === 'REMOVE_ITEM') state.items = []; + return structuredClone(state); + }; + win.GHE = { filterItems: (items,q) => items.filter(i=>`${i.title} ${i.note}`.toLowerCase().includes(q.toLowerCase())), markdownLink: c => `[${c.title}](${c.url})`, DEFAULT_SETTINGS:state.settings }; + const file = 'src/shared/ui.js'; + if (fs.existsSync(file)) win.eval(fs.readFileSync(file,'utf8')); + assert.equal(typeof win.GHE.mountWorkbench, 'function', 'workbench must be implemented'); + const context = { url:'https://github.com/octocat/Hello-World',repo:'octocat/Hello-World',owner:'octocat',name:'Hello-World',type:'repository',title:'Hello-World' }; + const ui = win.GHE.mountWorkbench(win.document.querySelector('#app'), { request:api, context, copy: async()=>{}, openOptions:()=>{}, close:()=>{}, loadDrafts:async()=>Object.entries(draftStore), saveDraft:async(url,note)=>{draftStore[url]=note;}, deleteDraft:async(url)=>{delete draftStore[url];} }); + return { dom,win,state,ui,context, doc:win.document }; +} +test('saving a page exposes one searchable saved item and safe title text', async()=>{ + const x=setup(); await x.ui.ready; + x.doc.querySelector('[data-action="save"]').click(); await flush(); + assert.equal(x.doc.querySelectorAll('[data-saved-item]').length,1); + x.ui.setContext({...x.context,title:''}); + assert.equal(x.doc.querySelectorAll('img').length,0); + assert.match(x.doc.querySelector('[data-context-title]').textContent,/{ + const x=setup();await x.ui.ready; + const full='OctoCat/Hello-World: A useful repository description'; + x.ui.setContext({...x.context,repo:'octocat/hello-world',title:full}); + const heading=x.doc.querySelector('[data-context-title]'); + assert.equal(heading.textContent,'OctoCat/Hello-World'); + assert.equal(heading.title,full); + x.doc.querySelector('[data-action="save"]').click();await flush(); + assert.equal(x.state.items[0].title,full); + const saved=x.doc.querySelector('.saved-title'); + assert.equal(saved.textContent,'OctoCat/Hello-World'); + assert.equal(saved.title,full); + const search=x.doc.querySelector('[aria-label="Search saved pages"]'); + search.value='useful repository description';search.dispatchEvent(new x.win.Event('input')); + assert.equal(x.doc.querySelectorAll('[data-saved-item]').length,1); + x.dom.window.close(); +}); +test('unrelated repository titles and issue titles remain complete',async()=>{ + const x=setup();await x.ui.ready; + for(const context of [ + {...x.context,title:'Release notes: a custom title'}, + {...x.context,title:'octocat/Hello-World: investigate a bug',type:'issue'}, + {...x.context,title:'other/Hello-World: a different repository'}, + ]){x.ui.setContext(context);assert.equal(x.doc.querySelector('[data-context-title]').textContent,context.title);} + x.dom.window.close(); +}); +test('note drafts survive context changes and save only to the original page',async()=>{ + const x=setup();await x.ui.ready; + x.doc.querySelector('[data-action="note"]').click(); + const note=x.doc.querySelector('[aria-label="Private note"]');note.value='Investigate edge cases';note.dispatchEvent(new x.win.Event('input')); + x.ui.setContext({...x.context,url:'https://github.com/octocat/Other',repo:'octocat/Other',title:'Other'}); + x.ui.setContext(x.context); + assert.equal(x.doc.querySelector('[aria-label="Private note"]').value,'Investigate edge cases'); + x.doc.querySelector('[data-action="save-note"]').click();await flush(); + assert.equal(x.state.items[0].url,x.context.url);assert.equal(x.state.items[0].note,'Investigate edge cases');x.dom.window.close(); +}); +test('failed persistence keeps the draft and never announces success',async()=>{ + const x=setup({fail:true});await x.ui.ready;x.doc.querySelector('[data-action="note"]').click(); + const note=x.doc.querySelector('[aria-label="Private note"]');note.value='Keep this';note.dispatchEvent(new x.win.Event('input')); + x.doc.querySelector('[data-action="save-note"]').click();await flush(); + assert.equal(x.doc.querySelector('[aria-label="Private note"]').value,'Keep this'); + assert.match(x.doc.querySelector('[role="status"]').textContent,/Storage is full/); + assert.equal(x.doc.querySelectorAll('[data-saved-item]').length,0);x.dom.window.close(); +}); +test('opening and escaping command search restores keyboard focus',async()=>{ + const x=setup();await x.ui.ready;const launch=x.doc.querySelector('[data-action="commands"]');launch.focus();launch.click(); + assert.equal(x.doc.activeElement.getAttribute('aria-label'),'Search commands and saved pages'); + x.doc.activeElement.dispatchEvent(new x.win.KeyboardEvent('keydown',{key:'Escape',bubbles:true})); + assert.equal(x.doc.activeElement,launch);x.dom.window.close(); +}); + +test('Escape in command search is marked handled before reaching the frame close handler',async()=>{ + const x=setup();await x.ui.ready;x.ui.openPalette();const event=new x.win.KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true});x.doc.activeElement.dispatchEvent(event);assert.equal(event.defaultPrevented,true);x.dom.window.close(); +}); + +test('the command shortcut works inside a focused note and restores it without duplicating the palette',async()=>{ + const x=setup();await x.ui.ready;x.doc.querySelector('[data-action="note"]').click(); + const note=x.doc.querySelector('textarea');note.value='Keep this draft';note.dispatchEvent(new x.win.Event('input'));note.focus(); + let propagated=0;x.win.addEventListener('keydown',()=>propagated++); + const shortcut=()=>new x.win.KeyboardEvent('keydown',{key:'K',code:'KeyK',altKey:true,shiftKey:true,bubbles:true,cancelable:true}); + const event=shortcut();note.dispatchEvent(event); + assert.equal(x.doc.activeElement.getAttribute('aria-label'),'Search commands and saved pages'); + assert.equal(event.defaultPrevented,true);assert.equal(propagated,0); + x.doc.activeElement.value='clone';x.doc.activeElement.dispatchEvent(new x.win.Event('input')); + x.doc.activeElement.dispatchEvent(shortcut()); + assert.equal(x.doc.querySelectorAll('.command-overlay').length,1);assert.equal(x.doc.activeElement.value,'clone'); + x.doc.activeElement.dispatchEvent(new x.win.KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true})); + assert.equal(x.doc.activeElement,note);assert.equal(note.value,'Keep this draft');x.dom.window.close(); +}); + +test('the command shortcut honors refreshed enablement settings',async()=>{ + const x=setup();await x.ui.ready;const launch=x.doc.querySelector('[data-action="commands"]'); + for(const settings of [{enabled:true,shortcut:false},{enabled:false,shortcut:true}]){ + Object.assign(x.state.settings,settings);await x.ui.refresh();launch.focus(); + const event=new x.win.KeyboardEvent('keydown',{code:'KeyK',altKey:true,shiftKey:true,bubbles:true,cancelable:true});launch.dispatchEvent(event); + assert.equal(x.doc.querySelector('.command-overlay'),null);assert.equal(event.defaultPrevented,false); + } + Object.assign(x.state.settings,{enabled:true,shortcut:true});await x.ui.refresh(); + launch.dispatchEvent(new x.win.KeyboardEvent('keydown',{code:'KeyK',altKey:true,shiftKey:true,bubbles:true,cancelable:true})); + assert.ok(x.doc.querySelector('.command-overlay'));x.dom.window.close(); +}); + +test('ordinary typing and other modifier combinations remain unhandled',async()=>{ + const x=setup();await x.ui.ready;x.doc.querySelector('[data-action="note"]').click();const note=x.doc.querySelector('textarea'); + for(const init of [{key:'k',code:'KeyK'},{code:'KeyK',altKey:true},{code:'KeyK',shiftKey:true},{code:'KeyK',altKey:true,shiftKey:true,ctrlKey:true},{code:'KeyK',altKey:true,shiftKey:true,metaKey:true},{code:'KeyJ',altKey:true,shiftKey:true}]){ + const event=new x.win.KeyboardEvent('keydown',{...init,bubbles:true,cancelable:true});note.dispatchEvent(event); + assert.equal(event.defaultPrevented,false);assert.equal(x.doc.querySelector('.command-overlay'),null); + } + x.dom.window.close(); +}); + +test('an unsaved note is recovered after the extension UI is closed and reopened',async()=>{ + const draftStore={};const x=setup({draftStore});await x.ui.ready;x.doc.querySelector('[data-action="note"]').click();const note=x.doc.querySelector('textarea');note.value='Recover this research';note.dispatchEvent(new x.win.Event('input'));await flush();x.dom.window.close(); + const next=setup({draftStore});await next.ui.ready;assert.equal(next.doc.querySelector('textarea')?.value,'Recover this research'); + next.doc.querySelector('[data-action="save-note"]').click();await flush();assert.equal(next.state.items[0].note,'Recover this research');assert.deepEqual(draftStore,{});next.dom.window.close(); +}); diff --git a/tests/workspaces.test.cjs b/tests/workspaces.test.cjs new file mode 100644 index 0000000..ebd0640 --- /dev/null +++ b/tests/workspaces.test.cjs @@ -0,0 +1,58 @@ +const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const {JSDOM}=require('jsdom'); +function setup(options={}){const dom=new JSDOM('
',{url:'https://extension.test',runScripts:'outside-only'});const w=dom.window;let state={items:[{url:'https://github.com/o/r/issues/1',title:'Investigate race',repo:'o/r',note:'Existing note'}],snippets:[{id:'snippet1',title:'Race source',path:'src/app.js',code:'return 1',url:'https://github.com/o/r/blob/main/src/app.js#L1',language:'javascript',lineStart:1,lineEnd:1}],workspaces:[]};const messages=[];let copied='';w.eval(fs.readFileSync('src/shared/model.js','utf8'));Object.assign(w.GHE,{markdownLink:c=>`[${c.title}](${c.url})`,snippetMarkdown:s=>s.code});w.eval(fs.readFileSync('src/shared/workspaces.js','utf8'));if(options.state)state=structuredClone(options.state);const request=async m=>{messages.push(m);await options.beforeRequest?.(m);if(m.type==='CREATE_WORKSPACE')state.workspaces.push({id:'w1',title:m.title,note:'',itemUrls:[],snippetIds:[]});if(m.type==='LINK_WORKSPACE_ITEM')state.workspaces[0].itemUrls.push(m.url);if(m.type==='LINK_WORKSPACE_SNIPPET')state.workspaces[0].snippetIds.push(m.snippetId);if(m.type==='UPDATE_WORKSPACE')Object.assign(state.workspaces[0],m.patch);return structuredClone(state);};let ui;ui=w.GHE.mountWorkspaces(w.document.querySelector('main'),{...options,getState:()=>state,getContext:()=>state.items[0],request,onState:s=>{state=s;ui.render();},notify:()=>{},copy:async s=>copied=s,openPages:async()=>{}});ui.render();return{dom,w,ui,messages,getState:()=>state,getCopied:()=>copied};} +const tick=()=>new Promise(r=>setTimeout(r,0)); +test('workspace combines saved pages and snippets and exports their sources',async()=>{const x=setup(),d=x.w.document;d.querySelector('[aria-label="New workspace name"]').value='Race investigation';d.querySelector('[data-ws="create"]').click();await tick();assert.equal(x.getState().workspaces.length,1);d.querySelector('[data-ws="add-current"]').click();await tick();assert.deepEqual(x.getState().workspaces[0].itemUrls,['https://github.com/o/r/issues/1']);d.querySelector('[aria-label="Add a saved snippet"]').value='snippet1';d.querySelector('[data-ws="add-snippet"]').click();await tick();assert.deepEqual(x.getState().workspaces[0].snippetIds,['snippet1']);assert.equal([...d.querySelectorAll('a')].find(a=>a.textContent==='Race source').hash,'#L1');d.querySelector('[data-ws="copy"]').click();await tick();assert.match(x.getCopied(),/Race investigation/);assert.match(x.getCopied(),/Investigate race/);assert.match(x.getCopied(),/return 1/);x.dom.window.close();}); +test('unsaved workspace note survives unrelated state refreshes',async()=>{const x=setup(),d=x.w.document;d.querySelector('[aria-label="New workspace name"]').value='Notes';d.querySelector('[data-ws="create"]').click();await tick();const n=d.querySelector('[aria-label="Workspace note"]');n.value='Keep this draft';n.dispatchEvent(new x.w.Event('input'));x.ui.render();assert.equal(d.querySelector('[aria-label="Workspace note"]').value,'Keep this draft');d.querySelector('[data-ws="save-note"]').click();await tick();assert.equal(x.getState().workspaces[0].note,'Keep this draft');x.dom.window.close();}); +test('workspace creation and rename text survive unrelated refreshes',async()=>{const x=setup(),d=x.w.document;const name=d.querySelector('[aria-label="New workspace name"]');name.value='Investigation in progress';name.dispatchEvent(new x.w.Event('input'));x.ui.render();assert.equal(d.querySelector('[aria-label="New workspace name"]').value,'Investigation in progress');d.querySelector('[data-ws="create"]').click();await tick();assert.equal(d.querySelector('[aria-label="New workspace name"]').value,'');d.querySelector('[data-ws="rename"]').click();const rename=d.querySelector('[aria-label="Rename workspace"]');rename.value='Renamed investigation';rename.dispatchEvent(new x.w.Event('input'));x.ui.render();assert.equal(d.querySelector('[aria-label="Rename workspace"]').value,'Renamed investigation');d.querySelector('[data-ws="save-name"]').click();await tick();assert.equal(x.getState().workspaces[0].title,'Renamed investigation');assert.equal(d.querySelector('[aria-label="Rename workspace"]'),null);x.dom.window.close();}); + +function recovery(store,overrides={}){return {loadToolDrafts:async kind=>Object.entries(store).map(([key,value])=>[key,structuredClone(value)]),saveToolDraft:async(kind,key,value)=>{store[key]=structuredClone(value);},deleteToolDraft:async(kind,key,expected)=>{if(JSON.stringify(store[key])===JSON.stringify(expected))delete store[key];},...overrides};} +function type(x,label,value){const input=x.w.document.querySelector(`[aria-label="${label}"]`);input.value=value;input.dispatchEvent(new x.w.Event('input'));} +function choose(x,id='w1'){const select=x.w.document.querySelector('[aria-label="Choose workspace"]');select.value=id;select.dispatchEvent(new x.w.Event('change'));} +const workspaceState=()=>({items:[],snippets:[],workspaces:[{id:'w1',title:'Investigation',note:'Committed',itemUrls:[],snippetIds:[]}]}); +test('workspace note, creation and rename drafts recover on remount and clear only when committed',async()=>{ + const store={},state=workspaceState(),x=setup({...recovery(store),state});await x.ui.ready;choose(x);type(x,'Workspace note','Remember edge case');type(x,'New workspace name','Next investigation');x.w.document.querySelector('[data-ws="rename"]').click();type(x,'Rename workspace','Better title');await tick();x.dom.window.close(); + const y=setup({...recovery(store),state});assert.ok(y.ui.ready instanceof y.w.Promise);await y.ui.ready;choose(y);assert.equal(y.w.document.querySelector('[aria-label="Workspace note"]').value,'Remember edge case');assert.equal(y.w.document.querySelector('[aria-label="New workspace name"]').value,'Next investigation');assert.equal(y.w.document.querySelector('[aria-label="Rename workspace"]').value,'Better title');assert.equal(y.ui.hasDrafts(),true); + y.w.document.querySelector('[data-ws="save-note"]').click();await tick();assert.equal(y.getState().workspaces[0].note,'Remember edge case');assert.equal(store['note:w1'],undefined);assert.deepEqual(store['rename:w1'],{title:'Better title'});y.dom.window.close(); +}); +test('late recovery cannot replace a touched or discarded draft',async()=>{ + let resolve;const pending=new Promise(r=>resolve=r);const x=setup({...recovery({}, {loadToolDrafts:()=>pending}),state:workspaceState()});choose(x);type(x,'Workspace note','New input');type(x,'New workspace name','Fresh title');resolve([['note:w1',{note:'Old recovered'}],['create',{title:'Old title'}]]);await x.ui.ready;assert.equal(x.w.document.querySelector('[aria-label="Workspace note"]').value,'New input');assert.equal(x.w.document.querySelector('[aria-label="New workspace name"]').value,'Fresh title');x.w.document.querySelector('[data-ws="discard-note"]').click();await tick();assert.equal(x.w.document.querySelector('[aria-label="Workspace note"]').value,'Committed');x.dom.window.close(); +}); +test('saving an older note does not erase a newer draft on this surface or another',async()=>{ + const store={};let release;const gate=new Promise(r=>release=r);const x=setup({...recovery(store),state:workspaceState(),beforeRequest:m=>m.type==='UPDATE_WORKSPACE'?gate:undefined});await x.ui.ready;choose(x);type(x,'Workspace note','Submitted');x.w.document.querySelector('[data-ws="save-note"]').click();type(x,'Workspace note','Newer local');await tick();store['note:w1']={note:'Newer other surface'};release();await tick();assert.equal(x.w.document.querySelector('[aria-label="Workspace note"]').value,'Newer local');assert.deepEqual(store['note:w1'],{note:'Newer other surface'});assert.equal(x.getState().workspaces[0].note,'Submitted');x.dom.window.close(); +}); + +test('successful create and rename clear the exact recovered snapshots',async()=>{ + const store={create:{title:'Recovered title'}},x=setup(recovery(store));await x.ui.ready;x.w.document.querySelector('[data-ws="create"]').click();await tick();assert.equal(store.create,undefined);assert.equal(x.w.document.querySelector('[aria-label="New workspace name"]').value,'');x.w.document.querySelector('[data-ws="rename"]').click();type(x,'Rename workspace','Renamed');await tick();x.w.document.querySelector('[data-ws="save-name"]').click();await tick();assert.equal(store['rename:w1'],undefined);assert.equal(x.getState().workspaces[0].title,'Renamed');assert.equal(x.ui.hasDrafts(),false);x.dom.window.close(); +}); +test('discard before recovery settles prevents an old note from returning',async()=>{ + let release;const pending=new Promise(r=>release=r),store={};const x=setup({...recovery(store,{loadToolDrafts:()=>pending}),state:workspaceState()});choose(x);type(x,'Workspace note','Temporary');x.w.document.querySelector('[data-ws="discard-note"]').click();await tick();release([['note:w1',{note:'Old session copy'}]]);await x.ui.ready;assert.equal(x.w.document.querySelector('[aria-label="Workspace note"]').value,'Committed');assert.equal(x.ui.hasDrafts(),false);assert.equal(store['note:w1'],undefined);x.dom.window.close(); +}); +test('failed note commit retains recovery and user edits',async()=>{ + const store={},x=setup({...recovery(store),state:workspaceState(),beforeRequest:()=>{throw new Error('Storage full');}});await x.ui.ready;choose(x);type(x,'Workspace note','Must retain');await tick();x.w.document.querySelector('[data-ws="save-note"]').click();await tick();assert.equal(x.getState().workspaces[0].note,'Committed');assert.deepEqual(store['note:w1'],{note:'Must retain'});assert.equal(x.w.document.querySelector('[aria-label="Workspace note"]').value,'Must retain');x.dom.window.close(); +}); + +test('creation focus and selected text survive refresh with no workspace selected',async()=>{ + const x=setup();await x.ui.ready;const input=x.w.document.querySelector('[aria-label="New workspace name"]');type(x,'New workspace name','Investigation title');input.focus();input.setSelectionRange(2,9);x.ui.render();const current=x.w.document.querySelector('[aria-label="New workspace name"]');assert.equal(x.w.document.activeElement,current);assert.equal(current.selectionStart,2);assert.equal(current.selectionEnd,9);x.dom.window.close(); +}); + +test('controller selection opens an existing workspace and ignores missing IDs',async()=>{const x=setup({state:workspaceState()});await x.ui.ready;assert.equal(x.ui.select('w1'),true);assert.equal(x.w.document.querySelector('[aria-label="Workspace note"]').value,'Committed');assert.equal(x.ui.select('missing'),false);assert.equal(x.w.document.querySelector('[aria-label="Choose workspace"]').value,'w1');x.dom.window.close();}); + +test('workspace exports disclose unsaved edits and include only saved notes',async()=>{ + const x=setup({state:workspaceState()});await x.ui.ready;x.ui.select('w1');type(x,'Workspace note','Unsaved private thought');assert.match(x.w.document.querySelector('[data-workspace-export-notice]').textContent,/Export uses saved notes/);assert.equal(x.w.document.querySelector('[data-workspace-export-notice]').hidden,false);x.w.document.querySelector('[data-ws="copy"]').click();await tick();assert.match(x.getCopied(),/Committed/);assert.doesNotMatch(x.getCopied(),/Unsaved private thought/);assert.equal(x.messages.length,0);x.dom.window.close(); +}); +test('linked PR file notes are an explicit counted export option and exclude unlinked review records',async()=>{ + const state=workspaceState(),urls=['https://github.com/o/r/pull/4','https://github.com/o/r/pull/4/changes#diff-x'];state.workspaces[0].itemUrls=urls;state.items=urls.map(url=>({url,title:'Linked PR',repo:'o/r',note:''}));state.reviews=[{prUrl:urls[0],files:[{path:'src/[a].js',note:'Saved finding