summaryrefslogtreecommitdiff
path: root/src/popup/popup.js
blob: eb213f504d730374f614a941ed28e667925c12c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
'use strict';

import { LANGUAGES, ERROR_CODES, RUNTIME_MESSAGES } from '../shared/constants.js';
import { defaultSettings, sanitizeSettings } from '../shared/settings-schema.js';

const $enabled = /** @type {HTMLInputElement} */ (document.getElementById('enabled-toggle'));
const $model = /** @type {HTMLSelectElement} */ (document.getElementById('model-select'));
const $reload = /** @type {HTMLButtonElement} */ (document.getElementById('reload-models'));
const $modelStatus = /** @type {HTMLParagraphElement} */ (document.getElementById('model-status'));
const $language = /** @type {HTMLSelectElement} */ (document.getElementById('language-select'));
const $openOptions = /** @type {HTMLButtonElement} */ (document.getElementById('open-options'));

/** @type {string[]} current model list for change detection */
let knownModels = [];

function fillLanguages(selected) {
  $language.textContent = '';
  for (const lang of LANGUAGES) {
    const option = document.createElement('option');
    option.value = lang.code;
    option.textContent = lang.label;
    if (lang.code === selected) option.selected = true;
    $language.append(option);
  }
}

function fillModels(models, selected) {
  $model.textContent = '';
  if (models.length === 0) {
    const option = document.createElement('option');
    option.value = '';
    option.textContent = '(モデルなし / Ollama未起動)';
    $model.append(option);
  }
  for (const name of models) {
    const option = document.createElement('option');
    option.value = name;
    option.textContent = name;
    if (name === selected) option.selected = true;
    $model.append(option);
  }
  if (selected && !models.includes(selected)) {
    const option = document.createElement('option');
    option.value = selected;
    option.textContent = `${selected}(一覧にありません)`;
    option.selected = true;
    $model.append(option);
  }
  if (!selected && models.length > 0) {
    // No model saved yet: explicitly select the first one so the UI value
    // matches what will be used. Otherwise the browser auto-selects the
    // first option visually while storage still has an empty model,
    // which made translation fail until the user pressed Save.
    $model.selectedIndex = 0;
  }
}

function showStatus(message, isError) {
  $modelStatus.hidden = false;
  $modelStatus.textContent = message;
  $modelStatus.classList.toggle('error', Boolean(isError));
}

async function loadModels() {
  showStatus('モデル一覧を取得中…', false);
  try {
    const response = await browser.runtime.sendMessage({ type: RUNTIME_MESSAGES.LIST_MODELS });
    if (response && response.ok && Array.isArray(response.models)) {
      knownModels = response.models;
      const current = $model.value;
      fillModels(response.models, current);
      if (response.models.length === 0) {
        $modelStatus.hidden = true;
      } else {
        $modelStatus.hidden = true;
      }
    } else {
      const code = response && response.error;
      if (code === ERROR_CODES.OLLAMA_UNAVAILABLE) {
        showStatus('Ollamaに接続できません。', true);
      } else {
        showStatus('モデル一覧の取得に失敗しました。', true);
      }
      fillModels([], $model.value);
    }
  } catch {
    showStatus('モデル一覧の取得に失敗しました。', true);
  }
}

async function loadSettings() {
  const result = await browser.storage.local.get({ settings: null });
  const settings = sanitizeSettings(result.settings || defaultSettings());
  $enabled.checked = Boolean(settings.enabled);
  for (const lang of LANGUAGES) {
    const option = document.createElement('option');
    option.value = lang.code;
    option.textContent = lang.label;
    $language.append(option);
  }
  $language.value = settings.targetLanguage || 'ja';
  fillModels(knownModels, settings.model || '');
}

async function persist(patch) {
  const result = await browser.storage.local.get({ settings: null });
  const settings = sanitizeSettings(result.settings || defaultSettings());
  const merged = { ...settings, ...patch };
  // Sanitize before saving so unrelated fields stay valid.
  const validated = sanitizeSettings(merged);
  await browser.storage.local.set({ settings: validated });
}

$enabled.addEventListener('change', () => {
  void persist({ enabled: $enabled.checked });
});

$model.addEventListener('change', () => {
  const value = $model.value;
  if (value) void persist({ model: value });
});

$language.addEventListener('change', () => {
  void persist({ targetLanguage: $language.value });
});

$reload.addEventListener('click', () => {
  void loadModels();
});

$openOptions.addEventListener('click', () => {
  browser.runtime.openOptionsPage();
});

void (async () => {
  await loadSettings();
  await loadModels();
  // If the model list loaded and no model is saved yet, persist the
  // auto-selected first model so the stored settings match the UI.
  if (knownModels.length > 0) {
    const result = await browser.storage.local.get({ settings: null });
    const stored = sanitizeSettings(result.settings || defaultSettings());
    if (!stored.model) {
      await persist({ model: $model.value });
    }
  }
})();