Compare commits

..

6 Commits

Author SHA1 Message Date
Sergey Marinkevich d8c4cc3f9f release 0.1.8 4 months ago
Sergey Marinkevich dbe8418cdd use promise to cache requests
Don't do N equal requests for N equal answers
4 months ago
Sergey Marinkevich b4a66ee5c0 placeholder utill we loaded up 4 months ago
Sergey Marinkevich db11fff026 simplify build 4 months ago
Сергей Маринкевич 2a17029751 add readme 4 months ago
Сергей Маринкевич 434007ce68 add firefox support 4 months ago

@ -0,0 +1 @@
BUILD=8

@ -1 +1,3 @@
VITE_API_BASE_URL=https://redmine-reactions.marinkevich.ru
AMO_JWT_ISSUER=
AMO_JWT_SECRET=

2
.gitignore vendored

@ -2,3 +2,5 @@
dist
node_modules
redmine-reactions.pem
build
output

@ -4,16 +4,35 @@ FROM node:20-alpine AS builder
# Устанавливаем рабочую директорию внутри контейнера
WORKDIR /app
#ENV USER=docker
#ENV GROUPNAME=$USER
#ENV UID=1000
#ENV GID=1000
#
#RUN addgroup \
# --gid "$GID" \
# "$GROUPNAME" \
#&& adduser \
# --disabled-password \
# --gecos "" \
# --home "$(pwd)" \
# --ingroup "$GROUPNAME" \
# --no-create-home \
# --uid "$UID" \
# $USER
# Копируем сначала только package.json и package-lock.json (если есть)
# Это ключевая оптимизация! Docker будет кэшировать этот слой, и npm install
# не будет запускаться каждый раз, если зависимости не менялись.
COPY package*.json ./
COPY --chown=node:node package*.json ./
RUN chown node:node /app -R
RUN echo -e 'nameserver 1.1.1.1\noptions single-request-reopen' > /etc/resolv.conf && \
cat /etc/resolv.conf && \
npm install --verbose
su - node -c "cd /app && npm install"
USER node
# Теперь копируем все остальные исходники
COPY . .
COPY --chown=node:node . .
# Команда, которая будет выполняться по умолчанию для сборки проекта
CMD ["npm", "run", "build"]

@ -0,0 +1,56 @@
BUILD_DIR := build
DIST_DIR := $(BUILD_DIR)/dist
OUTPUT_DIR := output
CHROME_ZIP := $(OUTPUT_DIR)/chrome/redmine-reactions.zip
FIREFOX_XPI := $(OUTPUT_DIR)/firefox/redmine-reactions.xpi
DOCKER_COMPOSE_RUN := docker-compose run --rm builder
ifneq (,$(wildcard .env))
include .env
export AMO_JWT_ISSUER AMO_JWT_SECRET
endif
include .aibuild
BUILD := $(shell echo $$(($(BUILD) + 1)))
.PHONY: all chrome firefox clean
all: chrome firefox
chrome: build output builder aibuild
@echo "==> 🏗️ Building for Chrome..."
sed -e "s/AI_BUILD/$(BUILD)/" manifest-chrome.json > ./build/manifest.json
$(DOCKER_COMPOSE_RUN) npm run build
@echo "==> 📦 Packaging Chrome extension..."
mkdir -p $(OUTPUT_DIR)/chrome
cd $(DIST_DIR) && zip -rq ../../$(CHROME_ZIP) .
@echo "==> ✅ Chrome package is ready: $(CHROME_ZIP)"
firefox: build output builder aibuild
@echo "==> 🏗️ Building for Firefox..."
sed -e "s/AI_BUILD/$(BUILD)/" manifest-firefox.json > ./build/manifest.json
$(DOCKER_COMPOSE_RUN) npm run build
@echo "==> ✍️ Signing Firefox extension (this may take a moment)..."
$(DOCKER_COMPOSE_RUN) npm run sign:firefox
@echo "==> 🚚 Moving signed XPI to output..."
mkdir -p $(OUTPUT_DIR)/firefox
find $(BUILD_DIR)/amo -name "*.xpi" -exec mv {} $(FIREFOX_XPI) \;
@echo "==> ✅ Firefox package is ready: $(FIREFOX_XPI)"
aibuild:
@echo BUILD=$(BUILD) > .aibuild
output:
mkdir output
build:
mkdir build
builder:
docker-compose build
clean:
@echo "==> 🧹 Cleaning up build artifacts..."
rm -rf $(BUILD_DIR) $(OUTPUT_DIR)

@ -1,18 +1,16 @@
Build
=====
docker-compose run --rm builder npm run build:chrome
make chrome
or
docker-compose run --rm builder npm run build:firefox
make firefox
Signed
======
Needs AMO API key from Mozilla.
Needs AMO API key from Mozilla. Place it to the `.env` file.
docker-compose run --rm \
-e AMO_JWT_ISSUER="$USER" \
-e AMO_JWT_SECRET="$SECRET" \
builder npm run package:firefox-signed
AMO_JWT_ISSUER=$USER
AMO_JWT_SECRET=$SECRET

@ -1,34 +1,13 @@
version: '3.8'
services:
# Сервис для ОДНОРАЗОВОЙ СБОРКИ расширения (команда npm run build)
# Запускается командой: docker-compose run --rm builder
builder:
# Собираем образ на основе нашего Dockerfile.build
build:
context: .
dockerfile: Dockerfile.build
# Это магия! Мы "пробрасываем" всю текущую папку внутрь контейнера.
# Когда внутри контейнера в /app создастся папка dist, она автоматически
# появится и на нашей хост-машине.
env_file:
- .env
volumes:
- .:/app
# Анонимный том для node_modules. Важный трюк!
# Он предотвращает перезапись папки node_modules, установленной внутри
# контейнера, пустой папкой с хоста.
- /app/node_modules
# Сервис для РЕЖИМА РАЗРАБОТКИ (команда npm run dev)
# Запускается командой: docker-compose up dev
dev:
build:
context: .
dockerfile: Dockerfile.build
ports:
# Пробрасываем порт Vite для hot-reload
- "5173:5173"
volumes:
- .:/app
- /app/node_modules
# Переопределяем команду по умолчанию на запуск dev-сервера
command: npm run dev
- ./build:/app/build
- ./build/manifest.json:/app/manifest.json
- ./output:/app/output

@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Redmine Reactions",
"version": "0.1.0",
"version": "0.1.AI_BUILD",
"description": "Добавляет реакции на комментарии в локальном Redmine.",
"permissions": ["storage"],
"icons": {
@ -10,7 +10,8 @@
"content_scripts": [
{
"matches": ["https://red.eltex.loc/issues/*"],
"js": ["src/content.tsx"]
"js": ["src/content.tsx"],
"run_at": "document_start"
}
]
}

@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Redmine Reactions",
"version": "0.1.0",
"version": "0.1.AI_BUILD",
"description": "Добавляет реакции на комментарии в локальном Redmine.",
"permissions": [
"storage",
@ -13,7 +13,8 @@
"content_scripts": [
{
"matches": ["https://red.eltex.loc/issues/*"],
"js": ["src/content.tsx"]
"js": ["src/content.tsx"],
"run_at": "document_start"
}
],
"browser_specific_settings": {

@ -5,12 +5,9 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"build:firefox": "cp manifest-firefox.json manifest.json && tsc && vite build",
"package:firefox": "npm run build:firefox && web-ext build --source-dir dist/ --overwrite-dest",
"package:firefox-signed": "echo -e 'nameserver 1.1.1.1\noptions single-request-reopen' > /etc/resolv.conf && npm run build:firefox && web-ext sign --source-dir dist/ --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET",
"build:chrome": "cp manifest-chrome.json manifest.json && npm run build",
"package:chrome": "npm run build:chrome && crx3 dist/ --key redmine-reactions.pem --output dist/redmine-reactions.crx"
"build": "tsc && vite build --outDir build/dist --emptyOutDir",
"lint": "tsc --noEmit",
"sign:firefox": "web-ext sign --source-dir build/dist --artifacts-dir build/amo --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET"
},
"dependencies": {
"webextension-polyfill": "^0.10.0",

@ -0,0 +1,76 @@
import browser from 'webextension-polyfill';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
// Тип для ответа сервера, который мы ожидаем
type AllReactionsForIssue = {
[commentId: string]: {
[emoji: string]: string[];
};
};
// --- НАШ КЭШ ---
// Мы будем хранить Promise, а не сами данные.
let reactionsPromiseCache: Promise<AllReactionsForIssue> | null = null;
/**
* Получает все реакции для указанной задачи.
* Использует кэш на уровне модуля, чтобы избежать повторных запросов на одной странице.
*/
export async function fetchReactionsForIssue(issueId: number): Promise<AllReactionsForIssue> {
// Если Promise уже есть в кэше, просто возвращаем его.
if (reactionsPromiseCache) {
console.log('Serving reactions from cache.');
return reactionsPromiseCache;
}
console.log('Fetching reactions from network...');
// Если кэш пуст, создаем новый Promise, СОХРАНЯЕМ ЕГО В КЭШ, и возвращаем.
reactionsPromiseCache = fetch(`${API_BASE_URL}/api/reactions/${issueId}`)
.then(response => {
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
return response.json();
})
.catch(error => {
// В случае ошибки, очищаем кэш, чтобы можно было попробовать снова.
reactionsPromiseCache = null;
throw error;
});
return reactionsPromiseCache;
}
/**
* Получает анонимный ID пользователя из хранилища.
* (Переносим эту логику сюда, чтобы весь код, связанный с API/Storage, был в одном месте).
*/
export async function getAnonymousUserId(): Promise<string> {
const data = await browser.storage.local.get('userId');
if (data.userId) return data.userId;
const newUserId = crypto.randomUUID();
await browser.storage.local.set({ userId: newUserId });
return newUserId;
}
/**
* Отправляет запрос на добавление/удаление реакции.
*/
export async function toggleReactionApi(
issueId: number,
commentId: string,
emoji: string,
userId: string,
method: 'POST' | 'DELETE'
) {
return fetch(`${API_BASE_URL}/api/reactions`, {
method,
headers: {
'Content-Type': 'application/json',
'X-User-ID': userId,
},
body: JSON.stringify({ issueId, commentId, emoji }),
});
}

@ -1,20 +1,10 @@
import React, { useState, useEffect, useRef } from 'react';
import EmojiPicker, { EmojiClickData } from 'emoji-picker-react';
import browser from 'webextension-polyfill';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
import { fetchReactionsForIssue, getAnonymousUserId, toggleReactionApi } from '../api';
type CommentReactions = { [emoji: string]: string[] };
interface ReactionsProps { issueId: number; commentId: string; }
async function getAnonymousUserId(): Promise<string> {
const data = await browser.storage.local.get('userId');
if (data.userId) return data.userId;
const newUserId = crypto.randomUUID();
await browser.storage.local.set({ userId: newUserId });
return newUserId;
}
const Reactions: React.FC<ReactionsProps> = ({ issueId, commentId }) => {
const [reactions, setReactions] = useState<CommentReactions>({});
const [myUserId, setMyUserId] = useState<string | null>(null);
@ -25,16 +15,17 @@ const Reactions: React.FC<ReactionsProps> = ({ issueId, commentId }) => {
useEffect(() => {
const fetchData = async () => {
try {
const userId = await getAnonymousUserId();
const [userId, allReactions] = await Promise.all([
getAnonymousUserId(),
fetchReactionsForIssue(issueId)
]);
setMyUserId(userId);
const response = await fetch(`${API_BASE_URL}/api/reactions/${issueId}`);
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
if (data && data[commentId]) {
setReactions(data[commentId]);
if (allReactions && allReactions[commentId]) {
setReactions(allReactions[commentId]);
}
} catch (error) {
console.error("Failed to fetch reactions:", error);
console.error("Failed to fetch data:", error);
} finally {
setIsLoading(false);
}
@ -52,22 +43,22 @@ const Reactions: React.FC<ReactionsProps> = ({ issueId, commentId }) => {
const handleReactionClick = async (emoji: string) => {
if (!myUserId) return;
const currentReactions = reactions[emoji] || [];
const hasReacted = currentReactions.includes(myUserId);
const hasReacted = (reactions[emoji] || []).includes(myUserId);
const method = hasReacted ? 'DELETE' : 'POST';
const previousReactions = { ...reactions };
setReactions(prev => {
const newUsers = hasReacted ? (prev[emoji] || []).filter(id => id !== myUserId) : [...(prev[emoji] || []), myUserId];
const users = prev[emoji] || [];
const newUsers = hasReacted ? users.filter(id => id !== myUserId) : [...users, myUserId];
const newReactionsForComment = { ...prev, [emoji]: newUsers };
if (newReactionsForComment[emoji].length === 0) delete newReactionsForComment[emoji];
if (newReactionsForComment[emoji].length === 0) {
delete newReactionsForComment[emoji];
}
return newReactionsForComment;
});
try {
const response = await fetch(`${API_BASE_URL}/api/reactions`, {
method,
headers: { 'Content-Type': 'application/json', 'X-User-ID': myUserId },
body: JSON.stringify({ issueId, commentId, emoji }),
});
const response = await toggleReactionApi(issueId, commentId, emoji, myUserId, method);
if (!response.ok) throw new Error('Server returned an error');
} catch (error) {
console.error("Failed to update reaction:", error);
@ -80,7 +71,17 @@ const Reactions: React.FC<ReactionsProps> = ({ issueId, commentId }) => {
handleReactionClick(emojiData.emoji);
};
if (isLoading || !myUserId) return null;
if (isLoading) {
return (
<div style={styles.container}>
<div style={{ ...styles.skeleton, width: '50px' }}></div>
<div style={{ ...styles.skeleton, width: '45px' }}></div>
<div style={styles.addButtonSkeleton}></div>
</div>
);
}
if (!myUserId) return null;
return (
<div style={styles.container}>
@ -109,7 +110,7 @@ const Reactions: React.FC<ReactionsProps> = ({ issueId, commentId }) => {
};
const styles: { [key: string]: React.CSSProperties } = {
container: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '6px', marginTop: '8px', marginBottom: '8px', paddingLeft: '10px', fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif', fontSize: '13px' },
container: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '6px', marginTop: '8px', marginBottom: '8px', paddingLeft: '10px', fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif', fontSize: '13px', minHeight: '36px' },
badge: { display: 'flex', alignItems: 'center', padding: '2px 8px', border: '1px solid #dcdcdc', borderRadius: '12px', cursor: 'pointer', transition: 'background-color 0.2s', backgroundColor: '#f7f7f7' },
badgeSelected: { backgroundColor: '#e6f2ff', borderColor: '#99ccff' },
emoji: { marginRight: '4px', fontSize: '15px', lineHeight: '1' },
@ -117,6 +118,7 @@ const styles: { [key: string]: React.CSSProperties } = {
countSelected: { color: '#005cc5' },
addButton: { display: 'flex', alignItems: 'center', padding: '2px 8px', border: '1px dashed #ccc', borderRadius: '12px', backgroundColor: 'transparent', cursor: 'pointer', color: '#555', fontFamily: 'inherit', fontSize: '13px' },
pickerWrapper: { position: 'absolute', bottom: '100%', left: 0, marginBottom: '10px', zIndex: 1000 },
skeleton: { height: '26px', backgroundColor: '#eef0f2', borderRadius: '12px', animation: 'reactions-pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite' },
addButtonSkeleton: { height: '26px', width: '42px', backgroundColor: 'transparent', border: '1px dashed #e0e0e0', borderRadius: '12px' },
};
export default Reactions;

@ -2,40 +2,61 @@ import React from 'react';
import ReactDOM from 'react-dom/client';
import Reactions from './components/Reactions';
console.log('Redmine Reactions Extension Loaded!');
// Функция для извлечения ID задачи из URL
function getIssueId(): number | null {
const match = window.location.pathname.match(/\/issues\/(\d+)/);
return match && match[1] ? parseInt(match[1], 10) : null;
// --- Подготовка ---
// Создаем элемент <style>, но пока не вставляем его
const styleSheet = document.createElement("style");
styleSheet.innerText = `
@keyframes reactions-pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
`;
// Флаг, чтобы убедиться, что стили вставляются только один раз
let stylesInjected = false;
function processCommentContainer(container: HTMLElement) {
if (container.dataset.reactionsInitialized) return;
container.dataset.reactionsInitialized = 'true';
const issueIdMatch = window.location.pathname.match(/\/issues\/(\d+)/);
if (!issueIdMatch) return;
const issueId = parseInt(issueIdMatch[1], 10);
const noteElement = container.querySelector<HTMLElement>('div[id^="note-"]');
if (!noteElement) return;
const commentId = noteElement.id;
const reactionRootEl = document.createElement('div');
reactionRootEl.style.minHeight = '36px'; // Резервируем место
container.appendChild(reactionRootEl);
const root = ReactDOM.createRoot(reactionRootEl);
root.render(
<React.StrictMode>
<Reactions issueId={issueId} commentId={commentId} />
</React.StrictMode>
);
}
// Находим все блоки с комментариями на странице
const commentContainers = document.querySelectorAll('div.journal.has-notes');
const issueId = getIssueId();
if (issueId) {
commentContainers.forEach(container => {
// Находим вложенный div с ID комментария
const noteElement = container.querySelector<HTMLDivElement>('div[id^="note-"]');
if (!noteElement) return;
const commentId = noteElement.id;
// Создаем div, в который будем рендерить наш React-компонент
const reactionRootEl = document.createElement('div');
reactionRootEl.className = 'reactions-app-root';
// Вставляем наш div в конец контейнера, как вы и определили
container.appendChild(reactionRootEl);
// Создаем React-root и рендерим компонент
const root = ReactDOM.createRoot(reactionRootEl);
root.render(
<React.StrictMode>
<Reactions issueId={issueId} commentId={commentId} />
</React.StrictMode>
);
});
}
const observer = new MutationObserver((mutations) => {
if (!stylesInjected && document.head) {
document.head.appendChild(styleSheet);
stylesInjected = true;
}
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node instanceof HTMLElement) {
if (node.matches('div.journal.has-notes')) {
processCommentContainer(node);
}
node.querySelectorAll<HTMLElement>('div.journal.has-notes').forEach(processCommentContainer);
}
}
}
});
observer.observe(document, {
childList: true,
subtree: true,
});

Loading…
Cancel
Save