hightjs 0.5.2 → 0.5.3

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 (48) hide show
  1. package/package.json +1 -1
  2. package/src/builder.js +8 -8
  3. package/src/hotReload.ts +4 -7
  4. package/src/router.ts +14 -26
  5. package/dist/adapters/express.d.ts +0 -7
  6. package/dist/adapters/express.js +0 -63
  7. package/dist/adapters/factory.d.ts +0 -23
  8. package/dist/adapters/factory.js +0 -122
  9. package/dist/adapters/fastify.d.ts +0 -25
  10. package/dist/adapters/fastify.js +0 -61
  11. package/dist/adapters/native.d.ts +0 -8
  12. package/dist/adapters/native.js +0 -198
  13. package/dist/api/console.d.ts +0 -94
  14. package/dist/api/console.js +0 -294
  15. package/dist/api/http.d.ts +0 -180
  16. package/dist/api/http.js +0 -469
  17. package/dist/bin/hightjs.d.ts +0 -2
  18. package/dist/bin/hightjs.js +0 -214
  19. package/dist/builder.d.ts +0 -32
  20. package/dist/builder.js +0 -581
  21. package/dist/client/DefaultNotFound.d.ts +0 -1
  22. package/dist/client/DefaultNotFound.js +0 -79
  23. package/dist/client/client.d.ts +0 -3
  24. package/dist/client/client.js +0 -24
  25. package/dist/client/clientRouter.d.ts +0 -58
  26. package/dist/client/clientRouter.js +0 -132
  27. package/dist/client/entry.client.d.ts +0 -1
  28. package/dist/client/entry.client.js +0 -455
  29. package/dist/components/Link.d.ts +0 -7
  30. package/dist/components/Link.js +0 -13
  31. package/dist/global/global.d.ts +0 -117
  32. package/dist/global/global.js +0 -17
  33. package/dist/helpers.d.ts +0 -20
  34. package/dist/helpers.js +0 -583
  35. package/dist/hotReload.d.ts +0 -32
  36. package/dist/hotReload.js +0 -548
  37. package/dist/index.d.ts +0 -18
  38. package/dist/index.js +0 -494
  39. package/dist/loaders.d.ts +0 -1
  40. package/dist/loaders.js +0 -46
  41. package/dist/renderer.d.ts +0 -14
  42. package/dist/renderer.js +0 -380
  43. package/dist/router.d.ts +0 -101
  44. package/dist/router.js +0 -667
  45. package/dist/types/framework.d.ts +0 -37
  46. package/dist/types/framework.js +0 -2
  47. package/dist/types.d.ts +0 -192
  48. package/dist/types.js +0 -2
@@ -1,24 +0,0 @@
1
- "use strict";
2
- /*
3
- * This file is part of the HightJS Project.
4
- * Copyright (c) 2025 itsmuzin
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.router = exports.Link = void 0;
20
- // Este arquivo exporta apenas código seguro para o cliente (navegador)
21
- var Link_1 = require("../components/Link");
22
- Object.defineProperty(exports, "Link", { enumerable: true, get: function () { return Link_1.Link; } });
23
- var clientRouter_1 = require("./clientRouter");
24
- Object.defineProperty(exports, "router", { enumerable: true, get: function () { return clientRouter_1.router; } });
@@ -1,58 +0,0 @@
1
- export interface RouterEvents {
2
- beforeNavigate?: (url: string) => boolean | Promise<boolean>;
3
- afterNavigate?: (url: string) => void;
4
- }
5
- declare class Router {
6
- private events;
7
- private listeners;
8
- /**
9
- * Navega para uma nova rota
10
- */
11
- push(url: string): Promise<void>;
12
- /**
13
- * Substitui a entrada atual do histórico
14
- */
15
- replace(url: string): Promise<void>;
16
- /**
17
- * Volta uma página no histórico
18
- */
19
- back(): void;
20
- /**
21
- * Avança uma página no histórico
22
- */
23
- forward(): void;
24
- /**
25
- * Recarrega a página atual (re-renderiza o componente)
26
- */
27
- refresh(): void;
28
- /**
29
- * Obtém a URL atual
30
- */
31
- get pathname(): string;
32
- /**
33
- * Obtém os query parameters atuais
34
- */
35
- get query(): URLSearchParams;
36
- /**
37
- * Obtém a URL completa atual
38
- */
39
- get url(): string;
40
- /**
41
- * Adiciona event listeners para eventos de roteamento
42
- */
43
- on(events: RouterEvents): void;
44
- /**
45
- * Remove event listeners
46
- */
47
- off(): void;
48
- /**
49
- * Adiciona um listener para mudanças de rota
50
- */
51
- subscribe(listener: () => void): () => void;
52
- /**
53
- * Dispara evento de navegação para todos os listeners
54
- */
55
- private triggerNavigation;
56
- }
57
- export declare const router: Router;
58
- export default router;
@@ -1,132 +0,0 @@
1
- "use strict";
2
- /*
3
- * This file is part of the HightJS Project.
4
- * Copyright (c) 2025 itsmuzin
5
- *
6
- * Licensed under the Apache License, Version 2.0 (the "License");
7
- * you may not use this file except in compliance with the License.
8
- * You may obtain a copy of the License at
9
- *
10
- * http://www.apache.org/licenses/LICENSE-2.0
11
- *
12
- * Unless required by applicable law or agreed to in writing, software
13
- * distributed under the License is distributed on an "AS IS" BASIS,
14
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- * See the License for the specific language governing permissions and
16
- * limitations under the License.
17
- */
18
- // Sistema de roteamento do lado do cliente para hweb-sdk
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.router = void 0;
21
- class Router {
22
- constructor() {
23
- this.events = {};
24
- this.listeners = new Set();
25
- }
26
- /**
27
- * Navega para uma nova rota
28
- */
29
- async push(url) {
30
- // Callback antes de navegar
31
- if (this.events.beforeNavigate) {
32
- const shouldProceed = await this.events.beforeNavigate(url);
33
- if (shouldProceed === false)
34
- return;
35
- }
36
- // Atualiza a URL na barra de endereço
37
- window.history.pushState({ path: url }, '', url);
38
- // Dispara evento para o roteador capturar de forma assíncrona
39
- setTimeout(() => this.triggerNavigation(), 0);
40
- // Callback após navegar
41
- if (this.events.afterNavigate) {
42
- this.events.afterNavigate(url);
43
- }
44
- }
45
- /**
46
- * Substitui a entrada atual do histórico
47
- */
48
- async replace(url) {
49
- // Callback antes de navegar
50
- if (this.events.beforeNavigate) {
51
- const shouldProceed = await this.events.beforeNavigate(url);
52
- if (shouldProceed === false)
53
- return;
54
- }
55
- // Substitui a URL atual no histórico
56
- window.history.replaceState({ path: url }, '', url);
57
- // Dispara evento para o roteador capturar de forma assíncrona
58
- setTimeout(() => this.triggerNavigation(), 0);
59
- // Callback após navegar
60
- if (this.events.afterNavigate) {
61
- this.events.afterNavigate(url);
62
- }
63
- }
64
- /**
65
- * Volta uma página no histórico
66
- */
67
- back() {
68
- window.history.back();
69
- }
70
- /**
71
- * Avança uma página no histórico
72
- */
73
- forward() {
74
- window.history.forward();
75
- }
76
- /**
77
- * Recarrega a página atual (re-renderiza o componente)
78
- */
79
- refresh() {
80
- setTimeout(() => this.triggerNavigation(), 0);
81
- }
82
- /**
83
- * Obtém a URL atual
84
- */
85
- get pathname() {
86
- return window.location.pathname;
87
- }
88
- /**
89
- * Obtém os query parameters atuais
90
- */
91
- get query() {
92
- return new URLSearchParams(window.location.search);
93
- }
94
- /**
95
- * Obtém a URL completa atual
96
- */
97
- get url() {
98
- return window.location.href;
99
- }
100
- /**
101
- * Adiciona event listeners para eventos de roteamento
102
- */
103
- on(events) {
104
- this.events = { ...this.events, ...events };
105
- }
106
- /**
107
- * Remove event listeners
108
- */
109
- off() {
110
- this.events = {};
111
- }
112
- /**
113
- * Adiciona um listener para mudanças de rota
114
- */
115
- subscribe(listener) {
116
- this.listeners.add(listener);
117
- return () => this.listeners.delete(listener);
118
- }
119
- /**
120
- * Dispara evento de navegação para todos os listeners
121
- */
122
- triggerNavigation() {
123
- // Dispara o evento nativo para o roteador do hweb capturar
124
- window.dispatchEvent(new PopStateEvent('popstate'));
125
- // Notifica todos os listeners customizados
126
- this.listeners.forEach(listener => listener());
127
- }
128
- }
129
- // Instância singleton do router
130
- exports.router = new Router();
131
- // Para compatibilidade, também exporta como default
132
- exports.default = exports.router;
@@ -1 +0,0 @@
1
- export {};
@@ -1,455 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- const jsx_runtime_1 = require("react/jsx-runtime");
37
- /*
38
- * This file is part of the HightJS Project.
39
- * Copyright (c) 2025 itsmuzin
40
- *
41
- * Licensed under the Apache License, Version 2.0 (the "License");
42
- * you may not use this file except in compliance with the License.
43
- * You may obtain a copy of the License at
44
- *
45
- * http://www.apache.org/licenses/LICENSE-2.0
46
- *
47
- * Unless required by applicable law or agreed to in writing, software
48
- * distributed under the License is distributed on an "AS IS" BASIS,
49
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
50
- * See the License for the specific language governing permissions and
51
- * limitations under the License.
52
- */
53
- const react_1 = __importStar(require("react"));
54
- const client_1 = require("react-dom/client");
55
- const clientRouter_1 = require("./clientRouter");
56
- function App({ componentMap, routes, initialComponentPath, initialParams, layoutComponent }) {
57
- // Estado que guarda o componente a ser renderizado atualmente
58
- const [hmrTimestamp, setHmrTimestamp] = (0, react_1.useState)(Date.now());
59
- // Helper para encontrar rota baseado no path
60
- const findRouteForPath = (0, react_1.useCallback)((path) => {
61
- for (const route of routes) {
62
- const regexPattern = route.pattern
63
- // [[...param]] → opcional catch-all
64
- .replace(/\[\[\.\.\.(\w+)\]\]/g, '(?<$1>.+)?')
65
- // [...param] → obrigatório catch-all
66
- .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)')
67
- // /[[param]] → opcional com barra também opcional
68
- .replace(/\/\[\[(\w+)\]\]/g, '(?:/(?<$1>[^/]+))?')
69
- // [[param]] → segmento opcional (sem barra anterior)
70
- .replace(/\[\[(\w+)\]\]/g, '(?<$1>[^/]+)?')
71
- // [param] → segmento obrigatório
72
- .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)');
73
- const regex = new RegExp(`^${regexPattern}/?$`);
74
- const match = path.match(regex);
75
- if (match) {
76
- return {
77
- componentPath: route.componentPath,
78
- params: match.groups || {}
79
- };
80
- }
81
- }
82
- return null;
83
- }, [routes]);
84
- // Inicializa o componente e params baseado na URL ATUAL (não no initialComponentPath)
85
- const [CurrentPageComponent, setCurrentPageComponent] = (0, react_1.useState)(() => {
86
- // Pega a rota atual da URL
87
- const currentPath = window.location.pathname;
88
- const match = findRouteForPath(currentPath);
89
- if (match) {
90
- return componentMap[match.componentPath];
91
- }
92
- // Se não encontrou rota, retorna null para mostrar 404
93
- return null;
94
- });
95
- const [params, setParams] = (0, react_1.useState)(() => {
96
- // Pega os params da URL atual
97
- const currentPath = window.location.pathname;
98
- const match = findRouteForPath(currentPath);
99
- return match ? match.params : {};
100
- });
101
- // HMR: Escuta eventos de hot reload
102
- (0, react_1.useEffect)(() => {
103
- // Ativa o sistema de HMR
104
- window.__HWEB_HMR__ = true;
105
- const handleHMRUpdate = async (event) => {
106
- const { file, timestamp } = event.detail;
107
- const fileName = file ? file.split('/').pop()?.split('\\').pop() : 'unknown';
108
- console.log('🔥 HMR: Hot reloading...', fileName);
109
- try {
110
- // Aguarda um pouco para o esbuild terminar de recompilar
111
- await new Promise(resolve => setTimeout(resolve, 300));
112
- // Re-importa o módulo principal com cache busting
113
- const mainScript = document.querySelector('script[src*="main.js"]');
114
- if (mainScript) {
115
- const mainSrc = mainScript.src.split('?')[0];
116
- const cacheBustedSrc = `${mainSrc}?t=${timestamp}`;
117
- // Cria novo script
118
- const newScript = document.createElement('script');
119
- newScript.type = 'module';
120
- newScript.src = cacheBustedSrc;
121
- // Quando o novo script carregar, força re-render
122
- newScript.onload = () => {
123
- console.log('✅ HMR: Modules reloaded');
124
- // Força re-render do componente
125
- setHmrTimestamp(timestamp);
126
- // Marca sucesso
127
- window.__HMR_SUCCESS__ = true;
128
- setTimeout(() => {
129
- window.__HMR_SUCCESS__ = false;
130
- }, 3000);
131
- };
132
- newScript.onerror = () => {
133
- console.error('❌ HMR: Failed to reload modules');
134
- window.__HMR_SUCCESS__ = false;
135
- };
136
- // Remove o script antigo e adiciona o novo
137
- // (não remove para não quebrar o app)
138
- document.head.appendChild(newScript);
139
- }
140
- else {
141
- // Se não encontrou o script, apenas força re-render
142
- console.log('⚡ HMR: Forcing re-render');
143
- setHmrTimestamp(timestamp);
144
- window.__HMR_SUCCESS__ = true;
145
- }
146
- }
147
- catch (error) {
148
- console.error('❌ HMR Error:', error);
149
- window.__HMR_SUCCESS__ = false;
150
- }
151
- };
152
- window.addEventListener('hmr:component-update', handleHMRUpdate);
153
- return () => {
154
- window.removeEventListener('hmr:component-update', handleHMRUpdate);
155
- };
156
- }, []);
157
- const updateRoute = (0, react_1.useCallback)(() => {
158
- const currentPath = clientRouter_1.router.pathname;
159
- const match = findRouteForPath(currentPath);
160
- if (match) {
161
- setCurrentPageComponent(() => componentMap[match.componentPath]);
162
- setParams(match.params);
163
- }
164
- else {
165
- // Se não encontrou rota, define como null para mostrar 404
166
- setCurrentPageComponent(null);
167
- setParams({});
168
- }
169
- }, [clientRouter_1.router.pathname, findRouteForPath, componentMap]);
170
- // Ouve os eventos de "voltar" e "avançar" do navegador
171
- (0, react_1.useEffect)(() => {
172
- const handlePopState = () => {
173
- updateRoute();
174
- };
175
- window.addEventListener('popstate', handlePopState);
176
- // Também se inscreve no router para mudanças de rota
177
- const unsubscribe = clientRouter_1.router.subscribe(updateRoute);
178
- return () => {
179
- window.removeEventListener('popstate', handlePopState);
180
- unsubscribe();
181
- };
182
- }, [updateRoute]);
183
- // Se não há componente ou é a rota __404__, mostra página 404
184
- if (!CurrentPageComponent || initialComponentPath === '__404__') {
185
- // Usa o componente 404 personalizado se existir, senão usa o padrão do hweb
186
- const NotFoundComponent = window.__HWEB_NOT_FOUND__;
187
- if (NotFoundComponent) {
188
- // Usa o notFound.tsx personalizado do usuário
189
- const NotFoundContent = (0, jsx_runtime_1.jsx)(NotFoundComponent, {});
190
- // Aplica o layout se existir
191
- if (layoutComponent) {
192
- return react_1.default.createElement(layoutComponent, { children: NotFoundContent });
193
- }
194
- return NotFoundContent;
195
- }
196
- else {
197
- // Usa o 404 padrão do hweb que foi incluído no build
198
- const DefaultNotFound = window.__HWEB_DEFAULT_NOT_FOUND__;
199
- const NotFoundContent = (0, jsx_runtime_1.jsx)(DefaultNotFound, {});
200
- // Aplica o layout se existir
201
- if (layoutComponent) {
202
- return react_1.default.createElement(layoutComponent, { children: NotFoundContent });
203
- }
204
- return NotFoundContent;
205
- }
206
- }
207
- // Renderiza o componente atual (sem Context, usa o router diretamente)
208
- // Usa key com timestamp para forçar re-mount durante HMR
209
- const PageContent = (0, jsx_runtime_1.jsx)(CurrentPageComponent, { params: params }, `page-${hmrTimestamp}`);
210
- // SEMPRE usa o layout - se não existir, cria um wrapper padrão
211
- const content = layoutComponent
212
- ? react_1.default.createElement(layoutComponent, { children: PageContent })
213
- : (0, jsx_runtime_1.jsx)("div", { children: PageContent });
214
- // Adiciona o indicador de dev se não for produção
215
- return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [content, process.env.NODE_ENV !== 'production' && (0, jsx_runtime_1.jsx)(DevIndicator, {})] }));
216
- }
217
- // --- Constantes de Configuração ---
218
- const DEV_INDICATOR_SIZE = 48;
219
- const DEV_INDICATOR_CORNERS = [
220
- { top: 16, left: 16 }, // 0: topo-esquerda
221
- { top: 16, right: 16 }, // 1: topo-direita
222
- { bottom: 16, left: 16 }, // 2: baixo-esquerda
223
- { bottom: 16, right: 16 }, // 3: baixo-direita
224
- ];
225
- function DevIndicator() {
226
- const [corner, setCorner] = (0, react_1.useState)(3); // Canto atual (0-3)
227
- const [isDragging, setIsDragging] = (0, react_1.useState)(false); // Estado de arrastar
228
- const [isBuilding, setIsBuilding] = (0, react_1.useState)(false); // Estado de build
229
- // Posição visual do indicador durante o arraste
230
- const [position, setPosition] = (0, react_1.useState)({ top: 0, left: 0 });
231
- const indicatorRef = (0, react_1.useRef)(null);
232
- const dragStartRef = (0, react_1.useRef)(null);
233
- // Escuta eventos de hot reload para mostrar estado de build
234
- (0, react_1.useEffect)(() => {
235
- if (typeof window === 'undefined')
236
- return;
237
- const handleHotReloadMessage = (event) => {
238
- try {
239
- const message = JSON.parse(event.data);
240
- // Quando detecta mudança em arquivo, ativa loading
241
- if (message.type === 'frontend-reload' ||
242
- message.type === 'backend-api-reload' ||
243
- message.type === 'src-reload') {
244
- setIsBuilding(true);
245
- }
246
- // Quando o build termina ou servidor fica pronto, desativa loading
247
- if (message.type === 'server-ready' || message.type === 'build-complete') {
248
- setIsBuilding(false);
249
- }
250
- }
251
- catch (e) {
252
- // Ignora mensagens que não são JSON
253
- }
254
- };
255
- // Intercepta mensagens WebSocket
256
- const originalWebSocket = window.WebSocket;
257
- window.WebSocket = class extends originalWebSocket {
258
- constructor(url, protocols) {
259
- super(url, protocols);
260
- this.addEventListener('message', (event) => {
261
- if (url.toString().includes('hweb-hotreload')) {
262
- handleHotReloadMessage(event);
263
- }
264
- });
265
- }
266
- };
267
- return () => {
268
- window.WebSocket = originalWebSocket;
269
- };
270
- }, []);
271
- // --- Estilos Dinâmicos ---
272
- const getIndicatorStyle = () => {
273
- const baseStyle = {
274
- position: 'fixed',
275
- zIndex: 9999,
276
- width: DEV_INDICATOR_SIZE,
277
- height: DEV_INDICATOR_SIZE,
278
- borderRadius: '50%',
279
- background: isBuilding
280
- ? 'linear-gradient(135deg, #f093fb, #f5576c)' // Gradiente Rosa/Vermelho quando building
281
- : 'linear-gradient(135deg, #8e2de2, #4a00e0)', // Gradiente Roxo normal
282
- color: 'white',
283
- fontWeight: 'bold',
284
- fontSize: 28,
285
- boxShadow: isBuilding
286
- ? '0 4px 25px rgba(245, 87, 108, 0.6)' // Shadow mais forte quando building
287
- : '0 4px 15px rgba(0,0,0,0.2)',
288
- display: 'flex',
289
- alignItems: 'center',
290
- justifyContent: 'center',
291
- cursor: isDragging ? 'grabbing' : 'grab',
292
- userSelect: 'none',
293
- transition: isDragging ? 'none' : 'all 0.3s ease-out',
294
- animation: isBuilding ? 'hweb-pulse 1.5s ease-in-out infinite' : 'none',
295
- };
296
- if (isDragging) {
297
- return {
298
- ...baseStyle,
299
- top: position.top,
300
- left: position.left,
301
- };
302
- }
303
- return { ...baseStyle, ...DEV_INDICATOR_CORNERS[corner] };
304
- };
305
- const getMenuPositionStyle = () => {
306
- // Posiciona o menu dependendo do canto
307
- switch (corner) {
308
- case 0: return { top: '110%', left: '0' }; // Top-Left
309
- case 1: return { top: '110%', right: '0' }; // Top-Right
310
- case 2: return { bottom: '110%', left: '0' }; // Bottom-Left
311
- case 3: return { bottom: '110%', right: '0' }; // Bottom-Right
312
- default: return {};
313
- }
314
- };
315
- // --- Lógica de Eventos ---
316
- const handleMouseDown = (e) => {
317
- e.preventDefault();
318
- dragStartRef.current = { x: e.clientX, y: e.clientY, moved: false };
319
- if (indicatorRef.current) {
320
- const rect = indicatorRef.current.getBoundingClientRect();
321
- setPosition({ top: rect.top, left: rect.left });
322
- }
323
- setIsDragging(true);
324
- };
325
- const handleMouseMove = (0, react_1.useCallback)((e) => {
326
- if (!isDragging || !dragStartRef.current)
327
- return;
328
- const deltaX = e.clientX - dragStartRef.current.x;
329
- const deltaY = e.clientY - dragStartRef.current.y;
330
- // Diferencia clique de arrastar (threshold de 5px)
331
- if (!dragStartRef.current.moved && Math.hypot(deltaX, deltaY) > 5) {
332
- dragStartRef.current.moved = true;
333
- }
334
- if (dragStartRef.current.moved) {
335
- setPosition(prevPos => ({
336
- top: prevPos.top + deltaY,
337
- left: prevPos.left + deltaX,
338
- }));
339
- // Atualiza a referência para o próximo movimento
340
- dragStartRef.current.x = e.clientX;
341
- dragStartRef.current.y = e.clientY;
342
- }
343
- }, [isDragging]);
344
- const handleMouseUp = (0, react_1.useCallback)((e) => {
345
- if (!isDragging)
346
- return;
347
- setIsDragging(false);
348
- // Se moveu, calcula o canto mais próximo
349
- if (dragStartRef.current?.moved) {
350
- const { clientX, clientY } = e;
351
- const w = window.innerWidth;
352
- const h = window.innerHeight;
353
- const dists = [
354
- Math.hypot(clientX, clientY), // TL
355
- Math.hypot(w - clientX, clientY), // TR
356
- Math.hypot(clientX, h - clientY), // BL
357
- Math.hypot(w - clientX, h - clientY), // BR
358
- ];
359
- setCorner(dists.indexOf(Math.min(...dists)));
360
- }
361
- dragStartRef.current = null;
362
- }, [isDragging]);
363
- // Adiciona e remove listeners globais
364
- (0, react_1.useEffect)(() => {
365
- if (isDragging) {
366
- window.addEventListener('mousemove', handleMouseMove);
367
- window.addEventListener('mouseup', handleMouseUp);
368
- }
369
- return () => {
370
- window.removeEventListener('mousemove', handleMouseMove);
371
- window.removeEventListener('mouseup', handleMouseUp);
372
- };
373
- }, [isDragging, handleMouseMove, handleMouseUp]);
374
- return ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("style", { children: `
375
- @keyframes hweb-pulse {
376
- 0%, 100% {
377
- transform: scale(1);
378
- opacity: 1;
379
- }
380
- 50% {
381
- transform: scale(1.1);
382
- opacity: 0.8;
383
- }
384
- }
385
-
386
- @keyframes hweb-spin {
387
- from {
388
- transform: rotate(0deg);
389
- }
390
- to {
391
- transform: rotate(360deg);
392
- }
393
- }
394
- ` }), (0, jsx_runtime_1.jsx)("div", { ref: indicatorRef, style: getIndicatorStyle(), onMouseDown: handleMouseDown, title: isBuilding ? "Building..." : "Modo Dev HightJS", children: isBuilding ? ((0, jsx_runtime_1.jsx)("span", { style: { animation: 'hweb-spin 1s linear infinite' }, children: "\u27F3" })) : ('H') })] }));
395
- }
396
- // --- Inicialização do Cliente (CSR - Client-Side Rendering) ---
397
- function deobfuscateData(obfuscated) {
398
- try {
399
- // Remove o hash fake
400
- const parts = obfuscated.split('.');
401
- const base64 = parts.length > 1 ? parts[1] : parts[0];
402
- // Decodifica base64
403
- const jsonStr = atob(base64);
404
- // Parse JSON
405
- return JSON.parse(jsonStr);
406
- }
407
- catch (error) {
408
- console.error('[hweb] Failed to decode data:', error);
409
- return null;
410
- }
411
- }
412
- function initializeClient() {
413
- // Lê os dados do atributo data-h
414
- const dataElement = document.getElementById('__hight_data__');
415
- if (!dataElement) {
416
- console.error('[hweb] Initial data script not found.');
417
- return;
418
- }
419
- const obfuscated = dataElement.getAttribute('data-h');
420
- if (!obfuscated) {
421
- console.error('[hweb] Data attribute not found.');
422
- return;
423
- }
424
- const initialData = deobfuscateData(obfuscated);
425
- if (!initialData) {
426
- console.error('[hweb] Failed to parse initial data.');
427
- return;
428
- }
429
- // Cria o mapa de componentes dinamicamente a partir dos módulos carregados
430
- const componentMap = {};
431
- // Registra todos os componentes que foram importados
432
- if (window.__HWEB_COMPONENTS__) {
433
- Object.assign(componentMap, window.__HWEB_COMPONENTS__);
434
- }
435
- const container = document.getElementById('root');
436
- if (!container) {
437
- console.error('[hweb] Container #root not found.');
438
- return;
439
- }
440
- try {
441
- // Usar createRoot para render inicial (CSR)
442
- const root = (0, client_1.createRoot)(container);
443
- root.render((0, jsx_runtime_1.jsx)(App, { componentMap: componentMap, routes: initialData.routes, initialComponentPath: initialData.initialComponentPath, initialParams: initialData.initialParams, layoutComponent: window.__HWEB_LAYOUT__ }));
444
- }
445
- catch (error) {
446
- console.error('[hweb] Error rendering application:', error);
447
- }
448
- }
449
- // Executa quando o DOM estiver pronto
450
- if (document.readyState === 'loading') {
451
- document.addEventListener('DOMContentLoaded', initializeClient);
452
- }
453
- else {
454
- initializeClient();
455
- }
@@ -1,7 +0,0 @@
1
- import { type AnchorHTMLAttributes, type ReactNode } from 'react';
2
- interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
3
- href: string;
4
- children: ReactNode;
5
- }
6
- export declare function Link({ href, children, ...props }: LinkProps): import("react/jsx-runtime").JSX.Element;
7
- export {};