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
-[](https://github.com/adomorn/Github-Enhancer/actions/workflows/chrome-extension-ci.yml)
-
-
-
-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.
-
+## 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 @@
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 = `
-
Adjust your workbench and the way you read GitHub.
+
+
+
Loading your settingsโฆ
+
+
+
+
+
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.