html2apk 0.3.0 → 0.4.0

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.
@@ -50,7 +50,7 @@ const i18n = {
50
50
  oneSignalAppId: "OneSignal App ID",
51
51
  oneSignalAppIdHint: "Opcional. Use o App ID do OneSignal, nao a REST API Key.",
52
52
  androidPermissions: "Permissoes Android",
53
- chooseIcon: "Escolher icone PNG",
53
+ chooseIcon: "Trocar icone PNG",
54
54
  reviewBuild: "Revisar build",
55
55
  debugBuild: "Debug tecnico",
56
56
  debugBuildText: "Mantem a pasta Cordova temporaria para inspecao.",
@@ -65,6 +65,7 @@ const i18n = {
65
65
  buildEyebrow: "Revisao",
66
66
  buildTitle: "Confirme as informacoes e gere o APK",
67
67
  startBuild: "Gerar APK",
68
+ startUsbDebug: "Testar no USB",
68
69
  stepFolder: "Pasta recebida",
69
70
  stepSettings: "Configuracoes completas",
70
71
  stepDoctor: "Ambiente verificado",
@@ -76,9 +77,16 @@ const i18n = {
76
77
  logsTitle: "Logs do processo",
77
78
  codesEyebrow: "Bridge nativa",
78
79
  codesTitle: "Codigos interpretados",
79
- codesIntro: "Estas funcoes chamadas no JavaScript do app sao interpretadas pelo plugin Cordova e executadas no Java Android.",
80
+ codesIntro: "Use estes blocos no JavaScript do seu projeto. O html2apk espera o Android ficar pronto, pede permissoes quando precisar e abre a configuracao certa quando o Android bloquear o pop-up.",
81
+ javaLabel: "Motor nativo",
82
+ doesLabel: "O que faz",
83
+ whenUseLabel: "Quando usar",
80
84
  returnsLabel: "Retorno",
81
85
  handlingLabel: "Como tratar",
86
+ exampleLabel: "Exemplo copiavel",
87
+ copyCode: "Copiar",
88
+ copiedCode: "Copiado",
89
+ copyFailed: "Nao foi possivel copiar",
82
90
  clearLogs: "Limpar logs",
83
91
  helpEyebrow: "Sem misterio",
84
92
  helpTitle: "Doctor, build e dependencias",
@@ -102,9 +110,15 @@ const i18n = {
102
110
  buildRunning: "Gerando APK",
103
111
  buildOk: "APK gerado com sucesso",
104
112
  buildFail: "Build falhou",
113
+ usbDebugRunning: "Gerando e instalando no celular USB",
114
+ usbDebugOk: "APK instalado no celular USB",
115
+ usbDebugFail: "Teste USB falhou",
105
116
  droppedFolder: "Pasta recebida",
106
117
  noFolderDrop: "Solte uma pasta do projeto",
107
118
  projectLoaded: "Projeto carregado",
119
+ projectAutoUpdated: "Projeto atualizado automaticamente",
120
+ projectConfigReloaded: "Configuracoes recarregadas do projeto",
121
+ projectWatcherFail: "Nao foi possivel acompanhar alteracoes da pasta",
108
122
  logsCleared: "Logs limpos",
109
123
  settingsOk: "Configuracoes completas",
110
124
  settingsMissing: "Complete as configuracoes obrigatorias",
@@ -114,7 +128,7 @@ const i18n = {
114
128
  invalidPackageId: "Informe um Package ID valido, exemplo: com.seuapp.meuapp.",
115
129
  invalidVersion: "Informe a versao no formato 1.0.0.",
116
130
  missingMode: "Escolha o modo do app.",
117
- missingIcon: "Escolha o icone do app.",
131
+ defaultIcon: "Icone padrao do html2apk",
118
132
  invalidIconType: "Use um icone PNG para evitar falhas no Android.",
119
133
  invalidThemeColor: "Use uma cor hexadecimal valida, exemplo: #126fff.",
120
134
  invalidOneSignalAppId: "Use um OneSignal App ID valido ou deixe vazio.",
@@ -141,6 +155,8 @@ const i18n = {
141
155
  successEyebrow: "Concluido",
142
156
  successTitle: "APK gerado com sucesso",
143
157
  successText: "Seu arquivo Android esta pronto na pasta dist.",
158
+ usbSuccessTitle: "APK instalado no celular",
159
+ usbSuccessText: "O build debug foi enviado por USB. O app deve abrir no aparelho conectado.",
144
160
  newBuild: "Novo build"
145
161
  },
146
162
  en: {
@@ -190,7 +206,7 @@ const i18n = {
190
206
  oneSignalAppId: "OneSignal App ID",
191
207
  oneSignalAppIdHint: "Optional. Use the OneSignal App ID, not the REST API Key.",
192
208
  androidPermissions: "Android permissions",
193
- chooseIcon: "Choose PNG icon",
209
+ chooseIcon: "Change PNG icon",
194
210
  reviewBuild: "Review build",
195
211
  debugBuild: "Technical debug",
196
212
  debugBuildText: "Keeps the temporary Cordova folder for inspection.",
@@ -205,6 +221,7 @@ const i18n = {
205
221
  buildEyebrow: "Review",
206
222
  buildTitle: "Confirm the information and build the APK",
207
223
  startBuild: "Build APK",
224
+ startUsbDebug: "Test on USB",
208
225
  stepFolder: "Folder received",
209
226
  stepSettings: "Settings complete",
210
227
  stepDoctor: "Environment checked",
@@ -216,9 +233,16 @@ const i18n = {
216
233
  logsTitle: "Process logs",
217
234
  codesEyebrow: "Native bridge",
218
235
  codesTitle: "Interpreted code",
219
- codesIntro: "These functions called in your app JavaScript are interpreted by the Cordova plugin and executed in Android Java.",
236
+ codesIntro: "Use these blocks in your project JavaScript. html2apk waits for Android to be ready, asks permissions when needed and opens the right settings screen when Android blocks the prompt.",
237
+ javaLabel: "Native engine",
238
+ doesLabel: "What it does",
239
+ whenUseLabel: "When to use",
220
240
  returnsLabel: "Returns",
221
241
  handlingLabel: "How to handle",
242
+ exampleLabel: "Copyable example",
243
+ copyCode: "Copy",
244
+ copiedCode: "Copied",
245
+ copyFailed: "Could not copy",
222
246
  clearLogs: "Clear logs",
223
247
  helpEyebrow: "Plain and simple",
224
248
  helpTitle: "Doctor, build and dependencies",
@@ -242,9 +266,15 @@ const i18n = {
242
266
  buildRunning: "Building APK",
243
267
  buildOk: "APK generated successfully",
244
268
  buildFail: "Build failed",
269
+ usbDebugRunning: "Building and installing on USB phone",
270
+ usbDebugOk: "APK installed on USB phone",
271
+ usbDebugFail: "USB test failed",
245
272
  droppedFolder: "Folder received",
246
273
  noFolderDrop: "Drop a project folder",
247
274
  projectLoaded: "Project loaded",
275
+ projectAutoUpdated: "Project updated automatically",
276
+ projectConfigReloaded: "Settings reloaded from project",
277
+ projectWatcherFail: "Could not watch folder changes",
248
278
  logsCleared: "Logs cleared",
249
279
  settingsOk: "Settings complete",
250
280
  settingsMissing: "Complete the required settings",
@@ -254,7 +284,7 @@ const i18n = {
254
284
  invalidPackageId: "Enter a valid Package ID, example: com.yourapp.name.",
255
285
  invalidVersion: "Enter the version as 1.0.0.",
256
286
  missingMode: "Choose the app mode.",
257
- missingIcon: "Choose the app icon.",
287
+ defaultIcon: "Default html2apk icon",
258
288
  invalidIconType: "Use a PNG icon to avoid Android build failures.",
259
289
  invalidThemeColor: "Use a valid hex color, example: #126fff.",
260
290
  invalidOneSignalAppId: "Use a valid OneSignal App ID or leave it empty.",
@@ -281,6 +311,8 @@ const i18n = {
281
311
  successEyebrow: "Complete",
282
312
  successTitle: "APK generated successfully",
283
313
  successText: "Your Android file is ready in the dist folder.",
314
+ usbSuccessTitle: "APK installed on phone",
315
+ usbSuccessText: "The debug build was sent over USB. The app should open on the connected device.",
284
316
  newBuild: "New build"
285
317
  }
286
318
  };
@@ -363,7 +395,7 @@ const nativeCodeEntries = [
363
395
  java: "notify",
364
396
  description: { pt: "Cria notificacao Android imediata. `acoes` ou `actions` viram botoes clicaveis.", en: "Creates an immediate Android notification. `actions` or `acoes` become clickable buttons." },
365
397
  returns: { pt: "Promise<void>; cliques chegam em `aoEvento('notificacao:clicada')` ou `aoClicarNotificacao()`.", en: "Promise<void>; clicks arrive through `onEvent('notification:clicked')` or `onNotificationClick()`." },
366
- handling: { pt: "Antes de usar, chame `solicitarPermissaoNotificacoes()` no Android 13+. Trate o clique pela acao enviada em `aoClicar`/`onClick`.", en: "Before using it, call `requestNotificationPermission()` on Android 13+. Handle clicks using the action sent in `onClick`/`aoClicar`." }
398
+ handling: { pt: "Ao chamar, o html2apk pede permissao automaticamente no Android 13+. Se o Android nao puder mostrar o pop-up, ele abre as configuracoes e retorna `settingsOpened`.", en: "When called, html2apk automatically requests permission on Android 13+. If Android cannot show the prompt, it opens settings and returns `settingsOpened`." }
367
399
  },
368
400
  {
369
401
  syntax: { pt: "agendarNotificacao({ titulo, texto, quando }) / agendarNotificacoes([...])", en: "scheduleNotification({ title, text, when }) / scheduleNotifications([...])" },
@@ -383,7 +415,7 @@ const nativeCodeEntries = [
383
415
  syntax: { pt: "solicitarPermissaoNotificacoes()", en: "requestNotificationPermission()" },
384
416
  java: "requestNotificationPermission",
385
417
  description: { pt: "Pede permissao para mostrar notificacoes quando o Android exigir.", en: "Requests permission to show notifications when Android requires it." },
386
- returns: { pt: "{ permission, required, granted }.", en: "{ permission, required, granted }." },
418
+ returns: { pt: "{ permission, required, granted, requiresSettings, settingsOpened }.", en: "{ permission, required, granted, requiresSettings, settingsOpened }." },
387
419
  handling: { pt: "Se `granted` for falso, desative botoes de notificacao ou explique ao usuario como habilitar depois.", en: "If `granted` is false, disable notification buttons or explain how the user can enable it later." }
388
420
  },
389
421
  {
@@ -398,7 +430,7 @@ const nativeCodeEntries = [
398
430
  java: "permissionStatus",
399
431
  description: { pt: "Consulta se permissoes Android estao liberadas.", en: "Checks whether Android permissions are granted." },
400
432
  returns: { pt: "Objeto com permissao Android como chave e boolean como valor.", en: "Object with Android permission names as keys and booleans as values." },
401
- handling: { pt: "Use antes de liberar recursos sensiveis; quando vier falso, mostre uma etapa de permissao em vez de falhar silenciosamente.", en: "Use it before enabling sensitive features; when false, show a permission step instead of failing silently." }
433
+ handling: { pt: "Use apenas para consultar. Para pedir permissao, chame a funcao real (`lanterna`, `ouvirMic`, `notificar`) ou a API manual correspondente.", en: "Use only to check. To request permission, call the real function (`flashlight`, `listenMic`, `notify`) or the matching manual API." }
402
434
  },
403
435
  {
404
436
  syntax: { pt: "aoEvento('app:background', fn)", en: "onEvent('app:background', fn)" },
@@ -424,23 +456,23 @@ const nativeCodeEntries = [
424
456
  {
425
457
  syntax: { pt: "solicitarPermissaoCamera()", en: "requestCameraPermission()" },
426
458
  java: "requestCameraPermission",
427
- description: { pt: "Pede permissao de camera antes de usar lanterna.", en: "Requests camera permission before using flashlight." },
428
- returns: { pt: "{ permission, required, granted }.", en: "{ permission, required, granted }." },
429
- handling: { pt: "Chame antes de `lanterna()`. Se `granted` for falso, mostre uma mensagem e mantenha a lanterna desativada.", en: "Call before `flashlight()`. If `granted` is false, show a message and keep the flashlight disabled." }
459
+ description: { pt: "Pede permissao de camera manualmente, se voce quiser preparar a experiencia antes da lanterna.", en: "Requests camera permission manually, if you want to prepare the experience before flashlight." },
460
+ returns: { pt: "{ permission, required, granted, requiresSettings, settingsOpened }.", en: "{ permission, required, granted, requiresSettings, settingsOpened }." },
461
+ handling: { pt: "`lanterna()` ja pede permissao sozinha. Use esta funcao apenas se quiser explicar antes e controlar a UI pelo `granted`.", en: "`flashlight()` already requests permission by itself. Use this only if you want to explain first and control the UI from `granted`." }
430
462
  },
431
463
  {
432
464
  syntax: { pt: "await ouvirMic(); const audio = await pararMic()", en: "await listenMic(); const audio = await stopMic()" },
433
465
  java: "MediaRecorder",
434
466
  description: { pt: "Comeca a gravar pelo microfone e finaliza retornando o audio em base64.", en: "Starts recording from the microphone and finishes by returning the audio as base64." },
435
- returns: { pt: "`ouvirMic`: { recording, startedAt, granted }. `pararMic`: { base64, mimeType, extension, durationMs, size }.", en: "`listenMic`: { recording, startedAt, granted }. `stopMic`: { base64, mimeType, extension, durationMs, size }." },
436
- handling: { pt: "Chame `solicitarPermissaoMicrofone()` ou deixe `ouvirMic()` pedir a permissao. Para tocar/enviar, monte `data:${audio.mimeType};base64,${audio.base64}`; se parar rapido demais, tente aguardar alguns instantes antes de `pararMic()`.", en: "Call `requestMicrophonePermission()` or let `listenMic()` request permission. To play/upload, build `data:${audio.mimeType};base64,${audio.base64}`; if you stop too quickly, wait a little before `stopMic()`." }
467
+ returns: { pt: "`ouvirMic`: { recording, startedAt, granted, settingsOpened }. `pararMic`: { base64, mimeType, extension, durationMs, size }.", en: "`listenMic`: { recording, startedAt, granted, settingsOpened }. `stopMic`: { base64, mimeType, extension, durationMs, size }." },
468
+ handling: { pt: "`ouvirMic()` pede microfone sozinho. Se `settingsOpened` vier true, o Android abriu as configuracoes; quando o usuario voltar, chame `ouvirMic()` de novo.", en: "`listenMic()` requests the microphone by itself. If `settingsOpened` is true, Android opened settings; when the user returns, call `listenMic()` again." }
437
469
  },
438
470
  {
439
471
  syntax: { pt: "lanterna(true) / statusLanterna()", en: "flashlight(true) / flashlightStatus()" },
440
472
  java: "flashlight",
441
473
  description: { pt: "Liga, desliga e consulta a lanterna do aparelho.", en: "Turns the device flashlight on/off and reads its status." },
442
474
  returns: { pt: "{ available, enabled, permissionGranted }.", en: "{ available, enabled, permissionGranted }." },
443
- handling: { pt: "Se `available` for falso, esconda o controle. Se `permissionGranted` for falso, volte para a etapa de permissao.", en: "If `available` is false, hide the control. If `permissionGranted` is false, return to the permission step." }
475
+ handling: { pt: "Ao chamar, o html2apk pede CAMERA automaticamente. Se `settingsOpened` vier true, o Android abriu as configuracoes porque o pop-up estava bloqueado.", en: "When called, html2apk automatically requests CAMERA. If `settingsOpened` is true, Android opened settings because the prompt was blocked." }
444
476
  },
445
477
  {
446
478
  syntax: { pt: "alternarLanterna()", en: "toggleFlashlight()" },
@@ -608,7 +640,624 @@ const nativeCodeEntries = [
608
640
  java: "FloatingIconService",
609
641
  description: { pt: "Controla o icone flutuante quando o app foi gerado em modo floating.", en: "Controls the floating icon when the app was generated in floating mode." },
610
642
  returns: { pt: "Promise<void>.", en: "Promise<void>." },
611
- handling: { pt: "Antes de iniciar, confira `statusPermissaoSobreposicao()` e chame `solicitarPermissaoSobreposicao()` se faltar permissao.", en: "Before starting, check `overlayPermissionStatus()` and call `requestOverlayPermission()` when permission is missing." }
643
+ handling: { pt: "`iniciarIconeFlutuante()` abre a tela de permissao automaticamente se faltar sobreposicao. Quando o usuario voltar, chame novamente para iniciar.", en: "`startFloatingIcon()` opens the permission screen automatically if draw-over-apps is missing. When the user comes back, call it again to start." }
644
+ }
645
+ ];
646
+
647
+ const nativeCodeRecipes = [
648
+ {
649
+ when: { pt: "Para avisos curtos dentro do app, como sucesso, erro simples ou confirmacao.", en: "For short in-app feedback such as success, simple errors or confirmations." },
650
+ example: {
651
+ pt: `try {
652
+ await toast("Salvo com sucesso");
653
+ } catch (erro) {
654
+ console.error("Toast falhou", erro);
655
+ }`,
656
+ en: `try {
657
+ await toast("Saved successfully");
658
+ } catch (error) {
659
+ console.error("Toast failed", error);
660
+ }`
661
+ }
662
+ },
663
+ {
664
+ when: { pt: "Para dar feedback fisico em botoes, alertas ou acoes importantes.", en: "For physical feedback on buttons, alerts or important actions." },
665
+ example: {
666
+ pt: `await vibrar(250);`,
667
+ en: `await vibrate(250);`
668
+ }
669
+ },
670
+ {
671
+ when: { pt: "Para mostrar uma notificacao agora. A permissao aparece automaticamente se o Android exigir.", en: "To show a notification now. Permission appears automatically if Android requires it." },
672
+ example: {
673
+ pt: `await notificar({
674
+ titulo: "Pedido aprovado",
675
+ texto: "Toque para abrir os detalhes",
676
+ aoClicar: { acao: "abrir-pedido", id: 123 }
677
+ });`,
678
+ en: `await notify({
679
+ title: "Order approved",
680
+ text: "Tap to open details",
681
+ onClick: { action: "open-order", id: 123 }
682
+ });`
683
+ }
684
+ },
685
+ {
686
+ when: { pt: "Para lembrar o usuario depois, mesmo se o app nao estiver aberto.", en: "To remind the user later, even if the app is not open." },
687
+ example: {
688
+ pt: `const aviso = await agendarNotificacao({
689
+ titulo: "Lembrete",
690
+ texto: "Volte ao app daqui 1 minuto",
691
+ quando: Date.now() + 60 * 1000
692
+ });
693
+
694
+ console.log("ID para cancelar depois:", aviso.id);`,
695
+ en: `const reminder = await scheduleNotification({
696
+ title: "Reminder",
697
+ text: "Come back in 1 minute",
698
+ when: Date.now() + 60 * 1000
699
+ });
700
+
701
+ console.log("ID to cancel later:", reminder.id);`
702
+ }
703
+ },
704
+ {
705
+ when: { pt: "Para uma sequencia recorrente de notificacoes, como a cada 12 horas.", en: "For a repeating sequence of notifications, such as every 12 hours." },
706
+ example: {
707
+ pt: `const loop = await agendarLoopNotificacoes({
708
+ aCada: "12h",
709
+ notificacoes: [
710
+ { titulo: "Agua", texto: "Beba agua agora" },
711
+ { titulo: "Alongar", texto: "Faca uma pausa rapida" }
712
+ ]
713
+ });
714
+
715
+ // Depois, se quiser parar:
716
+ // await cancelarNotificacao(loop.id);`,
717
+ en: `const loop = await scheduleNotificationLoop({
718
+ every: "12h",
719
+ notifications: [
720
+ { title: "Water", text: "Drink water now" },
721
+ { title: "Stretch", text: "Take a quick break" }
722
+ ]
723
+ });
724
+
725
+ // Later, to stop it:
726
+ // await cancelNotification(loop.id);`
727
+ }
728
+ },
729
+ {
730
+ when: { pt: "Opcional: use se quiser pedir a permissao antes de chamar notificacoes.", en: "Optional: use it if you want to ask permission before calling notifications." },
731
+ example: {
732
+ pt: `const permissao = await solicitarPermissaoNotificacoes();
733
+
734
+ if (!permissao.granted) {
735
+ if (permissao.settingsOpened) {
736
+ console.log("O Android abriu as configuracoes do app");
737
+ }
738
+ }`,
739
+ en: `const permission = await requestNotificationPermission();
740
+
741
+ if (!permission.granted) {
742
+ if (permission.settingsOpened) {
743
+ console.log("Android opened the app settings");
744
+ }
745
+ }`
746
+ }
747
+ },
748
+ {
749
+ when: { pt: "Para push remoto enviado pelo painel/API do OneSignal. Requer OneSignal App ID no build.", en: "For remote push sent by the OneSignal dashboard/API. Requires OneSignal App ID in the build." },
750
+ example: {
751
+ pt: `const permitido = await solicitarPermissaoPush();
752
+
753
+ if (permitido) {
754
+ await identificarUsuarioPush("usuario-123");
755
+ await adicionarTagPush("plano", "premium");
756
+ }
757
+
758
+ const parar = aoClicarPush((evento) => {
759
+ abrirNoApp("#/notificacoes");
760
+ });`,
761
+ en: `const allowed = await requestPushPermission();
762
+
763
+ if (allowed) {
764
+ await loginPushUser("user-123");
765
+ await addPushTag("plan", "premium");
766
+ }
767
+
768
+ const stop = onPushClick((event) => {
769
+ openInApp("#/notifications");
770
+ });`
771
+ }
772
+ },
773
+ {
774
+ when: { pt: "Para consultar permissoes sem abrir uma solicitacao na tela.", en: "To check permissions without opening a permission prompt." },
775
+ example: {
776
+ pt: `const permissoes = await statusPermissoes([
777
+ "CAMERA",
778
+ "RECORD_AUDIO",
779
+ "POST_NOTIFICATIONS"
780
+ ]);
781
+
782
+ console.log(permissoes);`,
783
+ en: `const permissions = await permissionStatus([
784
+ "CAMERA",
785
+ "RECORD_AUDIO",
786
+ "POST_NOTIFICATIONS"
787
+ ]);
788
+
789
+ console.log(permissions);`
790
+ }
791
+ },
792
+ {
793
+ when: { pt: "Para reagir a eventos do Android, como app indo para segundo plano ou clique em notificacao.", en: "To react to Android events, such as backgrounding or notification clicks." },
794
+ example: {
795
+ pt: `const parar = aoEvento("app:background", (evento) => {
796
+ console.log("Saiu da frente", evento.timestamp);
797
+ });
798
+
799
+ // Quando nao precisar mais:
800
+ // parar();`,
801
+ en: `const stop = onEvent("app:background", (event) => {
802
+ console.log("Moved to background", event.timestamp);
803
+ });
804
+
805
+ // When you no longer need it:
806
+ // stop();`
807
+ }
808
+ },
809
+ {
810
+ when: { pt: "Para pausar/resumir tarefas quando o usuario minimiza ou volta para o app.", en: "To pause/resume work when the user minimizes or returns to the app." },
811
+ example: {
812
+ pt: `const pararMinimizar = aoMinimizar(() => {
813
+ console.log("Pause videos, timers ou leituras pesadas");
814
+ });
815
+
816
+ const pararVoltar = aoVoltarParaApp(() => {
817
+ console.log("Atualize dados se precisar");
818
+ });`,
819
+ en: `const stopMinimize = onMinimize(() => {
820
+ console.log("Pause videos, timers or heavy reads");
821
+ });
822
+
823
+ const stopResume = onAppResume(() => {
824
+ console.log("Refresh data if needed");
825
+ });`
826
+ }
827
+ },
828
+ {
829
+ when: { pt: "Para abrir uma tela especifica quando o APK foi chamado por link.", en: "To open a specific screen when the APK was launched from a link." },
830
+ example: {
831
+ pt: `const linkInicial = await obterLinkInicial();
832
+ if (linkInicial) {
833
+ abrirNoApp("#" + linkInicial.path);
834
+ }
835
+
836
+ aoAbrirLink((link) => {
837
+ console.log("Link recebido", link.url);
838
+ });`,
839
+ en: `const initialLink = await getInitialLink();
840
+ if (initialLink) {
841
+ openInApp("#" + initialLink.path);
842
+ }
843
+
844
+ onOpenLink((link) => {
845
+ console.log("Link received", link.url);
846
+ });`
847
+ }
848
+ },
849
+ {
850
+ when: { pt: "Opcional: use antes da lanterna se quiser explicar a permissao ao usuario.", en: "Optional: use it before flashlight if you want to explain the permission." },
851
+ example: {
852
+ pt: `const camera = await solicitarPermissaoCamera();
853
+
854
+ if (camera.granted) {
855
+ await lanterna(true);
856
+ } else if (camera.settingsOpened) {
857
+ console.log("Libere Camera nas configuracoes e volte ao app");
858
+ }`,
859
+ en: `const camera = await requestCameraPermission();
860
+
861
+ if (camera.granted) {
862
+ await flashlight(true);
863
+ } else if (camera.settingsOpened) {
864
+ console.log("Allow Camera in settings and return to the app");
865
+ }`
866
+ }
867
+ },
868
+ {
869
+ when: { pt: "Para gravar audio curto pelo microfone e receber o arquivo em base64.", en: "To record short audio from the microphone and receive the file as base64." },
870
+ example: {
871
+ pt: `const inicio = await ouvirMic();
872
+ if (inicio.settingsOpened) {
873
+ console.log("Libere Microfone nas configuracoes e tente de novo");
874
+ return;
875
+ }
876
+
877
+ setTimeout(async () => {
878
+ const audio = await pararMic();
879
+ const url = "data:" + audio.mimeType + ";base64," + audio.base64;
880
+ new Audio(url).play();
881
+ }, 3000);`,
882
+ en: `const start = await listenMic();
883
+ if (start.settingsOpened) {
884
+ console.log("Allow Microphone in settings and try again");
885
+ return;
886
+ }
887
+
888
+ setTimeout(async () => {
889
+ const audio = await stopMic();
890
+ const url = "data:" + audio.mimeType + ";base64," + audio.base64;
891
+ new Audio(url).play();
892
+ }, 3000);`
893
+ }
894
+ },
895
+ {
896
+ when: { pt: "Para ligar ou desligar a lanterna. A permissao de camera e pedida automaticamente.", en: "To turn the flashlight on or off. Camera permission is requested automatically." },
897
+ example: {
898
+ pt: `const status = await lanterna(true);
899
+
900
+ if (status.settingsOpened) {
901
+ console.log("Libere Camera nas configuracoes e chame lanterna(true) de novo");
902
+ } else if (!status.available) {
903
+ await toast("Este aparelho nao tem lanterna");
904
+ }`,
905
+ en: `const status = await flashlight(true);
906
+
907
+ if (status.settingsOpened) {
908
+ console.log("Allow Camera in settings and call flashlight(true) again");
909
+ } else if (!status.available) {
910
+ await toast("This device has no flashlight");
911
+ }`
912
+ }
913
+ },
914
+ {
915
+ when: { pt: "Para um botao que liga/desliga a lanterna sem guardar estado manualmente.", en: "For a button that toggles flashlight without tracking state manually." },
916
+ example: {
917
+ pt: `const status = await alternarLanterna();
918
+ console.log("Lanterna ligada?", status.enabled);`,
919
+ en: `const status = await toggleFlashlight();
920
+ console.log("Flashlight on?", status.enabled);`
921
+ }
922
+ },
923
+ {
924
+ when: { pt: "Para deixar o usuario escolher uma foto da galeria ou arquivos de imagem.", en: "To let the user choose a photo from gallery or image files." },
925
+ example: {
926
+ pt: `const imagem = await escolherImagem();
927
+
928
+ if (imagem) {
929
+ document.querySelector("img.preview").src = imagem.uri;
930
+ }`,
931
+ en: `const image = await pickImage();
932
+
933
+ if (image) {
934
+ document.querySelector("img.preview").src = image.uri;
935
+ }`
936
+ }
937
+ },
938
+ {
939
+ when: { pt: "Para galeria com selecao multipla, como anexar varias fotos.", en: "For multiple gallery selection, such as attaching many photos." },
940
+ example: {
941
+ pt: `const imagens = await escolherImagens({ multiplo: true });
942
+
943
+ for (const imagem of imagens) {
944
+ console.log(imagem.nome, imagem.tamanho);
945
+ }`,
946
+ en: `const images = await pickImages({ multiple: true });
947
+
948
+ for (const image of images) {
949
+ console.log(image.name, image.size);
950
+ }`
951
+ }
952
+ },
953
+ {
954
+ when: { pt: "Para escolher PDF, ZIP, TXT ou qualquer tipo de documento.", en: "To choose PDF, ZIP, TXT or any document type." },
955
+ example: {
956
+ pt: `const pdf = await escolherArquivo({
957
+ tipos: ["application/pdf"]
958
+ });
959
+
960
+ if (pdf) {
961
+ console.log("PDF escolhido:", pdf.nome);
962
+ }`,
963
+ en: `const pdf = await pickFile({
964
+ types: ["application/pdf"]
965
+ });
966
+
967
+ if (pdf) {
968
+ console.log("Chosen PDF:", pdf.name);
969
+ }`
970
+ }
971
+ },
972
+ {
973
+ when: { pt: "Para anexar varios arquivos de uma vez.", en: "To attach multiple files at once." },
974
+ example: {
975
+ pt: `const arquivos = await escolherArquivos({ multiplo: true });
976
+
977
+ const total = arquivos.reduce((soma, arquivo) => {
978
+ return soma + (arquivo.tamanho || 0);
979
+ }, 0);
980
+
981
+ console.log("Total em bytes:", total);`,
982
+ en: `const files = await pickFiles({ multiple: true });
983
+
984
+ const total = files.reduce((sum, file) => {
985
+ return sum + (file.size || 0);
986
+ }, 0);
987
+
988
+ console.log("Total bytes:", total);`
989
+ }
990
+ },
991
+ {
992
+ when: { pt: "Para pedir um video do usuario sem mostrar documentos que nao sejam video.", en: "To ask the user for a video without showing non-video documents." },
993
+ example: {
994
+ pt: `const video = await escolherVideo();
995
+
996
+ if (video && video.tamanho > 50 * 1024 * 1024) {
997
+ await toast("Video muito grande");
998
+ }`,
999
+ en: `const video = await pickVideo();
1000
+
1001
+ if (video && video.size > 50 * 1024 * 1024) {
1002
+ await toast("Video is too large");
1003
+ }`
1004
+ }
1005
+ },
1006
+ {
1007
+ when: { pt: "Para o usuario escolher uma pasta quando o Android permitir acesso por URI.", en: "To let the user choose a folder when Android allows URI access." },
1008
+ example: {
1009
+ pt: `const pasta = await escolherPasta();
1010
+
1011
+ if (pasta.uri) {
1012
+ console.log("Pasta escolhida:", pasta.uri);
1013
+ }`,
1014
+ en: `const folder = await pickFolder();
1015
+
1016
+ if (folder.uri) {
1017
+ console.log("Chosen folder:", folder.uri);
1018
+ }`
1019
+ }
1020
+ },
1021
+ {
1022
+ when: { pt: "Para salvar texto ou base64 em um arquivo escolhido pelo usuario.", en: "To save text or base64 to a file chosen by the user." },
1023
+ example: {
1024
+ pt: `const salvo = await salvarArquivo({
1025
+ nome: "relatorio.txt",
1026
+ mimeType: "text/plain",
1027
+ conteudo: "Conteudo do relatorio"
1028
+ });
1029
+
1030
+ if (salvo.saved) {
1031
+ await toast("Arquivo salvo");
1032
+ }`,
1033
+ en: `const saved = await saveFile({
1034
+ name: "report.txt",
1035
+ mimeType: "text/plain",
1036
+ content: "Report content"
1037
+ });
1038
+
1039
+ if (saved.saved) {
1040
+ await toast("File saved");
1041
+ }`
1042
+ }
1043
+ },
1044
+ {
1045
+ when: { pt: "Para abrir o compartilhamento nativo do Android com texto e/ou link.", en: "To open Android native sharing with text and/or link." },
1046
+ example: {
1047
+ pt: `await compartilhar({
1048
+ texto: "Veja esse app",
1049
+ url: "https://exemplo.com"
1050
+ });`,
1051
+ en: `await share({
1052
+ text: "Check this app",
1053
+ url: "https://example.com"
1054
+ });`
1055
+ }
1056
+ },
1057
+ {
1058
+ when: { pt: "Para copiar dados para a area de transferencia ou ler o que esta copiado.", en: "To copy data to the clipboard or read what is copied." },
1059
+ example: {
1060
+ pt: `await copiarTexto("ABC-123");
1061
+ await toast("Codigo copiado");
1062
+
1063
+ const copiado = await lerTextoCopiado();
1064
+ console.log(copiado);`,
1065
+ en: `await copyText("ABC-123");
1066
+ await toast("Code copied");
1067
+
1068
+ const copied = await readText();
1069
+ console.log(copied);`
1070
+ }
1071
+ },
1072
+ {
1073
+ when: { pt: "Para impedir que a tela apague em leitura, video, mapa ou monitoramento.", en: "To keep screen awake during reading, video, maps or monitoring." },
1074
+ example: {
1075
+ pt: `await manterTelaLigada(true);
1076
+
1077
+ // Ao sair da tela:
1078
+ await manterTelaLigada(false);`,
1079
+ en: `await keepScreenOn(true);
1080
+
1081
+ // When leaving the screen:
1082
+ await keepScreenOn(false);`
1083
+ }
1084
+ },
1085
+ {
1086
+ when: { pt: "Para controlar o brilho so dentro do APK, sem mudar o brilho do sistema todo.", en: "To control brightness only inside the APK, without changing the whole system brightness." },
1087
+ example: {
1088
+ pt: `await brilhoTela(0.8);
1089
+
1090
+ // Restaurar comportamento padrao:
1091
+ await brilhoTela(-1);`,
1092
+ en: `await setScreenBrightness(0.8);
1093
+
1094
+ // Restore default behavior:
1095
+ await setScreenBrightness(-1);`
1096
+ }
1097
+ },
1098
+ {
1099
+ when: { pt: "Para combinar status bar/navigation bar com uma tela especifica do app.", en: "To match status/navigation bars with a specific app screen." },
1100
+ example: {
1101
+ pt: `await definirCorTema({
1102
+ statusBarColor: "#126fff",
1103
+ navigationBarColor: "#101827"
1104
+ });`,
1105
+ en: `await setThemeColor({
1106
+ statusBarColor: "#126fff",
1107
+ navigationBarColor: "#101827"
1108
+ });`
1109
+ }
1110
+ },
1111
+ {
1112
+ when: { pt: "Para navegar dentro do proprio WebView do APK.", en: "To navigate inside the APK WebView itself." },
1113
+ example: {
1114
+ pt: `await abrirNoApp("#/perfil");
1115
+
1116
+ // Sem deixar voltar para a tela anterior:
1117
+ await abrirNoApp("#/login", { substituir: true });`,
1118
+ en: `await openInApp("#/profile");
1119
+
1120
+ // Without keeping the previous screen:
1121
+ await openInApp("#/login", { replace: true });`
1122
+ }
1123
+ },
1124
+ {
1125
+ when: { pt: "Para abrir navegador, outro app ou link externo fora do APK.", en: "To open browser, another app or external link outside the APK." },
1126
+ example: {
1127
+ pt: `await abrirForaDoApp("https://exemplo.com");`,
1128
+ en: `await openOutsideApp("https://example.com");`
1129
+ }
1130
+ },
1131
+ {
1132
+ when: { pt: "Para abrir uma conversa do WhatsApp com numero e mensagem opcional.", en: "To open a WhatsApp conversation with phone number and optional message." },
1133
+ example: {
1134
+ pt: `await abrirWhatsapp(
1135
+ "559999999999",
1136
+ "Oi, vim pelo app"
1137
+ );`,
1138
+ en: `await openWhatsapp(
1139
+ "559999999999",
1140
+ "Hi, I came from the app"
1141
+ );`
1142
+ }
1143
+ },
1144
+ {
1145
+ when: { pt: "Para abrir o discador ou o app de mapas sem fazer a acao sozinho.", en: "To open dialer or maps without performing the action automatically." },
1146
+ example: {
1147
+ pt: `await discar("11999999999");
1148
+ await abrirMapa("Avenida Paulista, Sao Paulo");`,
1149
+ en: `await dial("11999999999");
1150
+ await openMap("Avenida Paulista, Sao Paulo");`
1151
+ }
1152
+ },
1153
+ {
1154
+ when: { pt: "Para diagnostico, suporte ou pequenas adaptacoes por versao do Android.", en: "For diagnostics, support or small adaptations by Android version." },
1155
+ example: {
1156
+ pt: `const aparelho = await infoDispositivo();
1157
+
1158
+ console.log(aparelho.modelo, aparelho.androidVersion);`,
1159
+ en: `const device = await deviceInfo();
1160
+
1161
+ console.log(device.model, device.androidVersion);`
1162
+ }
1163
+ },
1164
+ {
1165
+ when: { pt: "Para adaptar a UI quando ficar offline ou quando a bateria estiver baixa.", en: "To adapt the UI when offline or when battery is low." },
1166
+ example: {
1167
+ pt: `const rede = await infoRede();
1168
+ const bateria = await infoBateria();
1169
+
1170
+ if (!rede.online) {
1171
+ await toast("Sem internet");
1172
+ }`,
1173
+ en: `const network = await networkInfo();
1174
+ const battery = await batteryInfo();
1175
+
1176
+ if (!network.online) {
1177
+ await toast("No internet");
1178
+ }`
1179
+ }
1180
+ },
1181
+ {
1182
+ when: { pt: "Para saber se o app deve reduzir imagens, cache ou tarefas pesadas.", en: "To know whether the app should reduce images, cache or heavy tasks." },
1183
+ example: {
1184
+ pt: `const memoria = await infoMemoria();
1185
+ const mbLivre = memoria.availableBytes / 1024 / 1024;
1186
+
1187
+ if (memoria.lowMemory) {
1188
+ console.log("Reduza cache. MB livre:", mbLivre);
1189
+ }`,
1190
+ en: `const memory = await memoryInfo();
1191
+ const freeMb = memory.availableBytes / 1024 / 1024;
1192
+
1193
+ if (memory.lowMemory) {
1194
+ console.log("Reduce cache. Free MB:", freeMb);
1195
+ }`
1196
+ }
1197
+ },
1198
+ {
1199
+ when: { pt: "Para conferir espaco antes de baixar ou salvar arquivos grandes.", en: "To check space before downloading or saving large files." },
1200
+ example: {
1201
+ pt: `const armazenamento = await infoArmazenamento();
1202
+ const livre = armazenamento.internal.availableBytes;
1203
+
1204
+ console.log("Livre em MB:", Math.round(livre / 1024 / 1024));`,
1205
+ en: `const storage = await storageInfo();
1206
+ const free = storage.internal.availableBytes;
1207
+
1208
+ console.log("Free MB:", Math.round(free / 1024 / 1024));`
1209
+ }
1210
+ },
1211
+ {
1212
+ when: { pt: "Para uma tela de diagnostico com memoria, armazenamento, bateria e rede juntos.", en: "For a diagnostics screen with memory, storage, battery and network together." },
1213
+ example: {
1214
+ pt: `const desempenho = await infoDesempenho();
1215
+
1216
+ console.log(desempenho.memory);
1217
+ console.log(desempenho.storage);
1218
+ console.log(desempenho.battery);`,
1219
+ en: `const performance = await performanceInfo();
1220
+
1221
+ console.log(performance.memory);
1222
+ console.log(performance.storage);
1223
+ console.log(performance.battery);`
1224
+ }
1225
+ },
1226
+ {
1227
+ when: { pt: "Para diagnostico aproximado de processos que o Android deixa o APK enxergar.", en: "For approximate diagnostics of processes Android lets the APK see." },
1228
+ example: {
1229
+ pt: `const resultado = await appsAbertos();
1230
+
1231
+ for (const app of resultado.apps) {
1232
+ console.log(app.nome, app.ramMb + " MB");
1233
+ }`,
1234
+ en: `const result = await openAppsMemory();
1235
+
1236
+ for (const app of result.apps) {
1237
+ console.log(app.name, app.ramMb + " MB");
1238
+ }`
1239
+ }
1240
+ },
1241
+ {
1242
+ when: { pt: "Para apps em modo floating que precisam mostrar/esconder o icone flutuante.", en: "For floating-mode apps that need to show/hide the floating icon." },
1243
+ example: {
1244
+ pt: `const status = await iniciarIconeFlutuante();
1245
+
1246
+ if (status.requiresSettings) {
1247
+ console.log("O Android abriu a tela de sobreposicao");
1248
+ }
1249
+
1250
+ // Para desligar:
1251
+ // await pararIconeFlutuante();`,
1252
+ en: `const status = await startFloatingIcon();
1253
+
1254
+ if (status.requiresSettings) {
1255
+ console.log("Android opened the draw-over-apps screen");
1256
+ }
1257
+
1258
+ // To turn it off:
1259
+ // await stopFloatingIcon();`
1260
+ }
612
1261
  }
613
1262
  ];
614
1263
 
@@ -624,6 +1273,7 @@ const state = {
624
1273
  buildRunning: false,
625
1274
  lastApkPath: null,
626
1275
  lastDistPath: null,
1276
+ defaultIconPath: "",
627
1277
  animationTimer: null,
628
1278
  progress: 0,
629
1279
  logsVisible: localStorage.getItem("html2apk.logsVisible") === "true"
@@ -659,6 +1309,7 @@ function collectElements() {
659
1309
  "entryPath",
660
1310
  "doctorButton",
661
1311
  "buildButton",
1312
+ "usbDebugButton",
662
1313
  "appNameInput",
663
1314
  "packageIdInput",
664
1315
  "versionInput",
@@ -691,6 +1342,8 @@ function collectElements() {
691
1342
  "apkPath",
692
1343
  "openDistButton",
693
1344
  "showApkButton",
1345
+ "successTitle",
1346
+ "successText",
694
1347
  "successApkPath",
695
1348
  "successOpenDistButton",
696
1349
  "successShowApkButton",
@@ -874,6 +1527,7 @@ function updateActionButtons() {
874
1527
 
875
1528
  function setBuildButtons(enabled) {
876
1529
  elements.buildButton.disabled = !enabled;
1530
+ elements.usbDebugButton.disabled = !enabled;
877
1531
  }
878
1532
 
879
1533
  function packageSegment(value) {
@@ -900,12 +1554,16 @@ function toFileUrl(filePath) {
900
1554
  return `file:///${String(filePath).replace(/\\/g, "/").replace(/^\/+/, "")}`;
901
1555
  }
902
1556
 
1557
+ function defaultIconPath() {
1558
+ return state.defaultIconPath || "";
1559
+ }
1560
+
903
1561
  function isAbsolutePath(filePath) {
904
1562
  return /^[a-zA-Z]:[\\/]/.test(String(filePath || "")) || String(filePath || "").startsWith("/");
905
1563
  }
906
1564
 
907
1565
  function iconPreviewPath(iconPath) {
908
- if (!iconPath || !state.project) {
1566
+ if (!iconPath) {
909
1567
  return "../../../html2apk.png";
910
1568
  }
911
1569
  if (isAbsolutePath(iconPath)) {
@@ -914,6 +1572,18 @@ function iconPreviewPath(iconPath) {
914
1572
  return toFileUrl(`${state.project.projectRoot}\\${iconPath}`);
915
1573
  }
916
1574
 
1575
+ function displayIconValue(iconPath) {
1576
+ const value = String(iconPath || "").trim();
1577
+ if (!value || (state.defaultIconPath && value === state.defaultIconPath)) {
1578
+ return text("defaultIcon");
1579
+ }
1580
+ return value;
1581
+ }
1582
+
1583
+ function isConfigFilePath(filePath) {
1584
+ return /(^|[\\/])(app|config)\.json$/i.test(String(filePath || ""));
1585
+ }
1586
+
917
1587
  function escapeHtml(value) {
918
1588
  return String(value || "")
919
1589
  .replace(/&/g, "&amp;")
@@ -922,6 +1592,61 @@ function escapeHtml(value) {
922
1592
  .replace(/"/g, "&quot;");
923
1593
  }
924
1594
 
1595
+ function recipeForCode(index) {
1596
+ const language = currentLanguage();
1597
+ const recipe = nativeCodeRecipes[index] || {};
1598
+ return {
1599
+ when: recipe.when ? recipe.when[language] || recipe.when.pt : "",
1600
+ example: recipe.example ? recipe.example[language] || recipe.example.pt : ""
1601
+ };
1602
+ }
1603
+
1604
+ async function copyToClipboard(value) {
1605
+ const textValue = String(value || "");
1606
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1607
+ await navigator.clipboard.writeText(textValue);
1608
+ return;
1609
+ }
1610
+
1611
+ const textarea = document.createElement("textarea");
1612
+ textarea.value = textValue;
1613
+ textarea.setAttribute("readonly", "");
1614
+ textarea.style.position = "fixed";
1615
+ textarea.style.left = "-9999px";
1616
+ document.body.appendChild(textarea);
1617
+ textarea.select();
1618
+ document.execCommand("copy");
1619
+ textarea.remove();
1620
+ }
1621
+
1622
+ async function handleNativeCodeCopy(event) {
1623
+ const button = event.target.closest("[data-copy-code]");
1624
+ if (!button) {
1625
+ return;
1626
+ }
1627
+
1628
+ const index = Number.parseInt(button.dataset.copyCode, 10);
1629
+ const recipe = recipeForCode(index);
1630
+ if (!recipe.example) {
1631
+ return;
1632
+ }
1633
+
1634
+ const originalText = button.textContent;
1635
+ try {
1636
+ await copyToClipboard(recipe.example);
1637
+ button.textContent = text("copiedCode");
1638
+ button.classList.add("copied");
1639
+ } catch (error) {
1640
+ button.textContent = text("copyFailed");
1641
+ button.classList.add("copy-error");
1642
+ }
1643
+
1644
+ setTimeout(() => {
1645
+ button.textContent = originalText || text("copyCode");
1646
+ button.classList.remove("copied", "copy-error");
1647
+ }, 1400);
1648
+ }
1649
+
925
1650
  function selectedOptionText(select) {
926
1651
  if (!select || !select.selectedOptions || !select.selectedOptions.length) {
927
1652
  return select ? select.value : "";
@@ -1023,21 +1748,37 @@ function renderNativeCodeGrid() {
1023
1748
  }
1024
1749
 
1025
1750
  const language = currentLanguage();
1751
+ const javaLabel = text("javaLabel");
1752
+ const doesLabel = text("doesLabel");
1753
+ const whenUseLabel = text("whenUseLabel");
1026
1754
  const returnsLabel = text("returnsLabel");
1027
1755
  const handlingLabel = text("handlingLabel");
1028
- elements.nativeCodeGrid.innerHTML = nativeCodeEntries.map((entry) => {
1756
+ const exampleLabel = text("exampleLabel");
1757
+ const copyCodeLabel = text("copyCode");
1758
+ elements.nativeCodeGrid.innerHTML = nativeCodeEntries.map((entry, index) => {
1029
1759
  const syntax = entry.syntax ? entry.syntax[language] || entry.syntax.pt : entry.js;
1030
1760
  const description = entry.description[language] || entry.description.pt;
1031
1761
  const returns = entry.returns[language] || entry.returns.pt;
1032
1762
  const handling = entry.handling[language] || entry.handling.pt;
1763
+ const recipe = recipeForCode(index);
1033
1764
 
1034
1765
  return `
1035
1766
  <article class="code-card">
1036
- <code>${escapeHtml(syntax)}</code>
1037
- <span>Java: ${escapeHtml(entry.java)}</span>
1038
- <p>${escapeHtml(description)}</p>
1767
+ <div class="code-card-top">
1768
+ <code>${escapeHtml(syntax)}</code>
1769
+ <span>${escapeHtml(javaLabel)}: ${escapeHtml(entry.java)}</span>
1770
+ </div>
1771
+ <p><strong>${escapeHtml(doesLabel)}:</strong> ${escapeHtml(description)}</p>
1772
+ <small><strong>${escapeHtml(whenUseLabel)}:</strong> ${escapeHtml(recipe.when)}</small>
1039
1773
  <small><strong>${escapeHtml(returnsLabel)}:</strong> ${escapeHtml(returns)}</small>
1040
1774
  <small class="handling"><strong>${escapeHtml(handlingLabel)}:</strong> ${escapeHtml(handling)}</small>
1775
+ <div class="copy-example">
1776
+ <div class="copy-example-header">
1777
+ <strong>${escapeHtml(exampleLabel)}</strong>
1778
+ <button type="button" class="copy-code-button" data-copy-code="${index}">${escapeHtml(copyCodeLabel)}</button>
1779
+ </div>
1780
+ <pre><code>${escapeHtml(recipe.example)}</code></pre>
1781
+ </div>
1041
1782
  </article>
1042
1783
  `;
1043
1784
  }).join("");
@@ -1058,8 +1799,9 @@ function populateSettings(config = {}, project = state.project) {
1058
1799
  elements.themeColorTextInput.value = themeColor;
1059
1800
  elements.oneSignalAppIdInput.value = oneSignalAppIdFromConfig(config);
1060
1801
  renderPermissionOptions(Array.isArray(config.permissions) && config.permissions.length ? config.permissions : DEFAULT_PERMISSIONS);
1061
- elements.iconPathInput.value = config.icon || "";
1062
- elements.iconPreview.src = iconPreviewPath(config.icon || "");
1802
+ const iconPath = String(config.icon || "").trim() || defaultIconPath();
1803
+ elements.iconPathInput.value = iconPath;
1804
+ elements.iconPreview.src = iconPreviewPath(iconPath);
1063
1805
  elements.debugInput.checked = Boolean(config.debug);
1064
1806
  elements.releaseInput.checked = Boolean(config.release);
1065
1807
  }
@@ -1093,9 +1835,7 @@ function validateSettings() {
1093
1835
  if (!isValidOptionalOneSignalAppId(elements.oneSignalAppIdInput.value)) {
1094
1836
  errors.push(text("invalidOneSignalAppId"));
1095
1837
  }
1096
- if (!elements.iconPathInput.value.trim()) {
1097
- errors.push(text("missingIcon"));
1098
- } else if (!/\.png$/i.test(elements.iconPathInput.value.trim())) {
1838
+ if (elements.iconPathInput.value.trim() && !/\.png$/i.test(elements.iconPathInput.value.trim())) {
1099
1839
  errors.push(text("invalidIconType"));
1100
1840
  }
1101
1841
 
@@ -1142,7 +1882,7 @@ function renderReview() {
1142
1882
  [text("appThemeColor"), elements.themeColorTextInput.value.trim()],
1143
1883
  [text("oneSignalAppId"), elements.oneSignalAppIdInput.value.trim() || "-"],
1144
1884
  [text("androidPermissions"), selectedPermissions().join(", ")],
1145
- [text("appIcon"), elements.iconPathInput.value.trim()]
1885
+ [text("appIcon"), displayIconValue(elements.iconPathInput.value.trim())]
1146
1886
  ];
1147
1887
 
1148
1888
  elements.reviewGrid.innerHTML = items.map(([label, value]) => `
@@ -1305,22 +2045,67 @@ async function ensureEnvironmentBeforeSettings() {
1305
2045
  return ready;
1306
2046
  }
1307
2047
 
1308
- async function summarizeProject(project) {
2048
+ function renderProjectSnapshot(project) {
1309
2049
  state.project = project;
1310
- state.doctorOk = false;
1311
- state.environmentOk = false;
1312
- state.environmentChecking = false;
1313
- state.environmentFailed = false;
1314
- state.settingsValid = false;
1315
- state.lastApkPath = null;
1316
2050
  state.lastDistPath = project.distPath;
1317
-
1318
2051
  elements.projectSummary.classList.remove("hidden");
1319
2052
  elements.projectName.textContent = project.name;
1320
2053
  elements.projectPath.textContent = project.projectRoot;
1321
2054
  elements.configStatus.textContent = project.hasAppJson || project.hasConfigJson ? text("detected") : text("notDetected");
1322
2055
  elements.entryStatus.textContent = project.hasEntryFile ? text("detected") : text("missing");
1323
2056
  elements.entryPath.textContent = project.entryPath;
2057
+ }
2058
+
2059
+ async function watchCurrentProject() {
2060
+ if (!state.project || !api.watchProject) {
2061
+ return;
2062
+ }
2063
+
2064
+ try {
2065
+ const result = await api.watchProject(state.project.projectRoot);
2066
+ if (result && !result.ok) {
2067
+ appendLog(`${text("projectWatcherFail")}: ${result.message}`, "error");
2068
+ }
2069
+ } catch (error) {
2070
+ appendLog(`${text("projectWatcherFail")}: ${error.message}`, "error");
2071
+ }
2072
+ }
2073
+
2074
+ function applyProjectChange(payload) {
2075
+ if (!payload || !payload.project || !state.project) {
2076
+ return;
2077
+ }
2078
+
2079
+ if (payload.project.projectRoot !== state.project.projectRoot) {
2080
+ return;
2081
+ }
2082
+
2083
+ renderProjectSnapshot(payload.project);
2084
+
2085
+ const reloadSettings = isConfigFilePath(payload.changedPath);
2086
+ if (reloadSettings && !state.buildRunning) {
2087
+ populateSettings(payload.project.config || {}, payload.project);
2088
+ appendLog(text("projectConfigReloaded"), "system");
2089
+ } else {
2090
+ appendLog(`${text("projectAutoUpdated")}: ${payload.changedPath || payload.project.projectRoot}`, "system");
2091
+ }
2092
+
2093
+ setStep("folder", payload.project.hasEntryFile ? "done" : "active", payload.project.hasEntryFile ? text("folderReady") : text("missing"));
2094
+ validateSettings();
2095
+ if (document.querySelector(".nav-item.active")?.dataset.view === "build") {
2096
+ renderReview();
2097
+ }
2098
+ }
2099
+
2100
+ async function summarizeProject(project) {
2101
+ renderProjectSnapshot(project);
2102
+ state.doctorOk = false;
2103
+ state.environmentOk = false;
2104
+ state.environmentChecking = false;
2105
+ state.environmentFailed = false;
2106
+ state.settingsValid = false;
2107
+ state.lastApkPath = null;
2108
+
1324
2109
  elements.nextSettingsButton.disabled = false;
1325
2110
  elements.doctorButton.disabled = true;
1326
2111
  setBuildButtons(false);
@@ -1334,6 +2119,7 @@ async function summarizeProject(project) {
1334
2119
  appendLog(`${text("droppedFolder")}: ${project.projectRoot}`, "system");
1335
2120
  validateSettings();
1336
2121
  setProgress(project.hasEntryFile ? 25 : 15, project.hasEntryFile ? text("progressFolder") : text("missing"), project.hasEntryFile ? "" : "error");
2122
+ await watchCurrentProject();
1337
2123
  await ensureEnvironmentBeforeSettings();
1338
2124
  }
1339
2125
 
@@ -1451,6 +2237,8 @@ async function runBuildFlow() {
1451
2237
  state.lastApkPath = result.apkPath;
1452
2238
  state.lastDistPath = state.project.distPath;
1453
2239
  elements.apkPath.textContent = result.apkPath;
2240
+ elements.successTitle.textContent = text("successTitle");
2241
+ elements.successText.textContent = text("successText");
1454
2242
  elements.successApkPath.textContent = result.apkPath;
1455
2243
  elements.resultPanel.classList.remove("hidden");
1456
2244
  setStep("build", "done", text("buildOk"));
@@ -1470,6 +2258,74 @@ async function runBuildFlow() {
1470
2258
  }
1471
2259
  }
1472
2260
 
2261
+ async function runUsbDebugFlow() {
2262
+ if (!state.project || state.buildRunning) {
2263
+ setStatus("error", state.project ? text("usbDebugRunning") : text("chooseProjectFirst"));
2264
+ return;
2265
+ }
2266
+ if (!goToReview()) {
2267
+ return;
2268
+ }
2269
+
2270
+ showLogBar();
2271
+ state.buildRunning = true;
2272
+ updateActionButtons();
2273
+ elements.resultPanel.classList.add("hidden");
2274
+ setView("build");
2275
+ setStep("folder", "done", text("folderReady"));
2276
+
2277
+ const doctorOk = await runDoctorOnly();
2278
+ if (!doctorOk) {
2279
+ state.buildRunning = false;
2280
+ updateActionButtons();
2281
+ return;
2282
+ }
2283
+
2284
+ setStatus("busy", text("usbDebugRunning"));
2285
+ setStep("build", "active", text("usbDebugRunning"));
2286
+ setProgress(90, text("progressBuild"), "active");
2287
+ startAnimatedLogs();
2288
+
2289
+ try {
2290
+ const response = await api.runUsbDebugBuild(buildOptions());
2291
+ stopAnimatedLogs();
2292
+ if (!response.ok) {
2293
+ setStep("build", "error", text("usbDebugFail"));
2294
+ setStatus("error", text("usbDebugFail"));
2295
+ setProgress(90, text("progressError"), "error");
2296
+ appendLog(response.message || text("usbDebugFail"), "error");
2297
+ if (response.buildDir) {
2298
+ appendLog(`Build directory kept: ${response.buildDir}`, "system");
2299
+ }
2300
+ return;
2301
+ }
2302
+
2303
+ const result = response.result;
2304
+ state.lastApkPath = result.apkPath;
2305
+ state.lastDistPath = state.project.distPath;
2306
+ elements.apkPath.textContent = result.apkPath;
2307
+ elements.successTitle.textContent = text("usbSuccessTitle");
2308
+ elements.successText.textContent = text("usbSuccessText");
2309
+ elements.successApkPath.textContent = result.apkPath;
2310
+ elements.resultPanel.classList.remove("hidden");
2311
+ setStep("build", "done", text("usbDebugOk"));
2312
+ setStatus("ready", text("usbDebugOk"));
2313
+ setProgress(100, text("progressDone"));
2314
+ appendLog(`${text("usbDebugOk")}: ${result.device && result.device.id ? result.device.id : "Android USB"}`, "success");
2315
+ appendLog(`${text("buildOk")}: ${result.apkPath}`, "success");
2316
+ setView("success");
2317
+ } catch (error) {
2318
+ stopAnimatedLogs();
2319
+ setStep("build", "error", text("usbDebugFail"));
2320
+ setStatus("error", error.message);
2321
+ setProgress(90, text("progressError"), "error");
2322
+ appendLog(error.message, "error");
2323
+ } finally {
2324
+ state.buildRunning = false;
2325
+ updateActionButtons();
2326
+ }
2327
+ }
2328
+
1473
2329
  function toggleTheme() {
1474
2330
  state.theme = state.theme === "dark" ? "light" : "dark";
1475
2331
  applyTheme();
@@ -1519,6 +2375,7 @@ function bindEvents() {
1519
2375
  elements.settingsNextButton.addEventListener("click", goToReview);
1520
2376
  elements.doctorButton.addEventListener("click", runDoctorOnly);
1521
2377
  elements.buildButton.addEventListener("click", runBuildFlow);
2378
+ elements.usbDebugButton.addEventListener("click", runUsbDebugFlow);
1522
2379
  elements.clearLogsButton.addEventListener("click", clearLogs);
1523
2380
  elements.toggleLogsButton.addEventListener("click", toggleLogBar);
1524
2381
  elements.bottomToggleLogsButton.addEventListener("click", toggleLogBar);
@@ -1553,6 +2410,7 @@ function bindEvents() {
1553
2410
  validateSettings();
1554
2411
  });
1555
2412
  elements.permissionGrid.addEventListener("change", validateSettings);
2413
+ elements.nativeCodeGrid.addEventListener("click", handleNativeCodeCopy);
1556
2414
  [
1557
2415
  elements.appNameInput,
1558
2416
  elements.packageIdInput,
@@ -1629,6 +2487,16 @@ function bindEvents() {
1629
2487
  api.onInstallLog((payload) => {
1630
2488
  appendLog(payload.line, payload.kind || "raw");
1631
2489
  });
2490
+
2491
+ if (api.onProjectChanged) {
2492
+ api.onProjectChanged(applyProjectChange);
2493
+ }
2494
+
2495
+ if (api.onProjectWatchError) {
2496
+ api.onProjectWatchError((payload) => {
2497
+ appendLog(`${text("projectWatcherFail")}: ${payload.message}`, "error");
2498
+ });
2499
+ }
1632
2500
  }
1633
2501
 
1634
2502
  async function init() {
@@ -1645,6 +2513,11 @@ async function init() {
1645
2513
  try {
1646
2514
  const info = await api.appInfo();
1647
2515
  elements.appVersion.textContent = `v${info.version}`;
2516
+ state.defaultIconPath = info.iconPath || "";
2517
+ if (elements.iconPathInput && !elements.iconPathInput.value.trim() && state.defaultIconPath) {
2518
+ elements.iconPathInput.value = state.defaultIconPath;
2519
+ elements.iconPreview.src = iconPreviewPath(state.defaultIconPath);
2520
+ }
1648
2521
  } catch {
1649
2522
  elements.appVersion.textContent = "v0.1.0";
1650
2523
  }