imio.omnia.tinymce 1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. imio/omnia/tinymce/__init__.py +6 -0
  2. imio/omnia/tinymce/browser/__init__.py +0 -0
  3. imio/omnia/tinymce/browser/action.py +6 -0
  4. imio/omnia/tinymce/browser/configure.zcml +40 -0
  5. imio/omnia/tinymce/browser/controlpanel.py +93 -0
  6. imio/omnia/tinymce/browser/npm/package-lock.json +125 -0
  7. imio/omnia/tinymce/browser/npm/package.json +8 -0
  8. imio/omnia/tinymce/browser/overrides/.gitkeep +0 -0
  9. imio/omnia/tinymce/browser/resources/.env.example +13 -0
  10. imio/omnia/tinymce/browser/resources/.git +1 -0
  11. imio/omnia/tinymce/browser/resources/.gitignore +26 -0
  12. imio/omnia/tinymce/browser/resources/.gitlab-ci.yml +77 -0
  13. imio/omnia/tinymce/browser/resources/.storybook/main.js +124 -0
  14. imio/omnia/tinymce/browser/resources/.storybook/preview.js +8 -0
  15. imio/omnia/tinymce/browser/resources/CHANGELOG.md +19 -0
  16. imio/omnia/tinymce/browser/resources/CLAUDE.md +62 -0
  17. imio/omnia/tinymce/browser/resources/Makefile +28 -0
  18. imio/omnia/tinymce/browser/resources/README.md +327 -0
  19. imio/omnia/tinymce/browser/resources/dev/index.html +41 -0
  20. imio/omnia/tinymce/browser/resources/dev/vite.config.js +78 -0
  21. imio/omnia/tinymce/browser/resources/docs/images/example1.png +0 -0
  22. imio/omnia/tinymce/browser/resources/eslint.config.js +36 -0
  23. imio/omnia/tinymce/browser/resources/package-lock.json +4913 -0
  24. imio/omnia/tinymce/browser/resources/package.json +61 -0
  25. imio/omnia/tinymce/browser/resources/src/assets/ia-icon.svg +5 -0
  26. imio/omnia/tinymce/browser/resources/src/assets/omnia-icon.svg +10 -0
  27. imio/omnia/tinymce/browser/resources/src/client.js +239 -0
  28. imio/omnia/tinymce/browser/resources/src/config.js +220 -0
  29. imio/omnia/tinymce/browser/resources/src/plugin.js +158 -0
  30. imio/omnia/tinymce/browser/resources/src/shortcuts.js +92 -0
  31. imio/omnia/tinymce/browser/resources/src/ui/App.jsx +75 -0
  32. imio/omnia/tinymce/browser/resources/src/ui/FloatingPanel.jsx +375 -0
  33. imio/omnia/tinymce/browser/resources/src/ui/PanelHeader.jsx +15 -0
  34. imio/omnia/tinymce/browser/resources/src/ui/SidePanel.jsx +284 -0
  35. imio/omnia/tinymce/browser/resources/src/ui/StreamingText.jsx +143 -0
  36. imio/omnia/tinymce/browser/resources/src/ui/components.jsx +70 -0
  37. imio/omnia/tinymce/browser/resources/src/ui/mount.jsx +35 -0
  38. imio/omnia/tinymce/browser/resources/src/ui/omnia.css +35 -0
  39. imio/omnia/tinymce/browser/resources/src/utils.js +56 -0
  40. imio/omnia/tinymce/browser/resources/stories/FloatingPanel.stories.jsx +66 -0
  41. imio/omnia/tinymce/browser/resources/stories/SidePanel.stories.jsx +31 -0
  42. imio/omnia/tinymce/browser/resources/stories/StreamingText.stories.jsx +85 -0
  43. imio/omnia/tinymce/browser/resources/stories/TinyMCEEditor.stories.js +228 -0
  44. imio/omnia/tinymce/browser/resources/stories/TypingDots.stories.jsx +31 -0
  45. imio/omnia/tinymce/browser/resources/stories/mocks/editor.js +66 -0
  46. imio/omnia/tinymce/browser/resources/stories/mocks/omnia-client.js +99 -0
  47. imio/omnia/tinymce/browser/resources/stories/presets/accessibilite-reglement.html +49 -0
  48. imio/omnia/tinymce/browser/resources/stories/presets/ameliorer-communication.html +36 -0
  49. imio/omnia/tinymce/browser/resources/stories/presets/corriger-bulletin.html +186 -0
  50. imio/omnia/tinymce/browser/resources/stories/presets/long-cdld.html +12389 -0
  51. imio/omnia/tinymce/browser/resources/stories/presets/reduire-deliberation.html +87 -0
  52. imio/omnia/tinymce/browser/resources/stories/presets/traduire-guide.html +234 -0
  53. imio/omnia/tinymce/browser/resources/vite.config.js +27 -0
  54. imio/omnia/tinymce/browser/static/omnia-tinymce.css +1 -0
  55. imio/omnia/tinymce/browser/static/omnia-tinymce.js +22 -0
  56. imio/omnia/tinymce/browser/templates/omnia_config.pt +10 -0
  57. imio/omnia/tinymce/browser/viewlets.py +57 -0
  58. imio/omnia/tinymce/configure.zcml +42 -0
  59. imio/omnia/tinymce/interfaces.py +7 -0
  60. imio/omnia/tinymce/locales/README.rst +37 -0
  61. imio/omnia/tinymce/locales/__init__.py +0 -0
  62. imio/omnia/tinymce/locales/en/LC_MESSAGES/imio.omnia.tinymce.po +83 -0
  63. imio/omnia/tinymce/locales/fr/LC_MESSAGES/imio.omnia.tinymce.po +83 -0
  64. imio/omnia/tinymce/locales/imio.omnia.tinymce.pot +86 -0
  65. imio/omnia/tinymce/locales/update.py +74 -0
  66. imio/omnia/tinymce/locales/update.sh +12 -0
  67. imio/omnia/tinymce/permissions.zcml +10 -0
  68. imio/omnia/tinymce/profiles/default/actions.xml +13 -0
  69. imio/omnia/tinymce/profiles/default/browserlayer.xml +7 -0
  70. imio/omnia/tinymce/profiles/default/catalog.xml +4 -0
  71. imio/omnia/tinymce/profiles/default/metadata.xml +7 -0
  72. imio/omnia/tinymce/profiles/default/registry/main.xml +35 -0
  73. imio/omnia/tinymce/profiles/default/rolemap.xml +7 -0
  74. imio/omnia/tinymce/profiles/uninstall/browserlayer.xml +7 -0
  75. imio/omnia/tinymce/setuphandlers.py +45 -0
  76. imio/omnia/tinymce/testing.py +48 -0
  77. imio/omnia/tinymce/tests/__init__.py +0 -0
  78. imio/omnia/tinymce/tests/robot/test_example.robot +66 -0
  79. imio/omnia/tinymce/tests/test_robot.py +28 -0
  80. imio/omnia/tinymce/tests/test_setup.py +68 -0
  81. imio/omnia/tinymce/tests/test_viewlet.py +99 -0
  82. imio.omnia.tinymce-1.0-py3.12-nspkg.pth +2 -0
  83. imio_omnia_tinymce-1.0.dist-info/METADATA +294 -0
  84. imio_omnia_tinymce-1.0.dist-info/RECORD +90 -0
  85. imio_omnia_tinymce-1.0.dist-info/WHEEL +5 -0
  86. imio_omnia_tinymce-1.0.dist-info/entry_points.txt +5 -0
  87. imio_omnia_tinymce-1.0.dist-info/licenses/LICENSE.GPL +339 -0
  88. imio_omnia_tinymce-1.0.dist-info/licenses/LICENSE.rst +15 -0
  89. imio_omnia_tinymce-1.0.dist-info/namespace_packages.txt +2 -0
  90. imio_omnia_tinymce-1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,158 @@
1
+ import tinymce from 'tinymce';
2
+ import omniaIcon from './assets/omnia-icon.svg?raw';
3
+ import { OmniaClient } from './client.js';
4
+ import { FEATURE_DEFS, registerOmniaOptions, resolveOmniaConfig } from './config.js';
5
+ import { mountOmniaUI } from './ui/mount.jsx';
6
+ import { bindShortcuts } from './shortcuts.js';
7
+
8
+ if (!tinymce) {
9
+ throw new Error('[omnia] tinymce is not available — the plugin must be loaded after TinyMCE.');
10
+ }
11
+
12
+ tinymce.PluginManager.add('omnia', (editor) => {
13
+ registerOmniaOptions(editor);
14
+
15
+ // Allow host pages to provide options via window.omnia_tinymce_settings
16
+ // when they cannot inject them directly into the tinymce.init() config
17
+ // (e.g. when TinyMCE is initialised inside a bundler-scoped module).
18
+ if (window.omnia_tinymce_settings) {
19
+ for (const [key, value] of Object.entries(window.omnia_tinymce_settings)) {
20
+ if (key.startsWith('omnia_') && !editor.options.isSet(key)) {
21
+ editor.options.set(key, value);
22
+ }
23
+ }
24
+ }
25
+
26
+ const baseUrl = editor.options.get('omnia_base_url');
27
+ if (!baseUrl) {
28
+ console.warn('[omnia] omnia_base_url is required');
29
+ return;
30
+ }
31
+
32
+ const config = resolveOmniaConfig(editor);
33
+ const enabledFeatureSet = new Set(config.enabledFeatures);
34
+
35
+ const client = new OmniaClient({
36
+ baseUrl,
37
+ application: config.application,
38
+ municipality: config.municipality,
39
+ authToken: config.authToken,
40
+ endpoints: config.endpoints,
41
+ onError: (err) => console.error('[omnia]', err),
42
+ });
43
+
44
+ let ui = null;
45
+ let shortcuts = null;
46
+
47
+ editor.on('init', () => {
48
+ ui = mountOmniaUI(editor, client, config);
49
+ shortcuts = bindShortcuts(editor, ui, config.shortcuts);
50
+ });
51
+
52
+ editor.on('remove', () => {
53
+ shortcuts?.destroy();
54
+ shortcuts = null;
55
+ ui?.destroy();
56
+ ui = null;
57
+ });
58
+
59
+ function hasSelection() {
60
+ const content = editor.selection.getContent({ format: 'text' });
61
+ return content && content.trim().length > 0;
62
+ }
63
+
64
+ function showFloating(action) {
65
+ if (enabledFeatureSet.has(action)) {
66
+ ui?.appRef.current?.showFloatingPanel(action);
67
+ }
68
+ }
69
+
70
+ function buildMainMenuItems() {
71
+ const sel = hasSelection();
72
+ const items = [];
73
+
74
+ if (enabledFeatureSet.has('generate')) {
75
+ items.push({
76
+ type: 'menuitem',
77
+ text: 'Générer du contenu',
78
+ onAction: () => ui?.appRef.current?.toggleSidePanel(),
79
+ });
80
+ }
81
+
82
+ const groups = [
83
+ ['improve-text', 'correct-text'],
84
+ ['expand-text', 'reduce-text'],
85
+ ['make-accessible', 'translate-text'],
86
+ ];
87
+
88
+ for (const group of groups) {
89
+ const groupFeatures = group
90
+ .filter((id) => enabledFeatureSet.has(id))
91
+ .map((id) => FEATURE_DEFS.find((f) => f.id === id))
92
+ .filter(Boolean);
93
+
94
+ if (groupFeatures.length === 0) continue;
95
+
96
+ if (items.length > 0) {
97
+ items.push({ type: 'separator' });
98
+ }
99
+
100
+ for (const feature of groupFeatures) {
101
+ items.push({
102
+ type: 'menuitem',
103
+ text: feature.label,
104
+ enabled: sel,
105
+ onAction: () => showFloating(feature.id),
106
+ });
107
+ }
108
+ }
109
+
110
+ return items;
111
+ }
112
+
113
+ if (config.toolbar && config.enabledFeatures.length > 0) {
114
+ editor.ui.registry.addIcon('omnia', omniaIcon);
115
+ editor.ui.registry.addMenuButton('omnia', {
116
+ icon: 'omnia',
117
+ tooltip: "Assistant Omnia d'iMio",
118
+ fetch: (callback) => callback(buildMainMenuItems()),
119
+ });
120
+ }
121
+
122
+ for (const feature of FEATURE_DEFS) {
123
+ if (!feature.menuItem || !enabledFeatureSet.has(feature.id)) {
124
+ continue;
125
+ }
126
+
127
+ editor.ui.registry.addMenuItem(feature.menuItem.id, {
128
+ icon: 'omnia',
129
+ text: feature.menuItem.text,
130
+ onAction: () => {
131
+ if (feature.menu === 'panel') {
132
+ ui?.appRef.current?.toggleSidePanel();
133
+ } else {
134
+ showFloating(feature.id);
135
+ }
136
+ },
137
+ });
138
+ }
139
+
140
+ if (config.contextMenu) {
141
+ editor.ui.registry.addContextMenu('omnia', {
142
+ update: () => {
143
+ if (hasSelection()) {
144
+ return FEATURE_DEFS.filter(
145
+ (feature) =>
146
+ feature.menu === 'floating' &&
147
+ feature.menuItem &&
148
+ enabledFeatureSet.has(feature.id),
149
+ )
150
+ .map((feature) => feature.menuItem.id)
151
+ .join(' ');
152
+ }
153
+
154
+ return enabledFeatureSet.has('generate') ? 'omnia-generate' : '';
155
+ },
156
+ });
157
+ }
158
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Keyboard shortcut bindings for Omnia actions.
3
+ *
4
+ * Shortcuts follow the pattern: Alt+<prefix>, then a single letter.
5
+ * Press Alt+<prefix>, release, then press the action letter within the configured delay.
6
+ * Selection-based actions only fire when text is selected in the editor.
7
+ *
8
+ * Uses raw addEventListener on the capture phase so events are caught
9
+ * before TinyMCE or other handlers can swallow them. Binds to both the
10
+ * TinyMCE iframe document and the main document.
11
+ */
12
+
13
+ /**
14
+ * Bind keyboard shortcuts to Omnia actions.
15
+ *
16
+ * @param {object} editor - TinyMCE editor instance
17
+ * @param {{ appRef: { current: object } }} ui - Mounted UI handle
18
+ * @param {{ enabled: boolean, prefix: string, timeoutMs: number, bindings: Record<string, string> }} config
19
+ * @returns {{ destroy: () => void }}
20
+ */
21
+ export function bindShortcuts(editor, ui, config) {
22
+ if (!config.enabled) {
23
+ return { destroy() {} };
24
+ }
25
+
26
+ const keyToAction = Object.fromEntries(
27
+ Object.entries(config.bindings).map(([action, key]) => [key, action]),
28
+ );
29
+
30
+ let awaitingAction = false;
31
+ let resetTimer = null;
32
+
33
+ function dispatch(action) {
34
+ if (action === 'generate') {
35
+ ui.appRef.current?.toggleSidePanel();
36
+ } else {
37
+ const content = editor.selection.getContent({ format: 'text' });
38
+ if (content && content.trim().length > 0) {
39
+ ui.appRef.current?.showFloatingPanel(action);
40
+ }
41
+ }
42
+ }
43
+
44
+ function onKeyDown(e) {
45
+ // Step 2: we're waiting for the action letter after Alt+O
46
+ if (awaitingAction) {
47
+ awaitingAction = false;
48
+ clearTimeout(resetTimer);
49
+
50
+ // Ignore if any modifier is held (user might be doing something else)
51
+ if (e.altKey || e.ctrlKey || e.metaKey) return;
52
+
53
+ const action = keyToAction[e.key.toLowerCase()];
54
+ if (action) {
55
+ e.preventDefault();
56
+ e.stopPropagation();
57
+ dispatch(action);
58
+ }
59
+ return;
60
+ }
61
+
62
+ // Step 1: detect Alt+<prefix> (use e.code for cross-platform consistency)
63
+ if (
64
+ e.altKey &&
65
+ !e.ctrlKey &&
66
+ !e.metaKey &&
67
+ e.code === `Key${config.prefix.toUpperCase()}`
68
+ ) {
69
+ e.preventDefault();
70
+ e.stopPropagation();
71
+ awaitingAction = true;
72
+ resetTimer = setTimeout(() => {
73
+ awaitingAction = false;
74
+ }, config.timeoutMs);
75
+ }
76
+ }
77
+
78
+ // Bind to the TinyMCE iframe document (capture phase to beat TinyMCE handlers)
79
+ const editorDoc = editor.getDoc();
80
+ editorDoc.addEventListener('keydown', onKeyDown, true);
81
+
82
+ // Bind to the main document (for when focus is on toolbar / Omnia panels)
83
+ document.addEventListener('keydown', onKeyDown, true);
84
+
85
+ return {
86
+ destroy() {
87
+ editorDoc.removeEventListener('keydown', onKeyDown, true);
88
+ document.removeEventListener('keydown', onKeyDown, true);
89
+ clearTimeout(resetTimer);
90
+ },
91
+ };
92
+ }
@@ -0,0 +1,75 @@
1
+ import { useState, useCallback, useImperativeHandle } from 'preact/hooks';
2
+ import { forwardRef } from 'preact/compat';
3
+ import { FloatingPanel } from './FloatingPanel';
4
+ import { SidePanel } from './SidePanel';
5
+ import './omnia.css';
6
+
7
+ /**
8
+ * Root Omnia UI component. Manages which panels are visible.
9
+ * Exposes control methods via ref.
10
+ */
11
+ export const App = forwardRef(function App({ editor, client, config }, ref) {
12
+ const [floatingAction, setFloatingAction] = useState(null);
13
+ const [sidePanelVisible, setSidePanelVisible] = useState(false);
14
+
15
+ // Expose imperative API to the plugin entry point
16
+ useImperativeHandle(ref, () => ({
17
+ showFloatingPanel(action) {
18
+ setFloatingAction(action);
19
+ },
20
+ hideFloatingPanel() {
21
+ setFloatingAction(null);
22
+ },
23
+ toggleSidePanel() {
24
+ setSidePanelVisible((v) => !v);
25
+ },
26
+ showSidePanel() {
27
+ setSidePanelVisible(true);
28
+ },
29
+ hideSidePanel() {
30
+ setSidePanelVisible(false);
31
+ },
32
+ }));
33
+
34
+ const handleFloatingClose = useCallback(() => {
35
+ setFloatingAction(null);
36
+ }, []);
37
+
38
+ const handleFloatingAccept = useCallback(
39
+ (text) => {
40
+ if (editor) {
41
+ editor.undoManager.transact(() => {
42
+ editor.selection.setContent(text);
43
+ });
44
+ editor.selection.collapse(false);
45
+ editor.focus();
46
+ }
47
+ },
48
+ [editor],
49
+ );
50
+
51
+ const handleSidePanelClose = useCallback(() => {
52
+ setSidePanelVisible(false);
53
+ }, []);
54
+
55
+ return (
56
+ <>
57
+ <FloatingPanel
58
+ editor={editor}
59
+ client={client}
60
+ config={config}
61
+ mode={config.floatingPanelMode}
62
+ action={floatingAction}
63
+ onClose={handleFloatingClose}
64
+ onAccept={handleFloatingAccept}
65
+ />
66
+ <SidePanel
67
+ editor={editor}
68
+ client={client}
69
+ config={config}
70
+ visible={sidePanelVisible}
71
+ onClose={handleSidePanelClose}
72
+ />
73
+ </>
74
+ );
75
+ });
@@ -0,0 +1,375 @@
1
+ import { useState, useEffect, useRef } from 'preact/hooks';
2
+ import { motion, AnimatePresence, useDragControls, useMotionValue } from 'motion/react';
3
+ import { LANGUAGES as DEFAULT_LANGUAGES } from '../config.js';
4
+ import { PanelHeader } from './PanelHeader';
5
+ import { TypingDots, Button, INPUT_CLASS, AIDisclaimer } from './components';
6
+
7
+ const ACTION_LABELS = {
8
+ 'expand-text': 'Développer',
9
+ 'improve-text': 'Améliorer',
10
+ 'reduce-text': 'Réduire',
11
+ 'correct-text': 'Corriger',
12
+ 'make-accessible': 'Rendre accessible',
13
+ 'translate-text': 'Traduire',
14
+ };
15
+
16
+ // Actions that auto-start without user input
17
+ const AUTO_START_ACTIONS = new Set([
18
+ 'improve-text',
19
+ 'correct-text',
20
+ 'make-accessible',
21
+ 'expand-text',
22
+ 'reduce-text',
23
+ ]);
24
+
25
+ const DEFAULT_INLINE_WIDTH = 380;
26
+ const BLUR_WIDTH = 560;
27
+
28
+ /**
29
+ * Floating panel anchored near the text selection.
30
+ *
31
+ * Two display modes (controlled via the `mode` prop):
32
+ * - "inline": compact panel positioned near the selection, transparent overlay
33
+ * - "blur": wider centred panel, blurred overlay
34
+ *
35
+ * @param {{
36
+ * editor: object,
37
+ * client: object,
38
+ * mode: 'inline'|'blur',
39
+ * action: string|null,
40
+ * onClose: () => void,
41
+ * onAccept: (text: string) => void,
42
+ * }} props
43
+ */
44
+ export function FloatingPanel({ editor, client, config = {}, mode = 'inline', action, onClose, onAccept }) {
45
+ const [status, setStatus] = useState('idle');
46
+ const [result, setResult] = useState('');
47
+ const [error, setError] = useState(null);
48
+
49
+ // Action-specific inputs
50
+ const [targetLang, setTargetLang] = useState(config.defaultLanguage ?? 'fr');
51
+ const languages = config.languages?.length ? config.languages : DEFAULT_LANGUAGES;
52
+
53
+ const panelRef = useRef(null);
54
+ const abortRef = useRef(null);
55
+ const acceptRef = useRef(null);
56
+
57
+ // Drag
58
+ const dragControls = useDragControls();
59
+ const dragX = useMotionValue(0);
60
+ const dragY = useMotionValue(0);
61
+
62
+ // Resize (user-driven)
63
+ const inlineWidth = config.floatingPanelWidth ?? DEFAULT_INLINE_WIDTH;
64
+ const isFullWidth = inlineWidth === 'full';
65
+ const defaultWidth = mode === 'blur' ? BLUR_WIDTH : (isFullWidth ? window.innerWidth - 32 : inlineWidth);
66
+ const [panelSize, setPanelSize] = useState({ width: defaultWidth, height: null });
67
+
68
+ function onResizePointerDown(e) {
69
+ e.preventDefault();
70
+ e.stopPropagation();
71
+ const startX = e.clientX;
72
+ const startY = e.clientY;
73
+ const startWidth = panelRef.current.offsetWidth;
74
+ const startHeight = panelRef.current.offsetHeight;
75
+
76
+ const onMove = (ev) => {
77
+ const newWidth = Math.max(280, Math.min(startWidth + ev.clientX - startX, window.innerWidth - 32));
78
+ const newHeight = Math.max(120, Math.min(startHeight + ev.clientY - startY, window.innerHeight - 32));
79
+ setPanelSize({ width: newWidth, height: newHeight });
80
+ };
81
+ const onUp = () => {
82
+ document.removeEventListener('pointermove', onMove);
83
+ document.removeEventListener('pointerup', onUp);
84
+ };
85
+ document.addEventListener('pointermove', onMove);
86
+ document.addEventListener('pointerup', onUp);
87
+ }
88
+
89
+ // Inline mode: position near the text selection
90
+ useEffect(() => {
91
+ if (mode !== 'inline' || !action || !panelRef.current || !editor) return;
92
+ const panel = panelRef.current;
93
+ const panelRect = panel.getBoundingClientRect();
94
+
95
+ const rng = editor.selection.getRng();
96
+ const selRect = rng.getBoundingClientRect();
97
+
98
+ const iframe = editor.iframeElement;
99
+ const iframeRect = iframe?.getBoundingClientRect() || { top: 0, left: 0 };
100
+
101
+ const selBottom = iframeRect.top + selRect.bottom;
102
+ const selTop = iframeRect.top + selRect.top;
103
+
104
+ let top = selBottom + 8;
105
+ if (top + panelRect.height > window.innerHeight - 16) {
106
+ top = selTop - panelRect.height - 8;
107
+ }
108
+ top = Math.max(8, top);
109
+
110
+ let left;
111
+ if (isFullWidth) {
112
+ left = 16;
113
+ } else {
114
+ const selLeft = iframeRect.left + selRect.left;
115
+ const selWidth = selRect.width;
116
+ left = selLeft + (selWidth - panelRect.width) / 2;
117
+ left = Math.max(8, Math.min(left, window.innerWidth - panelRect.width - 8));
118
+ }
119
+
120
+ panel.style.top = `${top}px`;
121
+ panel.style.left = `${left}px`;
122
+ }, [action, editor, status]);
123
+
124
+ // Blur mode: keep centred (re-runs on resize via panelSize dependency)
125
+ useEffect(() => {
126
+ if (mode !== 'blur' || !action || !panelRef.current) return;
127
+ const panel = panelRef.current;
128
+ const rect = panel.getBoundingClientRect();
129
+ panel.style.top = `${Math.max(16, (window.innerHeight - rect.height) / 2)}px`;
130
+ panel.style.left = `${Math.max(16, (window.innerWidth - rect.width) / 2)}px`;
131
+ }, [action, status, panelSize]);
132
+
133
+ // Keyboard: Escape to close, Enter to accept when done
134
+ const keyRef = useRef(null);
135
+ keyRef.current = (e) => {
136
+ if (e.key === 'Escape') {
137
+ handleClose();
138
+ }
139
+ if (e.key === 'Enter' && status === 'done') {
140
+ const tag = e.target?.tagName;
141
+ if (tag !== 'INPUT' && tag !== 'TEXTAREA' && tag !== 'SELECT') {
142
+ e.preventDefault();
143
+ handleAccept();
144
+ }
145
+ }
146
+ };
147
+
148
+ useEffect(() => {
149
+ if (!action) return;
150
+ const onKey = (e) => keyRef.current?.(e);
151
+ document.addEventListener('keydown', onKey);
152
+ return () => document.removeEventListener('keydown', onKey);
153
+ }, [action]);
154
+
155
+ // Reset state when a new action starts (skip on close to preserve exit animation position)
156
+ useEffect(() => {
157
+ if (!action) return;
158
+
159
+ setStatus('idle');
160
+ setResult('');
161
+ setError(null);
162
+ setTargetLang(config.defaultLanguage ?? 'fr');
163
+ setPanelSize({ width: defaultWidth, height: null });
164
+ dragX.set(0);
165
+ dragY.set(0);
166
+
167
+ if (AUTO_START_ACTIONS.has(action)) {
168
+ startAction();
169
+ } else if (action) {
170
+ // Auto-focus the first input/select in the panel
171
+ requestAnimationFrame(() => {
172
+ const el = panelRef.current?.querySelector('.omnia-input, .omnia-select');
173
+ el?.focus();
174
+ });
175
+ }
176
+ }, [action]);
177
+
178
+ // Focus the accept button when result is ready
179
+ useEffect(() => {
180
+ if (status === 'done') {
181
+ acceptRef.current?.focus();
182
+ }
183
+ }, [status]);
184
+
185
+ function handleClose() {
186
+ abortRef.current?.abort();
187
+ onClose();
188
+ }
189
+
190
+ async function startAction() {
191
+ const selectedText = editor.selection.getContent({ format: 'html' });
192
+ if (!selectedText) return;
193
+
194
+ abortRef.current?.abort();
195
+ const controller = new AbortController();
196
+ abortRef.current = controller;
197
+
198
+ setStatus('streaming');
199
+ setError(null);
200
+ setResult('');
201
+
202
+ try {
203
+ let text;
204
+ if (action === 'expand-text') {
205
+ text = await client.expandText(selectedText, { signal: controller.signal });
206
+ } else if (action === 'improve-text') {
207
+ text = await client.improveText(selectedText, { signal: controller.signal });
208
+ } else if (action === 'reduce-text') {
209
+ text = await client.reduceText(selectedText, { signal: controller.signal });
210
+ } else if (action === 'correct-text') {
211
+ text = await client.correctText(selectedText, { signal: controller.signal });
212
+ } else if (action === 'make-accessible') {
213
+ text = await client.makeAccessible(selectedText, { signal: controller.signal });
214
+ } else if (action === 'translate-text') {
215
+ text = await client.translateText(selectedText, targetLang, { signal: controller.signal });
216
+ }
217
+ if (!controller.signal.aborted) {
218
+ setResult(text);
219
+ setStatus('done');
220
+ }
221
+ } catch (err) {
222
+ if (err.name !== 'AbortError') {
223
+ setError(err.message);
224
+ setStatus('error');
225
+ }
226
+ }
227
+ }
228
+
229
+ function handleAccept() {
230
+ if (result) {
231
+ onAccept(result);
232
+ }
233
+ onClose();
234
+ }
235
+
236
+ if (action && config.enabledFeatures && !config.enabledFeatures.includes(action)) {
237
+ return null;
238
+ }
239
+
240
+ const backdropClass = mode === 'blur'
241
+ ? 'omnia-backdrop om:fixed om:inset-0 om:z-[10000] om:bg-black/15 om:backdrop-blur-[2px]'
242
+ : 'omnia-backdrop om:fixed om:inset-0 om:z-[10000] om:bg-black/5';
243
+
244
+ const maxPreviewHeight = mode === 'blur' ? ' om:max-h-[50vh] om:overflow-y-auto' : ' om:max-h-[300px] om:overflow-y-auto';
245
+
246
+ return (
247
+ <AnimatePresence>
248
+ {action && (
249
+ <>
250
+ {/* Backdrop overlay */}
251
+ <motion.div
252
+ key="backdrop"
253
+ className={backdropClass}
254
+ data-omnia
255
+ initial={{ opacity: 0 }}
256
+ animate={{ opacity: 1 }}
257
+ exit={{ opacity: 0 }}
258
+ transition={{ duration: 0.15 }}
259
+ onMouseDown={handleClose}
260
+ />
261
+ <motion.div
262
+ key={action}
263
+ ref={panelRef}
264
+ className="omnia-floating-panel omnia-panel om:fixed om:z-[10001] om:max-w-[calc(100vw-16px)] om:font-sans om:text-sm om:leading-relaxed om:text-gray-800 om:bg-white om:border om:border-gray-200 om:rounded-lg om:shadow-lg om:box-border om:flex om:flex-col om:overflow-hidden"
265
+ data-omnia
266
+ style={{ x: dragX, y: dragY, width: panelSize.width, ...(panelSize.height ? { height: panelSize.height } : {}) }}
267
+ drag={mode !== 'blur'}
268
+ dragListener={false}
269
+ dragControls={dragControls}
270
+ dragTransition={{ power: 0.1, timeConstant: 80 }}
271
+ dragConstraints={{ left: -window.innerWidth / 2, right: window.innerWidth / 2, top: -window.innerHeight / 2, bottom: window.innerHeight / 2 }}
272
+ dragElastic={0.1}
273
+ initial={{ opacity: 0, scale: 0.95 }}
274
+ animate={{ opacity: 1, scale: 1 }}
275
+ exit={{ opacity: 0, scale: 0.95 }}
276
+ transition={{ duration: 0.15, ease: 'easeOut' }}
277
+ >
278
+ <div
279
+ class={`omnia-panel__header om:flex om:shrink-0 om:items-center om:justify-between om:px-3 om:py-2.5 om:border-b om:border-gray-100 om:select-none${mode !== 'blur' ? ' om:cursor-grab om:active:cursor-grabbing' : ''}`}
280
+ onPointerDown={mode !== 'blur' ? (e) => dragControls.start(e) : undefined}
281
+ >
282
+ <PanelHeader title={ACTION_LABELS[action] || action} />
283
+ <Button variant="icon" onClick={handleClose} aria-label="Close">✕</Button>
284
+ </div>
285
+
286
+ <div class={`omnia-panel__body om:p-3${panelSize.height ? ' om:flex-1 om:min-h-0 om:overflow-y-auto' : ''}`}>
287
+ {/* translate-text: language picker */}
288
+ {action === 'translate-text' && status === 'idle' && (
289
+ <div class="omnia-floating-panel__input-row om:flex om:gap-1.5 om:mb-2">
290
+ <select
291
+ class={`omnia-select om:flex-1 ${INPUT_CLASS}`}
292
+ value={targetLang}
293
+ onChange={(e) => setTargetLang(e.target.value)}
294
+ onKeyDown={(e) => {
295
+ if (e.key === 'Enter') startAction();
296
+ }}
297
+ >
298
+ {languages.map((l) => (
299
+ <option key={l.code} value={l.code}>
300
+ {l.label}
301
+ </option>
302
+ ))}
303
+ </select>
304
+ <Button variant="primary" onClick={startAction}>Traduire</Button>
305
+ </div>
306
+ )}
307
+
308
+ <div class={`omnia-stream-preview om:font-sans om:text-sm om:leading-relaxed om:text-gray-800 om:p-2 om:break-words${panelSize.height ? '' : maxPreviewHeight}`}>
309
+ {status === 'streaming' && (
310
+ <div class="om:flex om:justify-center om:py-4">
311
+ <TypingDots />
312
+ </div>
313
+ )}
314
+ {status === 'done' && result && (
315
+ <motion.div
316
+ className="omnia-stream-preview__text"
317
+ initial={{ opacity: 0 }}
318
+ animate={{ opacity: 1 }}
319
+ transition={{ duration: 0.2 }}
320
+ dangerouslySetInnerHTML={{ __html: result }}
321
+ />
322
+ )}
323
+ {status === 'error' && (
324
+ <motion.div
325
+ className="omnia-stream-preview__error om:flex om:items-center om:gap-2 om:text-red-600 om:text-[13px] om:mt-2"
326
+ initial={{ opacity: 0, x: -4 }}
327
+ animate={{ opacity: 1, x: 0 }}
328
+ transition={{ duration: 0.2 }}
329
+ >
330
+ <span>{error || 'An error occurred'}</span>
331
+ <Button variant="secondary" size="sm" onClick={startAction}>
332
+ Réessayer
333
+ </Button>
334
+ </motion.div>
335
+ )}
336
+ </div>
337
+ </div>
338
+
339
+ <AnimatePresence>
340
+ {status === 'done' && (
341
+ <motion.div
342
+ className="omnia-panel__footer om:flex om:shrink-0 om:flex-col om:border-t om:border-gray-100"
343
+ initial={{ opacity: 0, y: 8 }}
344
+ animate={{ opacity: 1, y: 0 }}
345
+ exit={{ opacity: 0, y: 8 }}
346
+ transition={{ duration: 0.15 }}
347
+ >
348
+
349
+ <div class="om:flex om:items-center om:justify-end om:gap-1.5 om:px-3 om:pt-3">
350
+ <Button onClick={handleClose}>Annuler</Button>
351
+ <Button ref={acceptRef} variant="primary" onClick={handleAccept} disabled={status !== 'done'}>
352
+ Accepter
353
+ </Button>
354
+ </div>
355
+ <AIDisclaimer />
356
+ </motion.div>
357
+ )}
358
+ </AnimatePresence>
359
+
360
+ {/* Resize handle */}
361
+ <div
362
+ class="omnia-resize-handle om:absolute om:bottom-0 om:right-0 om:w-6 om:h-6 om:cursor-nwse-resize om:flex om:items-end om:justify-end om:p-1 om:text-gray-400 om:opacity-60 om:transition-opacity hover:om:opacity-100"
363
+ onPointerDown={onResizePointerDown}
364
+ >
365
+ <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
366
+ <path d="M9 1L1 9" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
367
+ <path d="M9 5L5 9" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>
368
+ </svg>
369
+ </div>
370
+ </motion.div>
371
+ </>
372
+ )}
373
+ </AnimatePresence>
374
+ );
375
+ }