NovelAI Mod

Extention for NovelAI Image Generator. Fast Suggestion, Chant, Save in JPEG, Get aspect ratio.

  1. // ==UserScript==
  2. // @name NovelAI Mod
  3. // @namespace https://www6.notion.site/dc99953d5f04405c893fba95dace0722
  4. // @version 25.2
  5. // @description Extention for NovelAI Image Generator. Fast Suggestion, Chant, Save in JPEG, Get aspect ratio.
  6. // @author SenY
  7. // @match https://novelai.net/image
  8. // @match https://novelai.github.io/image
  9. // @icon https://www.google.com/s2/favicons?sz=64&domain=novelai.net
  10. // @grant none
  11. // @license MIT
  12.  
  13. // ==/UserScript==
  14.  
  15. /**
  16. * NOVEIAI用のユーザースクリプト - グローバル変数と設定
  17. *
  18. * このファイルは、main.js、control.jsと順番に読み込まれ、同じスコープで実行されます。
  19. * 変数や関数は共有されるため、globalへ持たせる必要はありません。
  20. */
  21.  
  22. // 定数と設定
  23. const SUGGESTION_LIMIT = 500;
  24. const colors = {
  25. "-1": ["red", "maroon"],
  26. "0": ["lightblue", "dodgerblue"],
  27. "1": ["gold", "goldenrod"],
  28. "3": ["violet", "darkorchid"],
  29. "4": ["lightgreen", "darkgreen"],
  30. "5": ["tomato", "darksalmon"],
  31. "6": ["red", "maroon"],
  32. "7": ["whitesmoke", "black"],
  33. "8": ["seagreen", "darkseagreen"]
  34. };
  35.  
  36. // グローバル変数
  37. let lastTyped = new Date();
  38. let suggested_at = new Date();
  39. let chants = [];
  40. let allTags = [];
  41. let chantURL;
  42. let tagNameIndex = new Map();
  43. let tagTermsIndex = new Map();
  44.  
  45. /**
  46. * NOVEIAI用のユーザースクリプト - メイン機能
  47. *
  48. * このファイルは、global.jsの後に読み込まれ、control.jsの前に読み込まれます。
  49. * 同じスコープで実行されるため、変数や関数は共有されます。
  50. */
  51.  
  52. // ユーティリティ関数
  53. const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
  54. const getAspect = whArray => whArray.map(x => x / gcd(whArray[0], whArray[1]));
  55.  
  56. const aspectList = (wa, ha, maxpixel = 1024 * 1024) => {
  57. let aspect = wa / ha;
  58. let limit = 16384;
  59. let steps = 64;
  60. let ws = Array.from({ length: (limit - steps) / steps + 1 }, (_, i) => (i + 1) * steps);
  61. let hs = ws.slice();
  62. return ws.flatMap(w => hs.map(h => w / h === aspect && w * h <= maxpixel ? [w, h] : null)).filter(Boolean);
  63. };
  64.  
  65. const getChantURL = force => {
  66. if (force === true) {
  67. localStorage.removeItem("chantURL");
  68. }
  69. let url = localStorage.getItem("chantURL") || prompt("Input your chants json url.\nThe URL must be a Cors-enabled server (e.g., gist.github.com).", "https://gist.githubusercontent.com/vkff5833/989808aadebf8648831955cdf2a7b3e3/raw/yuuri.json");
  70. if (url) localStorage.setItem("chantURL", url);
  71. return url;
  72. };
  73.  
  74. /**
  75. * 画像のDataURLを取得する
  76. * @param {string} mode - 'current'または'uploaded'
  77. * @returns {Promise<string|null>} 画像のDataURL
  78. */
  79. const getImageDataURL = async (mode) => {
  80. console.debug(`Getting image DataURL for mode: ${mode}`);
  81. try {
  82. if (mode === "current") {
  83. const imgs = Array.from(document.querySelectorAll('img[src]')).filter(x => x.offsetParent);
  84. const url = imgs.reduce((max, img) => img.height > max.height ? img : max).src || document.querySelector('img[src]')?.src;
  85. if (!url) {
  86. console.debug("No image URL found");
  87. return null;
  88. }
  89. console.debug("Found image URL:", url.substring(0, 50) + "...");
  90. const response = await fetch(url);
  91. const blob = await response.blob();
  92. return await new Promise(resolve => {
  93. let reader = new FileReader();
  94. reader.onload = () => resolve(reader.result);
  95. reader.readAsDataURL(blob);
  96. });
  97. } else if (mode === "uploaded") {
  98. const uploadInput = document.getElementById('naimodUploadedImage');
  99. const previewImage = document.getElementById('naimodPreviewImage');
  100. if (uploadInput && uploadInput.files[0]) {
  101. return await new Promise(resolve => {
  102. let reader = new FileReader();
  103. reader.onload = (e) => resolve(e.target.result);
  104. reader.readAsDataURL(uploadInput.files[0]);
  105. });
  106. } else if (previewImage && previewImage.src) {
  107. return previewImage.src;
  108. }
  109. return null;
  110. }
  111. } catch (error) {
  112. console.error("Error getting image DataURL:", error);
  113. return null;
  114. }
  115. };
  116.  
  117. /**
  118. * タグの改善提案をAIに要求する
  119. * @param {string} tags - 現在のタグリスト
  120. * @param {string} imageDataURL - 画像のDataURL
  121. * @returns {Promise<Object|false>} 改善提案の結果
  122. */
  123. async function ImprovementTags(tags, imageDataURL) {
  124. console.debug("Starting tag improvement process");
  125. console.debug("ImprovementTags function called with tags:", tags);
  126.  
  127. // タグの_を半角スペースに置換
  128. tags = tags.replace(/_/g, " ");
  129.  
  130. const apiKey = document.getElementById('geminiApiKey').value;
  131. if (!apiKey) {
  132. alert("Gemini API Keyが設定されていません。設定画面でAPIキーを入力してください。");
  133. return false;
  134. }
  135. console.debug("API Key found:", apiKey.substring(0, 5) + "...");
  136.  
  137. const model = document.getElementById('geminiModel').value;
  138. const ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
  139. console.debug("ENDPOINT:", ENDPOINT);
  140.  
  141. let prompt = `以下に示すのはdanbooruのタグを用いて画像を生成するNovelAIの機能で、添付の画像を生成する為に用意したタグの一覧です。
  142.  
  143. ${tags}
  144.  
  145. - 実際の画像の内容と列挙されたタグ一覧の、比較検討とブラッシュアップを行ってください。
  146. - 不要と判断したタグを列挙してください。例えば顔しか映っていない画像なのにスカートや靴下に関する言及がある場合や、顔が映らない構図なのに瞳の色や表情に言及がある場合、黒髪のキャラしか居ないのにblonde hairと記述されるなど明らかに的外れなタグが含まれている場合などは、それらを除去する必要があります。(should remove)
  147. - それとは逆に、新たに付与するべきであると考えられるタグがある場合は列挙してください。(should add)
  148. - また、客観的に画像から読み取って付与するべきと判断したタグ以外に、追加することでより表現が豊かになると考えられるタグがあれば、それも提案してください。例えば文脈上付与した方がよりリアリティが増すと思われるアクセサリや小物を示すタグ、より効果的な表現を得る為に付与するのが好ましいと思われるエフェクトのタグなどです。
  149. これらの内容は元々の画像には含まれていない要素であるべきです。(may add)
  150. - 固有名詞と思われる認識不能なタグに関しては無視してください。
  151. - また、NovelAI系ではない自然文のプロンプトで画像生成をする場合に用いるプロンプトも別途提案してください。実際の画像や上記のshouldRemove,shouldAdd,mayAddの内容を踏襲し、2000文字程度の自然言語の英文で表現してください。
  152.  
  153. 返信はJSON形式で以下のスキーマに従ってください。
  154.  
  155. {
  156. "shouldRemove": [string]
  157. "shouldAdd": [string]
  158. "mayAdd": [string],
  159. "naturalLanguagePrompt": [string]
  160. }
  161. `;
  162. console.debug("Prompt prepared:", prompt);
  163.  
  164. const payload = {
  165. method: 'POST',
  166. headers: {},
  167. body: JSON.stringify({
  168. contents: [
  169. {
  170. parts: [
  171. { text: prompt },
  172. { inline_data: { mime_type: "image/jpeg", data: imageDataURL.split(',')[1] } }
  173. ]
  174. }
  175. ],
  176. "generationConfig": {
  177. "temperature": 1.0,
  178. "max_output_tokens": 4096
  179. },
  180. safetySettings: [
  181. {
  182. "category": "HARM_CATEGORY_HATE_SPEECH",
  183. "threshold": "OFF"
  184. },
  185. {
  186. "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
  187. "threshold": "OFF"
  188. },
  189. {
  190. "category": "HARM_CATEGORY_HARASSMENT",
  191. "threshold": "OFF"
  192. },
  193. {
  194. "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
  195. "threshold": "OFF"
  196. }
  197. ]
  198. }),
  199. mode: 'cors'
  200. };
  201. console.debug("Payload prepared:", payload);
  202.  
  203. let result;
  204. try {
  205. console.debug("Sending fetch request to Gemini API");
  206. const response = await fetch(ENDPOINT, payload);
  207. console.debug("Response received:", response);
  208. const data = await response.json();
  209. console.debug("Response data:", data);
  210. result = data.candidates[0].content.parts[0].text;
  211. result = result.replace('```json\n', '').replace('\n```', '');
  212. result = JSON.parse(result);
  213. // 結果のタグも_を半角スペースに置換
  214. result.shouldRemove = result.shouldRemove.map(tag => tag.replace(/_/g, " "));
  215. result.shouldAdd = result.shouldAdd.map(tag => tag.replace(/_/g, " "));
  216. result.mayAdd = result.mayAdd.map(tag => tag.replace(/_/g, " "));
  217. console.debug("Parsed result:", result);
  218. } catch (error) {
  219. console.error('エラー:', error);
  220. alert("AI改善の処理中にエラーが発生しました。");
  221. return false;
  222. }
  223. return result || false;
  224. }
  225.  
  226. /**
  227. * 現在の画像をJPEG形式で保存する
  228. */
  229. const saveJpeg = async () => {
  230. console.debug("Starting JPEG save process");
  231.  
  232. // シードボタンの検索
  233. const seedButton = Array.from(document.querySelectorAll('span[style]')).find(x => x.textContent.trim().match(/^[0-9]*(seed|シード)/i))?.closest("button");
  234. console.debug("Found seed button:", seedButton);
  235.  
  236. // シード値の取得
  237. let seed = Array.from(seedButton.querySelectorAll("span")).find(x => x.textContent.match(/^[0-9]*$/))?.textContent;
  238. console.debug("Extracted seed:", seed);
  239.  
  240. let filename = `${seed}.jpg`;
  241. console.debug("Generated filename:", filename);
  242.  
  243. // 画像データの取得
  244. console.debug("Getting image DataURL...");
  245. const dataURI = await getImageDataURL("current");
  246. if (!dataURI) {
  247. throw new Error("Failed to get image DataURL");
  248. }
  249. console.debug("Got DataURL, length:", dataURI.length);
  250.  
  251. // 画像オブジェクトの作成
  252. console.debug("Creating Image object...");
  253. let image = new Image();
  254. image.src = dataURI;
  255.  
  256. console.debug("Waiting for image to load...");
  257. await new Promise((resolve, reject) => {
  258. image.onload = resolve;
  259. image.onerror = () => reject(new Error("Failed to load image"));
  260. });
  261. console.debug("Image loaded, dimensions:", image.width, "x", image.height);
  262.  
  263. // キャンバスの作成と描画
  264. console.debug("Creating canvas...");
  265. let canvas = document.createElement("canvas");
  266. canvas.width = image.width;
  267. canvas.height = image.height;
  268.  
  269. console.debug("Drawing image to canvas...");
  270. let ctx = canvas.getContext("2d");
  271. ctx.drawImage(image, 0, 0);
  272.  
  273. // JPEG形式への変換
  274. console.debug("Converting to JPEG...");
  275. let quality = document.getElementById("jpegQuality")?.value || 0.85;
  276. console.debug("Using JPEG quality:", quality);
  277. let JPEG = canvas.toDataURL("image/jpeg", quality);
  278. console.debug("JPEG conversion complete, data length:", JPEG.length);
  279.  
  280. // ダウンロードリンクの作成と実行
  281. console.debug("Creating download link...");
  282. let link = document.createElement('a');
  283. link.href = JPEG;
  284. link.download = filename;
  285. console.debug("Triggering download...");
  286. link.click();
  287.  
  288. console.debug("JPEG save process completed successfully");
  289. };
  290.  
  291. const updateImageDimensions = (w, h) => {
  292. document.querySelectorAll('input[type="number"][step="64"]').forEach((x, i) => {
  293. x.value = [w, h][i];
  294. x._valueTracker = '';
  295. x.dispatchEvent(new Event('input', { bubbles: true }));
  296. });
  297. };
  298.  
  299. /**
  300. * エディタのコンテンツを設定する
  301. * @param {string} content - 設定するコンテンツ
  302. * @param {Element} editor - 対象のエディタ要素
  303. * @param {Object} options - カーソル位置などのオプション
  304. */
  305. const setEditorContent = (content, editor, options = {}) => {
  306. console.debug("Setting editor content", { contentLength: content.length });
  307. if (!editor) {
  308. console.error("Editor is required for setEditorContent");
  309. return;
  310. }
  311.  
  312. const { cursorPosition } = options;
  313.  
  314. editor.innerHTML = "";
  315. const p = document.createElement("p");
  316. p.textContent = content;
  317. editor.appendChild(p);
  318. editor.dispatchEvent(new Event('input', { bubbles: true }));
  319.  
  320. // カーソル位置の復元
  321. if (typeof cursorPosition === 'number') {
  322. const range = document.createRange();
  323. const sel = window.getSelection();
  324. range.setStart(p.firstChild, Math.min(cursorPosition, content.length));
  325. range.collapse(true);
  326. sel.removeAllRanges();
  327. sel.addRange(range);
  328. }
  329. };
  330.  
  331. /**
  332. * エディタ内の絶対カーソル位置を計算する
  333. * @param {Element} editor - 対象のエディタ要素
  334. * @returns {number} 絶対カーソル位置
  335. */
  336. const getAbsoluteCursorPosition = (editor) => {
  337. console.debug("Calculating absolute cursor position");
  338. const selection = window.getSelection();
  339. const range = selection.getRangeAt(0);
  340.  
  341. // カーソルが含まれているp要素を特定
  342. const currentP = range.startContainer.nodeType === 3 ?
  343. range.startContainer.parentNode :
  344. range.startContainer;
  345.  
  346. // 全てのp要素を取得
  347. const allPs = Array.from(editor.querySelectorAll("p"));
  348. let absoluteCursorPosition = 0;
  349.  
  350. // カーソル位置までの文字数を計算
  351. for (let p of allPs) {
  352. if (p === currentP) {
  353. absoluteCursorPosition += range.startOffset;
  354. break;
  355. }
  356. absoluteCursorPosition += p.textContent.length + 1; // +1 は改行文字の分
  357. }
  358.  
  359. return absoluteCursorPosition + 2;
  360. };
  361.  
  362. /**
  363. * 現在のカーソル位置のタグを取得する
  364. * @param {Element} editor - 対象のエディタ要素
  365. * @param {number} position - カーソル位置
  366. * @returns {string|undefined} カーソル位置のタグ
  367. */
  368. const getCurrentTargetTag = (editor, position) => {
  369. console.debug("Getting current target tag at position:", position);
  370. const content = Array.from(editor.querySelectorAll("p"))
  371. .map(p => p.textContent)
  372. .join("\n");
  373. // カンマまたは改行で分割(連続する区切り文字は1つとして扱う)
  374. const splitTags = (text) =>
  375. text.split(/[,\n]+/).map(x => x.trim()).filter(Boolean);
  376. const oldTags = splitTags(content);
  377. const beforeCursor = content.slice(0, position);
  378. const beforeTags = splitTags(beforeCursor);
  379. const targetTag = beforeTags[beforeTags.length - 2];
  380. const result = oldTags[oldTags.indexOf(targetTag) + 1]?.trim();
  381. return result;
  382. };
  383.  
  384. // タグを削除する関数を修正
  385. const removeTagsFromPrompt = (tagsToRemove, editor, options = {}) => {
  386. if (!editor || !tagsToRemove?.length) return;
  387.  
  388. const { cursorPosition } = options;
  389. const content = Array.from(editor.querySelectorAll("p"))
  390. .map(p => p.textContent)
  391. .join("\n");
  392. const oldTags = content.split(/[,\n]+/).map(x => x.trim()).filter(Boolean);
  393.  
  394. // 削除対象のタグを除外
  395. const tags = oldTags.filter(tag => !tagsToRemove.includes(tag));
  396.  
  397. setEditorContent(tags.join(", ") + ", ", editor, { cursorPosition });
  398. };
  399.  
  400. // appendTagsToPromptを修正
  401. const appendTagsToPrompt = (tagsToAdd, editor, options = {}) => {
  402. if (!editor) {
  403. console.error("Editor is required for appendTagsToPrompt");
  404. return;
  405. }
  406. if (!tagsToAdd?.length) return;
  407.  
  408. const position = window.getLastCursorPosition();
  409. const { removeIncompleteTag } = options;
  410. const content = Array.from(editor.querySelectorAll("p"))
  411. .map(p => p.textContent)
  412. .join("\n");
  413. const oldTags = content.split(/[,\n]+/).map(x => x.trim()).filter(Boolean);
  414. console.log(oldTags, oldTags.includes(removeIncompleteTag), removeIncompleteTag);
  415. const targetTag = getCurrentTargetTag(editor, position);
  416.  
  417. let tags = oldTags.flatMap(tag =>
  418. tag === targetTag ? [tag, ...tagsToAdd] : [tag]
  419. );
  420.  
  421. if (!targetTag) {
  422. tags = [...tags, ...tagsToAdd];
  423. }
  424.  
  425. tags = [...new Set(tags.filter(Boolean))];
  426.  
  427. if (removeIncompleteTag) {
  428. tags = tags.filter(tag => tag !== removeIncompleteTag);
  429. }
  430.  
  431. setEditorContent(tags.join(", ") + ", ", editor, { cursorPosition: position });
  432. };
  433.  
  434. /**
  435. * タグの強調度を調整する
  436. * @param {number} value - 調整値(正: 強調、負: 抑制)
  437. * @param {Element} editor - 対象のエディタ要素
  438. * @param {Object} options - オプション
  439. */
  440. const adjustTagEmphasis = (value, editor, options = {}) => {
  441. console.debug("Adjusting tag emphasis", { value });
  442. if (!editor) {
  443. console.error("Editor is required for adjustTagEmphasis");
  444. return;
  445. }
  446.  
  447. const position = window.getLastCursorPosition();
  448. const targetTag = getCurrentTargetTag(editor, position);
  449.  
  450. if (targetTag) {
  451. const getTagEmphasisLevel = tag =>
  452. tag.split("").filter(x => x === "{").length -
  453. tag.split("").filter(x => x === "[").length;
  454.  
  455. const content = Array.from(editor.querySelectorAll("p"))
  456. .map(p => p.textContent)
  457. .join("\n");
  458. const oldTags = content.split(/[,\n]+/).map(x => x.trim()).filter(Boolean);
  459.  
  460. let tags = oldTags.map(tag => {
  461. if (tag === targetTag) {
  462. let emphasisLevel = getTagEmphasisLevel(targetTag) + value;
  463. tag = tag.replace(/[\{\}\[\]]/g, "");
  464. return emphasisLevel > 0 ? '{'.repeat(emphasisLevel) + tag + '}'.repeat(emphasisLevel) :
  465. emphasisLevel < 0 ? '['.repeat(-emphasisLevel) + tag + ']'.repeat(-emphasisLevel) : tag;
  466. }
  467. return tag;
  468. }).filter(Boolean);
  469.  
  470. setEditorContent(tags.join(", ") + ", ", editor, { cursorPosition: position });
  471. }
  472. };
  473.  
  474. // 初期化時にインデックスを構築
  475. const buildTagIndices = () => {
  476. allTags.forEach(tag => {
  477. // 名前のインデックス
  478. const normalizedName = tag.name.toLowerCase().replace(/_/g, " ");
  479. tagNameIndex.set(normalizedName, tag);
  480.  
  481. // 別名のインデックス
  482. tag.terms.forEach(term => {
  483. const normalizedTerm = term.toLowerCase().replace(/_/g, " ");
  484. if (!tagTermsIndex.has(normalizedTerm)) {
  485. tagTermsIndex.set(normalizedTerm, new Set());
  486. }
  487. tagTermsIndex.get(normalizedTerm).add(tag);
  488. });
  489. });
  490. };
  491.  
  492. // showTagSuggestionsの中のフィルタリング部分を修正
  493. const getTagSuggestions = (targetTag, limit = 20) => {
  494. const normalizedTarget = targetTag.toLowerCase()
  495. .replace(/_/g, " ")
  496. .replace(/[\{\}\[\]\\]/g, "");
  497.  
  498. const results = new Set();
  499.  
  500. // 名前での検索
  501. for (const [name, tag] of tagNameIndex) {
  502. if (name.includes(normalizedTarget)) {
  503. results.add(tag);
  504. if (results.size >= limit) break;
  505. }
  506. }
  507.  
  508. // 結果が不足している場合は別名も検索
  509. if (results.size < limit) {
  510. for (const [term, tags] of tagTermsIndex) {
  511. if (term.includes(normalizedTarget)) {
  512. for (const tag of tags) {
  513. results.add(tag);
  514. if (results.size >= limit) break;
  515. }
  516. }
  517. if (results.size >= limit) break;
  518. }
  519. }
  520.  
  521. return Array.from(results).slice(0, limit);
  522. };
  523.  
  524. /**
  525. * タグの提案を表示する
  526. * @param {Element} targetEditor - 対象のエディタ要素
  527. * @param {number} position - カーソル位置
  528. */
  529. const showTagSuggestions = (targetEditor = null, position = null) => {
  530. console.debug("=== Start showTagSuggestions ===");
  531.  
  532. const editor = targetEditor || window.getLastFocusedEditor();
  533. if (editor) {
  534. const cursorPosition = position ?? window.getLastCursorPosition();
  535. let targetTag = getCurrentTargetTag(editor, cursorPosition)?.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
  536.  
  537. let suggestionField = editor.closest(".relative")?.querySelector("#suggestionField") ||
  538. document.getElementById("suggestionField");
  539.  
  540. if (suggestionField) {
  541. suggestionField.textContent = "";
  542.  
  543. if (targetTag) {
  544. let suggestions = getTagSuggestions(targetTag);
  545. console.debug(`Found ${suggestions.length} suggestions for tag: ${targetTag}`);
  546.  
  547. let done = new Set();
  548. suggestions.forEach(tag => {
  549. if (!done.has(tag.name)) {
  550. const incompleteTag = targetTag;
  551.  
  552. let button = createButton(
  553. `${tag.name} (${tag.coumt > 1000 ? `${(Math.round(tag.coumt / 100) / 10)}k` : tag.coumt})`,
  554. colors[tag.category][1],
  555. () => appendTagsToPrompt([tag.name], editor, {
  556. removeIncompleteTag: incompleteTag
  557. })
  558. );
  559. button.title = tag.terms.filter(Boolean).join(", ");
  560. suggestionField.appendChild(button);
  561.  
  562. if (editor.textContent.split(",").map(y => y.trim().replace(/_/g, " ").replace(/[\{\}\[\]\\]/g, "")).includes(tag.name.replace(/_/g, " "))) {
  563. button.style.opacity = 0.5;
  564. }
  565. done.add(tag.name);
  566. }
  567. });
  568. }
  569. }
  570. }
  571. console.debug("=== End showTagSuggestions ===");
  572. };
  573.  
  574. // UIコンポーネントの作成関数
  575. const createSettingsModal = () => {
  576. let modal = document.getElementById("naimod-modal");
  577. if (!modal) {
  578. modal = document.createElement("div");
  579. modal.id = "naimod-modal";
  580. modal.className = "naimod-modal";
  581.  
  582. modal.addEventListener("click", (event) => {
  583. if (event.target === modal) {
  584. modal.style.display = "none";
  585. }
  586. });
  587.  
  588. let settingsContent = document.createElement("div");
  589. settingsContent.className = "naimod-settings-content";
  590.  
  591. // 2ペインコンテナ
  592. const twoPane = document.createElement("div");
  593. twoPane.className = "naimod-modal-two-pane";
  594.  
  595. // 左ペイン(Settings)
  596. const settingsPane = document.createElement("div");
  597. settingsPane.className = "naimod-modal-pane settings-pane";
  598.  
  599. // Settings タイトル
  600. const settingsTitle = document.createElement("h2");
  601. settingsTitle.textContent = "Settings";
  602. settingsTitle.className = "naimod-section-title";
  603. settingsPane.appendChild(settingsTitle);
  604.  
  605. // Reset Chants URLセクション
  606. settingsPane.appendChild(createResetChantsSection());
  607.  
  608. // API Settings セクション
  609. settingsPane.appendChild(createAPIKeySection());
  610.  
  611. // 画像ソース選択セクション
  612. settingsPane.appendChild(createImageSourceSection());
  613.  
  614. // 右ペイン(Operation)
  615. const operationPane = document.createElement("div");
  616. operationPane.className = "naimod-modal-pane operation-pane";
  617.  
  618. // Operation タイトル
  619. const operationTitle = document.createElement("h2");
  620. operationTitle.textContent = "AI Improvements";
  621. operationTitle.className = "naimod-section-title";
  622. operationPane.appendChild(operationTitle);
  623.  
  624. // Suggest AI Improvementsボタンを操作セクション直下に配置
  625. const initialButtonContainer = document.createElement("div");
  626. initialButtonContainer.className = "naimod-button-container";
  627. const suggestButton = createButton("Suggest AI Improvements", "blue", async () => {
  628. console.debug("Suggest AI Improvements clicked");
  629.  
  630. const rightPane = document.querySelector(".naimod-pane.right-pane");
  631. if (!rightPane) {
  632. console.error("Right pane not found");
  633. return;
  634. }
  635.  
  636. // 自然言語プロンプトの状態をリセット
  637. const naturalLanguagePrompt = document.getElementById("naturalLanguagePrompt");
  638. const copyButton = naturalLanguagePrompt?.parentElement?.querySelector("button");
  639. if (naturalLanguagePrompt) {
  640. naturalLanguagePrompt.textContent = "Waiting for AI suggestions...";
  641. if (copyButton) copyButton.style.display = "none";
  642. }
  643.  
  644. // lastFocusedEditorからタグを取得
  645. const editor = window.getLastFocusedEditor();
  646. if (!editor) {
  647. console.error("No editor is focused");
  648. rightPane.innerHTML = "Please focus on a tag editor first";
  649. naturalLanguagePrompt.textContent = "";
  650. if (copyButton) copyButton.style.display = "none";
  651. return;
  652. }
  653.  
  654. console.debug("Getting tags from editor");
  655. const tags = editor.textContent.trim();
  656. console.debug("Current tags:", tags);
  657.  
  658. if (tags) {
  659. rightPane.innerHTML = "Waiting for AI suggestions...";
  660. suggestButton.disabled = true;
  661. suggestButton.textContent = "Processing...";
  662.  
  663. console.debug("Getting image source");
  664. let imageSource = document.getElementById("imageSource").value;
  665. console.debug("Image source:", imageSource);
  666.  
  667. console.debug("Getting image DataURL");
  668. let imageDataURL = await getImageDataURL(imageSource);
  669.  
  670. if (!imageDataURL) {
  671. console.error("Failed to get image DataURL");
  672. rightPane.innerHTML = "";
  673. naturalLanguagePrompt.textContent = "";
  674. if (copyButton) copyButton.style.display = "none";
  675. suggestButton.disabled = false;
  676. suggestButton.textContent = "Suggest AI Improvements";
  677. return;
  678. }
  679. console.debug("Got image DataURL, length:", imageDataURL.length);
  680.  
  681. console.debug("Calling ImprovementTags");
  682. let result = await ImprovementTags(tags, imageDataURL);
  683. console.debug("ImprovementTags result:", result);
  684.  
  685. if (result) {
  686. displaySuggestions(result, rightPane);
  687. }
  688. suggestButton.disabled = false;
  689. suggestButton.textContent = "Suggest AI Improvements";
  690. } else {
  691. console.error("No tags found in editor");
  692. rightPane.innerHTML = "No tags found in editor";
  693. naturalLanguagePrompt.textContent = "";
  694. if (copyButton) copyButton.style.display = "none";
  695. }
  696. });
  697. suggestButton.className = "naimod-operation-button";
  698. initialButtonContainer.appendChild(suggestButton);
  699. operationPane.appendChild(initialButtonContainer);
  700.  
  701. // AIサジェスト関連セクション
  702. const suggestSection = document.createElement("div");
  703. suggestSection.className = "naimod-operation-section";
  704.  
  705. // Danbooru Tags セクションタイトル
  706. const danbooruTitle = document.createElement("h3");
  707. danbooruTitle.textContent = "Danbooru Tags";
  708. danbooruTitle.className = "naimod-section-title";
  709. suggestSection.appendChild(danbooruTitle);
  710.  
  711. // タグ提案表示域
  712. const rightPane = document.createElement("div");
  713. rightPane.className = "naimod-pane right-pane";
  714. suggestSection.appendChild(rightPane);
  715.  
  716. operationPane.appendChild(suggestSection);
  717.  
  718. // 自然言語プロンプトセクションを修正
  719. const createNaturalLanguageSection = () => {
  720. const container = document.createElement("div");
  721. container.className = "naimod-natural-language-container";
  722.  
  723. const title = document.createElement("h3");
  724. title.textContent = "Natural Language Prompt";
  725. title.className = "naimod-section-title";
  726. container.appendChild(title);
  727.  
  728. const content = document.createElement("div");
  729. content.id = "naturalLanguagePrompt";
  730. content.className = "naimod-natural-language-content";
  731. content.textContent = "";
  732. container.appendChild(content);
  733.  
  734. return container;
  735. };
  736.  
  737. operationPane.appendChild(createNaturalLanguageSection());
  738.  
  739. // ペインを追加
  740. twoPane.appendChild(settingsPane);
  741. twoPane.appendChild(operationPane);
  742. settingsContent.appendChild(twoPane);
  743.  
  744. // 閉じるボタンセクション
  745. settingsContent.appendChild(createCloseButtonSection(modal));
  746.  
  747. modal.appendChild(settingsContent);
  748. document.body.appendChild(modal);
  749. }
  750. return modal;
  751. };
  752.  
  753. const createAPIKeySection = () => {
  754. const section = document.createElement("div");
  755. section.className = "naimod-section";
  756.  
  757. const sectionTitle = document.createElement("h3");
  758. sectionTitle.textContent = "Gemini Settings";
  759. sectionTitle.className = "naimod-section-title";
  760. section.appendChild(sectionTitle);
  761.  
  762. // APIキー入力フィールド
  763. let apiKeyInput = document.createElement("input");
  764. apiKeyInput.type = "text";
  765. apiKeyInput.id = "geminiApiKey";
  766. apiKeyInput.className = "naimod-input";
  767. apiKeyInput.placeholder = "Enter Gemini API Key";
  768. apiKeyInput.value = localStorage.getItem("geminiApiKey") || "";
  769. apiKeyInput.style.width = "100%";
  770. apiKeyInput.style.padding = "5px";
  771. apiKeyInput.style.marginBottom = "10px";
  772. apiKeyInput.addEventListener("change", () => {
  773. localStorage.setItem("geminiApiKey", apiKeyInput.value);
  774. });
  775.  
  776. // モデル選択セレクトボックス
  777. const modelSelect = document.createElement("select");
  778. modelSelect.id = "geminiModel";
  779. modelSelect.className = "naimod-input";
  780. modelSelect.style.width = "100%";
  781. modelSelect.style.padding = "5px";
  782. modelSelect.style.marginBottom = "10px";
  783.  
  784. const models = [
  785. "gemini-2.0-flash-lite-preview",
  786. "gemini-2.0-flash-exp",
  787. "gemini-2.0-flash-thinking-exp",
  788. "gemini-2.0-pro-exp"
  789. ];
  790.  
  791. models.forEach(model => {
  792. const option = document.createElement("option");
  793. option.value = model;
  794. option.textContent = model;
  795. modelSelect.appendChild(option);
  796. });
  797.  
  798. // 保存された値があれば復元
  799. modelSelect.value = localStorage.getItem("geminiModel") || "gemini-2.0-flash-thinking-exp";
  800.  
  801. modelSelect.addEventListener("change", () => {
  802. localStorage.setItem("geminiModel", modelSelect.value);
  803. });
  804.  
  805. section.appendChild(apiKeyInput);
  806. section.appendChild(modelSelect);
  807. return section;
  808. };
  809.  
  810. const createResetChantsSection = () => {
  811. const section = document.createElement("div");
  812. section.className = "naimod-section";
  813. section.style.marginBottom = "20px";
  814.  
  815. const sectionTitle = document.createElement("h3");
  816. sectionTitle.textContent = "Chant Settings";
  817. sectionTitle.className = "naimod-section-title";
  818. section.appendChild(sectionTitle);
  819.  
  820. // リセットボタン
  821. let resetButton = createButton("Reset Chants URL", "red", () => {
  822. chantURL = getChantURL(true);
  823. initializeApplication();
  824. });
  825. resetButton.className = "naimod-button";
  826.  
  827. section.appendChild(resetButton);
  828. return section;
  829. };
  830.  
  831. const createImageSourceSection = () => {
  832. const section = document.createElement("div");
  833. section.className = "naimod-image-source-container";
  834.  
  835. const sectionTitle = document.createElement("h3");
  836. sectionTitle.textContent = "Image Source";
  837. sectionTitle.className = "naimod-section-title";
  838. section.appendChild(sectionTitle);
  839.  
  840. // 画像ソース選択UI
  841. const { imageSourceSelect, uploadContainer } = createImageSourceUI();
  842. section.appendChild(imageSourceSelect);
  843. section.appendChild(uploadContainer);
  844.  
  845. return section;
  846. };
  847.  
  848. const createTwoPaneSection = () => {
  849. const section = document.createElement("div");
  850. section.className = "naimod-operation-section";
  851.  
  852. // Danbooru Promptセクション
  853. const danbooruTitle = document.createElement("h3");
  854. danbooruTitle.textContent = "Danbooru Prompt";
  855. danbooruTitle.className = "naimod-section-title";
  856. section.appendChild(danbooruTitle);
  857.  
  858. // ボタンコンテナ
  859. const buttonContainer = document.createElement("div");
  860. buttonContainer.className = "naimod-button-container";
  861. buttonContainer.style.display = "flex";
  862. buttonContainer.style.gap = "10px";
  863. buttonContainer.style.marginBottom = "15px";
  864.  
  865. // Suggest AI Improvementsボタン
  866. let suggestButton = createButton("Suggest AI Improvements", "blue", async () => {
  867. console.debug("Suggest AI Improvements clicked");
  868.  
  869. const rightPane = document.querySelector(".naimod-pane.right-pane");
  870. if (!rightPane) {
  871. console.error("Right pane not found");
  872. return;
  873. }
  874.  
  875. // 自然言語プロンプトの状態をリセット
  876. const naturalLanguagePrompt = document.getElementById("naturalLanguagePrompt");
  877. const copyButton = naturalLanguagePrompt?.parentElement?.querySelector("button");
  878. if (naturalLanguagePrompt) {
  879. naturalLanguagePrompt.textContent = "Waiting for AI suggestions...";
  880. if (copyButton) copyButton.style.display = "none";
  881. }
  882.  
  883. // lastFocusedEditorからタグを取得
  884. const editor = window.getLastFocusedEditor();
  885. if (!editor) {
  886. console.error("No editor is focused");
  887. rightPane.innerHTML = "Please focus on a tag editor first";
  888. naturalLanguagePrompt.textContent = "";
  889. if (copyButton) copyButton.style.display = "none";
  890. return;
  891. }
  892.  
  893. console.debug("Getting tags from editor");
  894. const tags = editor.textContent.trim();
  895. console.debug("Current tags:", tags);
  896.  
  897. if (tags) {
  898. rightPane.innerHTML = "Waiting for AI suggestions...";
  899. suggestButton.disabled = true;
  900. suggestButton.textContent = "Processing...";
  901.  
  902. console.debug("Getting image source");
  903. let imageSource = document.getElementById("imageSource").value;
  904. console.debug("Image source:", imageSource);
  905.  
  906. console.debug("Getting image DataURL");
  907. let imageDataURL = await getImageDataURL(imageSource);
  908.  
  909. if (!imageDataURL) {
  910. console.error("Failed to get image DataURL");
  911. rightPane.innerHTML = "";
  912. naturalLanguagePrompt.textContent = "";
  913. if (copyButton) copyButton.style.display = "none";
  914. suggestButton.disabled = false;
  915. suggestButton.textContent = "Suggest AI Improvements";
  916. return;
  917. }
  918. console.debug("Got image DataURL, length:", imageDataURL.length);
  919.  
  920. console.debug("Calling ImprovementTags");
  921. let result = await ImprovementTags(tags, imageDataURL);
  922. console.debug("ImprovementTags result:", result);
  923.  
  924. if (result) {
  925. displaySuggestions(result, rightPane);
  926. }
  927. suggestButton.disabled = false;
  928. suggestButton.textContent = "Suggest AI Improvements";
  929. } else {
  930. console.error("No tags found in editor");
  931. rightPane.innerHTML = "No tags found in editor";
  932. naturalLanguagePrompt.textContent = "";
  933. if (copyButton) copyButton.style.display = "none";
  934. }
  935. });
  936. suggestButton.className = "naimod-operation-button";
  937.  
  938. // Apply Suggestionsボタン
  939. let applyButton = createButton("Apply Suggestions", "green", () => {
  940. console.debug("Apply Suggestions clicked");
  941.  
  942. const editor = window.getLastFocusedEditor();
  943. if (!editor) {
  944. console.error("No editor is focused");
  945. return;
  946. }
  947.  
  948. const rightPane = document.querySelector(".naimod-pane.right-pane");
  949. if (!rightPane) {
  950. console.error("Right pane not found");
  951. return;
  952. }
  953.  
  954. console.debug("Getting enabled tags");
  955. let enabledTags = Array.from(rightPane.querySelectorAll('button[data-enabled="true"]'))
  956. .map(button => button.textContent.replace(/_/g, " "));
  957. console.debug("Enabled tags:", enabledTags);
  958.  
  959. if (enabledTags.length > 0) {
  960. setEditorContent(enabledTags.join(", ") + ", ", editor);
  961. console.debug("Applied tags to editor");
  962.  
  963. // モーダルを閉じる
  964. const modal = document.getElementById("naimod-modal");
  965. if (modal) {
  966. modal.style.display = "none";
  967. console.debug("Closed modal");
  968. }
  969. } else {
  970. console.debug("No enabled tags found");
  971. }
  972. });
  973. applyButton.className = "naimod-operation-button";
  974.  
  975. buttonContainer.appendChild(suggestButton);
  976. buttonContainer.appendChild(applyButton);
  977. section.appendChild(buttonContainer);
  978.  
  979. // タグ提案表示域
  980. const suggestionPane = document.createElement("div");
  981. suggestionPane.className = "naimod-pane right-pane";
  982. section.appendChild(suggestionPane);
  983.  
  984. return section;
  985. };
  986.  
  987. // ポップアップの位置を調整する関数を修正
  988. const adjustPopupPosition = (popup) => {
  989. const rect = popup.getBoundingClientRect();
  990. const maxX = window.innerWidth - rect.width;
  991. const maxY = window.innerHeight - rect.height;
  992.  
  993. // 現在の位置を取得(getBoundingClientRectを使用)
  994. const currentTop = rect.top;
  995. const currentLeft = rect.left;
  996.  
  997. // 新しい位置を設定(window.scrollY/Xを考慮)
  998. const newTop = Math.min(Math.max(0, currentTop + window.scrollY), maxY + window.scrollY);
  999. const newLeft = Math.min(Math.max(0, currentLeft + window.scrollX), maxX + window.scrollX);
  1000.  
  1001. // 位置を設定(pxを付与)
  1002. popup.style.top = `${newTop}px`;
  1003. popup.style.left = `${newLeft}px`;
  1004.  
  1005. // 位置を保存
  1006. savePopupPosition(popup);
  1007. };
  1008.  
  1009. // MutationObserverでポップアップの高さ変更を監視
  1010. const observePopupSize = (popup) => {
  1011. const observer = new MutationObserver((mutations) => {
  1012. adjustPopupPosition(popup);
  1013. });
  1014.  
  1015. observer.observe(popup, {
  1016. attributes: true,
  1017. childList: true,
  1018. subtree: true
  1019. });
  1020. };
  1021.  
  1022. // ポップアップの位置を保存(廃止してsavePopupStateに統合)
  1023. const savePopupPosition = (popup) => {
  1024. savePopupState(popup);
  1025. };
  1026.  
  1027. // ポップアップの状態を復元を修正
  1028. const restorePopupState = (popup) => {
  1029. const savedState = localStorage.getItem('naimodPopupState');
  1030. if (savedState) {
  1031. const state = JSON.parse(savedState);
  1032.  
  1033. // 位置の復元(初期値を設定)
  1034. popup.style.top = state.position.top || '20px';
  1035. popup.style.left = state.position.left || '20px';
  1036. popup.style.width = state.size?.width || '300px';
  1037.  
  1038. // 開閉状態の復元
  1039. const content = popup.querySelector('.naimod-popup-content');
  1040. const foldButton = popup.querySelector('.naimod-toggle-button');
  1041. if (state.isCollapsed) {
  1042. content.style.display = 'none';
  1043. foldButton.innerHTML = '🟥';
  1044. } else {
  1045. content.style.display = 'block';
  1046. foldButton.innerHTML = '🟩';
  1047. }
  1048.  
  1049. // attach/detach状態の復元
  1050. document.body.dataset.naimodAttached = state.isAttached ? "1" : "0";
  1051. } else {
  1052. // デフォルト値の設定
  1053. popup.style.top = '20px';
  1054. popup.style.left = '20px';
  1055. popup.style.width = '300px';
  1056. document.body.dataset.naimodAttached = "1";
  1057. }
  1058.  
  1059. // 位置の調整のみ実行(保存はしない)
  1060. requestAnimationFrame(() => {
  1061. const rect = popup.getBoundingClientRect();
  1062. const maxX = window.innerWidth - rect.width;
  1063. const maxY = window.innerHeight - rect.height;
  1064. const newTop = Math.min(Math.max(0, rect.top + window.scrollY), maxY + window.scrollY);
  1065. const newLeft = Math.min(Math.max(0, rect.left + window.scrollX), maxX + window.scrollX);
  1066. popup.style.top = `${newTop}px`;
  1067. popup.style.left = `${newLeft}px`;
  1068. });
  1069. };
  1070.  
  1071. // ポップアップの状態を保存も更新
  1072. const savePopupState = (popup) => {
  1073. const state = {
  1074. position: {
  1075. top: popup.style.top,
  1076. left: popup.style.left
  1077. },
  1078. size: {
  1079. width: popup.style.width
  1080. },
  1081. isCollapsed: popup.querySelector('.naimod-popup-content').style.display === 'none',
  1082. isAttached: document.body.dataset.naimodAttached === "1"
  1083. };
  1084. console.debug("Saving popup state:", state);
  1085. localStorage.setItem('naimodPopupState', JSON.stringify(state));
  1086. };
  1087.  
  1088. // ドラッグ機能の実装を修正(位置保存を追加)
  1089. const makeDraggable = (element, handle) => {
  1090. let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  1091. let isDragging = false;
  1092.  
  1093. // マウスイベントハンドラー
  1094. const dragMouseDown = (e) => {
  1095. if (e.target === handle || e.target.parentElement === handle) {
  1096. e.preventDefault();
  1097. startDragging(e.clientX, e.clientY);
  1098. document.addEventListener('mouseup', closeDragElement);
  1099. document.addEventListener('mousemove', elementDrag);
  1100. }
  1101. };
  1102.  
  1103. // タッチイベントハンドラー
  1104. const dragTouchStart = (e) => {
  1105. if (e.target === handle || e.target.parentElement === handle) {
  1106. e.preventDefault();
  1107. const touch = e.touches[0];
  1108. startDragging(touch.clientX, touch.clientY);
  1109. document.addEventListener('touchend', closeDragElement);
  1110. document.addEventListener('touchmove', elementDragTouch);
  1111. }
  1112. };
  1113.  
  1114. // ドラッグ開始時の共通処理
  1115. const startDragging = (clientX, clientY) => {
  1116. isDragging = true;
  1117. pos3 = clientX;
  1118. pos4 = clientY;
  1119. };
  1120.  
  1121. // マウスでのドラッグ
  1122. const elementDrag = (e) => {
  1123. if (!isDragging) return;
  1124. e.preventDefault();
  1125. updateElementPosition(e.clientX, e.clientY);
  1126. };
  1127.  
  1128. // タッチでのドラッグ
  1129. const elementDragTouch = (e) => {
  1130. if (!isDragging) return;
  1131. e.preventDefault();
  1132. const touch = e.touches[0];
  1133. updateElementPosition(touch.clientX, touch.clientY);
  1134. };
  1135.  
  1136. // 位置更新の共通処理
  1137. const updateElementPosition = (clientX, clientY) => {
  1138. pos1 = pos3 - clientX;
  1139. pos2 = pos4 - clientY;
  1140. pos3 = clientX;
  1141. pos4 = clientY;
  1142.  
  1143. const newTop = element.offsetTop - pos2;
  1144. const newLeft = element.offsetLeft - pos1;
  1145.  
  1146. const maxX = window.innerWidth - element.offsetWidth;
  1147. const maxY = window.innerHeight - element.offsetHeight;
  1148.  
  1149. element.style.top = `${Math.min(Math.max(0, newTop), maxY)}px`;
  1150. element.style.left = `${Math.min(Math.max(0, newLeft), maxX)}px`;
  1151. };
  1152.  
  1153. // ドラッグ終了時の共通処理
  1154. const closeDragElement = () => {
  1155. isDragging = false;
  1156. document.removeEventListener('mouseup', closeDragElement);
  1157. document.removeEventListener('mousemove', elementDrag);
  1158. document.removeEventListener('touchend', closeDragElement);
  1159. document.removeEventListener('touchmove', elementDragTouch);
  1160. savePopupPosition(element);
  1161. };
  1162.  
  1163. // イベントリスナーの設定
  1164. handle.addEventListener('mousedown', dragMouseDown);
  1165. handle.addEventListener('touchstart', dragTouchStart, { passive: false });
  1166. };
  1167.  
  1168. /**
  1169. * メインUIを作成する
  1170. * @returns {Element} 作成されたUIのルート要素
  1171. */
  1172. const createMainUI = () => {
  1173. console.debug("Creating main UI");
  1174. // 既存のポップアップがあれば削除
  1175. const existingEmbeddings = document.getElementById("naimod-popup");
  1176. if (existingEmbeddings) {
  1177. existingEmbeddings.remove();
  1178. }
  1179.  
  1180. // メインのポップアップコンテナ
  1181. const popup = document.createElement("div");
  1182. popup.id = "naimod-popup";
  1183. popup.className = "naimod-popup";
  1184.  
  1185. // ヘッダー部分
  1186. const header = document.createElement("div");
  1187. header.className = "naimod-popup-header";
  1188.  
  1189. // タイトル
  1190. const title = document.createElement("h2");
  1191. title.textContent = "NovelAI Mod";
  1192. header.appendChild(title);
  1193.  
  1194. // ボタンコンテナ
  1195. const buttonContainer = document.createElement("div");
  1196. buttonContainer.className = "naimod-button-container";
  1197.  
  1198. // 初期状態の設定
  1199. document.body.dataset.naimodAttached = "1"; // デフォルトはattach状態
  1200.  
  1201. // ボタンを追加
  1202. buttonContainer.appendChild(createFoldButton(popup));
  1203. buttonContainer.appendChild(createSettingsButton());
  1204. buttonContainer.appendChild(createDetachButton());
  1205.  
  1206. header.appendChild(buttonContainer);
  1207.  
  1208. // コンテンツ部分
  1209. const content = document.createElement("div");
  1210. content.className = "naimod-popup-content";
  1211. content.id = "naimod-popup-content";
  1212.  
  1213. // 設置場所未定。後で考える。
  1214. //const jpegButton = createButton("JPEG", "green", saveJpeg);
  1215.  
  1216. // Chantsフィールドのタイトルとフィールド
  1217. const chantsSection = document.createElement("div");
  1218. chantsSection.className = "naimod-section";
  1219. const chantsTitle = document.createElement("h3");
  1220. chantsTitle.textContent = "Chants";
  1221. chantsTitle.className = "naimod-section-title";
  1222. chantsSection.appendChild(chantsTitle);
  1223. const chantsField = document.createElement("div");
  1224. chantsField.id = "chantsField";
  1225. chantsField.className = "naimod-chants-field";
  1226. addChantsButtons(chantsField);
  1227. chantsSection.appendChild(chantsField);
  1228. content.appendChild(chantsSection);
  1229.  
  1230. // サジェストフィールドのタイトルとフィールド
  1231. const suggestSection = document.createElement("div");
  1232. suggestSection.className = "naimod-section";
  1233. const suggestTitle = document.createElement("h3");
  1234. suggestTitle.textContent = "Tag Suggestions";
  1235. suggestTitle.className = "naimod-section-title";
  1236. suggestSection.appendChild(suggestTitle);
  1237. const suggestionField = document.createElement("div");
  1238. suggestionField.id = "suggestionField";
  1239. suggestionField.className = "naimod-suggestion-field";
  1240. suggestSection.appendChild(suggestionField);
  1241. content.appendChild(suggestSection);
  1242.  
  1243. // 関連タグフィールドのタイトルとフィールド
  1244. const relatedSection = document.createElement("div");
  1245. relatedSection.className = "naimod-section";
  1246. const relatedTitle = document.createElement("h3");
  1247. relatedTitle.textContent = "Related Tags";
  1248. relatedTitle.className = "naimod-section-title";
  1249. relatedSection.appendChild(relatedTitle);
  1250. const relatedTagsField = document.createElement("div");
  1251. relatedTagsField.id = "relatedTagsField";
  1252. relatedTagsField.className = "naimod-related-tags-field";
  1253. relatedSection.appendChild(relatedTagsField);
  1254. content.appendChild(relatedSection);
  1255.  
  1256. popup.appendChild(header);
  1257. popup.appendChild(content);
  1258.  
  1259. // スタイルの追加
  1260. addStyles();
  1261.  
  1262. // 状態を復元(位置と開閉状態)
  1263. restorePopupState(popup);
  1264.  
  1265. // ドラッグ可能にする
  1266. makeDraggable(popup, header);
  1267.  
  1268. // サイズ変更の監視を開始
  1269. observePopupSize(popup);
  1270.  
  1271. // リサイズハンドルを設定
  1272. setupResizeHandles(popup);
  1273.  
  1274. return popup;
  1275. };
  1276.  
  1277. const createEmbeddingsUI = () => {
  1278. console.debug("Creating embeddings UI");
  1279. // 既存のポップアップがあれば削除
  1280. const existingEmbeddings = document.getElementById("naimod-embeddings");
  1281. if (existingEmbeddings) {
  1282. existingEmbeddings.remove();
  1283. }
  1284.  
  1285. const ui = document.createElement("div");
  1286. ui.id = "naimod-embeddings";
  1287. ui.className = "naimod-embeddings";
  1288.  
  1289. const header = document.createElement("div");
  1290. header.className = "naimod-popup-header";
  1291.  
  1292. const title = document.createElement("h2");
  1293. title.textContent = "NovelAI Mod";
  1294. header.appendChild(title);
  1295.  
  1296. // ボタンコンテナ
  1297. const buttonContainer = document.createElement("div");
  1298. buttonContainer.className = "naimod-button-container";
  1299.  
  1300. // settingsとattachボタンのみを追加
  1301. buttonContainer.appendChild(createSettingsButton());
  1302. buttonContainer.appendChild(createDetachButton());
  1303.  
  1304. header.appendChild(buttonContainer);
  1305.  
  1306. ui.appendChild(header);
  1307.  
  1308. const content = document.createElement("div");
  1309. content.id = "naimod-embeddings-content";
  1310. content.className = "naimod-embeddings-content";
  1311. ui.appendChild(content);
  1312.  
  1313. // イベントリスナーを修正
  1314. ui.addEventListener("click", (e) => {
  1315. // クリックされた要素がbuttonまたはその子要素の場合
  1316. const button = e.target.closest('button');
  1317. if (button) {
  1318. // ポップアップ内の対応するボタンを探す
  1319. const popupContent = document.querySelector('#naimod-popup-content');
  1320. if (popupContent) {
  1321. // ボタンのテキストコンテンツを取得
  1322. const buttonText = button.textContent.trim();
  1323. const matchingButton = Array.from(popupContent.querySelectorAll('button'))
  1324. .find(btn => btn.textContent.trim() === buttonText);
  1325.  
  1326. // 一致するボタンが見つかった場合はクリックイベントを発火
  1327. if (matchingButton) {
  1328. matchingButton.click();
  1329. }
  1330. }
  1331. }
  1332. // カテゴリヘッダーのクリック処理を追加
  1333. const categoryHeader = e.target.closest('.naimod-category-header');
  1334. if (categoryHeader) {
  1335. const popupContent = document.querySelector('#naimod-popup-content');
  1336. if (popupContent) {
  1337. // カテゴリヘッダーのテキストコンテンツを取得(カテゴリ名と数を含む)
  1338. const headerText = categoryHeader.querySelector('span:first-child').textContent.trim();
  1339. // ポップアップ内の対応するカテゴリヘッダーを探す
  1340. const matchingHeader = Array.from(popupContent.querySelectorAll('.naimod-category-header'))
  1341. .find(header => header.querySelector('span:first-child').textContent.trim() === headerText);
  1342. // 一致するヘッダーが見つかった場合はクリックイベントを発火
  1343. if (matchingHeader) {
  1344. matchingHeader.click();
  1345. clonePopupContentsToEmbeddings();
  1346. }
  1347. }
  1348. }
  1349. });
  1350.  
  1351. return ui;
  1352. };
  1353.  
  1354. const clonePopupContentsToEmbeddings = () => {
  1355. const content = document.querySelector("#naimod-embeddings-content");
  1356. content.innerHTML = document.querySelector("#naimod-popup-content").innerHTML;
  1357. // カテゴリコンテンツの表示状態を同期
  1358. const popupCategories = document.querySelectorAll("#naimod-popup-content .naimod-category-container");
  1359. const embeddingCategories = document.querySelectorAll("#naimod-embeddings-content .naimod-category-container");
  1360. if (popupCategories.length === embeddingCategories.length) {
  1361. for (let i = 0; i < popupCategories.length; i++) {
  1362. const popupContent = popupCategories[i].querySelector('.naimod-category-content');
  1363. const embeddingContent = embeddingCategories[i].querySelector('.naimod-category-content');
  1364. if (popupContent && embeddingContent) {
  1365. // 表示状態を同期
  1366. embeddingContent.style.display = popupContent.style.display;
  1367. // ドロップダウンアイコンも同期
  1368. const popupIcon = popupCategories[i].querySelector('.naimod-dropdown-icon');
  1369. const embeddingIcon = embeddingCategories[i].querySelector('.naimod-dropdown-icon');
  1370. if (popupIcon && embeddingIcon) {
  1371. embeddingIcon.textContent = popupIcon.textContent;
  1372. }
  1373. }
  1374. }
  1375. }
  1376. };
  1377.  
  1378. // スタイルの追加を修正
  1379. const addStyles = () => {
  1380. if (document.getElementById('naimod-styles')) return;
  1381.  
  1382. const style = document.createElement('style');
  1383. style.id = 'naimod-styles';
  1384. style.textContent = `
  1385.  
  1386. /* ==========================================================================
  1387. 基本設定
  1388. ========================================================================== */
  1389. #imageSource {
  1390. color: black;
  1391. }
  1392.  
  1393. /* ==========================================================================
  1394. モーダル基本レイアウト
  1395. ========================================================================== */
  1396. .naimod-modal {
  1397. display: none;
  1398. position: fixed;
  1399. z-index: 1000;
  1400. left: 0;
  1401. top: 0;
  1402. width: 100%;
  1403. height: 100%;
  1404. background-color: rgba(0, 0, 0, 0.6);
  1405. overflow: hidden;
  1406. }
  1407.  
  1408. .naimod-settings-content {
  1409. width: 90%;
  1410. max-width: 1200px;
  1411. height: 90vh;
  1412. padding: 20px;
  1413. position: absolute;
  1414. left: 50%;
  1415. top: 50%;
  1416. transform: translate(-50%, -50%);
  1417. display: flex;
  1418. flex-direction: column;
  1419. background-color: rgba(0, 0, 64, 0.9);
  1420. color: #fff;
  1421. border-radius: 10px;
  1422. box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
  1423. }
  1424.  
  1425. /* ==========================================================================
  1426. ポップアップ関連
  1427. ========================================================================== */
  1428. .naimod-popup {
  1429. position: fixed;
  1430. top: 20px;
  1431. right: 20px;
  1432. background-color: rgba(0, 0, 64, 0.9);
  1433. border: 1px solid #ccc;
  1434. border-radius: 5px;
  1435. z-index: 10000;
  1436. width: 300px;
  1437. max-height: 90vh;
  1438. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  1439. color: white;
  1440. user-select: none;
  1441. display: flex;
  1442. flex-direction: column;
  1443. opacity: 0.85;
  1444. position: relative;
  1445. min-width: 200px;
  1446. max-width: 800px;
  1447. }
  1448.  
  1449. .naimod-popup-header {
  1450. padding: 0px 10px;
  1451. background-color: rgba(0, 0, 80, 0.95);
  1452. border-bottom: 1px solid #ccc;
  1453. cursor: move;
  1454. display: flex;
  1455. justify-content: space-between;
  1456. align-items: center;
  1457. user-select: none;
  1458. flex-shrink: 0;
  1459. }
  1460.  
  1461. .naimod-popup-header h2 {
  1462. margin: 0;
  1463. font-size: 0.9em;
  1464. pointer-events: none;
  1465. }
  1466.  
  1467. .naimod-popup-content {
  1468. padding: 5px;
  1469. overflow-y: auto;
  1470. width: 100%;
  1471. box-sizing: border-box;
  1472. flex: 1;
  1473. min-height: 0;
  1474. }
  1475. .naimod-resize-handle {
  1476. position: absolute;
  1477. top: 0;
  1478. bottom: 0;
  1479. width: 6px;
  1480. cursor: ew-resize;
  1481. z-index: 1000;
  1482. }
  1483. .naimod-resize-handle.left {
  1484. left: -3px;
  1485. }
  1486. .naimod-resize-handle.right {
  1487. right: -3px;
  1488. }
  1489. /* ==========================================================================
  1490. 埋め込みモード
  1491. ========================================================================== */
  1492. #naimod-embeddings-content {
  1493. background-color: rgba(0, 0, 64, 0.9);
  1494. }
  1495.  
  1496. .naimod-embeddings-content {
  1497. padding: 5px;
  1498. overflow-y: auto;
  1499. width: 100%;
  1500. box-sizing: border-box;
  1501. flex: 1;
  1502. min-height: 0;
  1503. }
  1504.  
  1505. body[data-naimod-attached="1"] #__next {
  1506. width: calc(100% - 20vh) !important;
  1507. right: 0;
  1508. }
  1509.  
  1510. body[data-naimod-attached="1"] #naimod-embeddings {
  1511. width: 20vh;
  1512. right: 0;
  1513. height: 100vh;
  1514. }
  1515.  
  1516. body[data-naimod-attached="1"] #naimod-embeddings .naimod-popup-header {
  1517. height: 5vh;
  1518. }
  1519. body[data-naimod-attached="1"] #naimod-embeddings .naimod-embeddings-content {
  1520. height: 95vh;
  1521. }
  1522.  
  1523. body[data-naimod-attached="1"] #naimod-popup {
  1524. visibility: hidden;
  1525. }
  1526.  
  1527. body[data-naimod-attached="1"] .naimod-toggle-button-anchor {
  1528. display: none;
  1529. }
  1530.  
  1531. body[data-naimod-attached="1"] .naimod-toggle-button-ship {
  1532. display: block;
  1533. }
  1534.  
  1535. body[data-naimod-attached="0"] .naimod-toggle-button-anchor {
  1536. display: block;
  1537. }
  1538.  
  1539. body[data-naimod-attached="0"] .naimod-toggle-button-ship {
  1540. display: none;
  1541. }
  1542.  
  1543. @media screen and (max-width: 900px) {
  1544. body[data-naimod-attached="1"] #__next {
  1545. top: 5vh;
  1546. }
  1547. body[data-naimod-attached="1"] #__next {
  1548. width: 100% !important;
  1549. }
  1550. body[data-naimod-attached="1"] #naimod-embeddings {
  1551. width: 100% !important;
  1552. }
  1553. body[data-naimod-attached="1"] #naimod-embeddings-content {
  1554. display: none;
  1555. }
  1556. body[data-naimod-attached="1"] .naimod-search-suggestion-menu {
  1557. display: none;
  1558. }
  1559. body[data-naimod-attached="1"] .naimod-contextmenu-suggestion-title {
  1560. display: none;
  1561. }
  1562. body[data-naimod-attached="1"] .naimod-contextmenu-suggestions {
  1563. margin-top: 0;
  1564. border-top: none;
  1565. padding-top: 0;
  1566. }
  1567. }
  1568.  
  1569. /* ==========================================================================
  1570. 2ペインレイアウト
  1571. ========================================================================== */
  1572. .naimod-modal-two-pane {
  1573. display: flex;
  1574. gap: 20px;
  1575. flex: 1;
  1576. overflow: hidden;
  1577. padding-bottom: 70px;
  1578. }
  1579.  
  1580. .naimod-modal-pane {
  1581. padding: 20px;
  1582. background-color: rgba(0, 0, 32, 0.5);
  1583. border-radius: 8px;
  1584. overflow-y: auto;
  1585. max-height: 100%;
  1586. }
  1587.  
  1588. .settings-pane {
  1589. width: 300px;
  1590. flex-shrink: 0;
  1591. }
  1592.  
  1593. .operation-pane {
  1594. flex: 1;
  1595. min-width: 600px;
  1596. }
  1597.  
  1598.  
  1599. /* ==========================================================================
  1600. コントロール要素
  1601. ========================================================================== */
  1602. /* ボタン */
  1603. .naimod-button {
  1604. background: none;
  1605. border: 1px solid currentColor;
  1606. padding: 5px 10px;
  1607. margin: 5px;
  1608. border-radius: 3px;
  1609. cursor: pointer;
  1610. color: white;
  1611. transition: opacity 0.3s;
  1612. }
  1613.  
  1614. .naimod-button:hover {
  1615. opacity: 0.8;
  1616. }
  1617.  
  1618. .naimod-button:disabled {
  1619. opacity: 0.5;
  1620. cursor: not-allowed;
  1621. }
  1622.  
  1623. .naimod-operation-button {
  1624. flex: 1;
  1625. padding: 8px 15px;
  1626. font-size: 1em;
  1627. border: 1px solid rgba(255, 255, 255, 0.3);
  1628. background-color: rgba(0, 0, 0, 0.2);
  1629. color: white;
  1630. border-radius: 4px;
  1631. cursor: pointer;
  1632. transition: all 0.2s;
  1633. }
  1634.  
  1635. .naimod-operation-button:hover {
  1636. background-color: rgba(255, 255, 255, 0.1);
  1637. }
  1638.  
  1639. .naimod-operation-button:disabled {
  1640. opacity: 0.5;
  1641. cursor: not-allowed;
  1642. }
  1643.  
  1644. .naimod-operation-button[data-color="blue"] {
  1645. border-color: rgba(52, 152, 219, 0.5);
  1646. }
  1647.  
  1648. .naimod-operation-button[data-color="green"] {
  1649. border-color: rgba(46, 204, 113, 0.5);
  1650. }
  1651.  
  1652. /* 入力フィールド */
  1653. .naimod-input {
  1654. width: 100%;
  1655. padding: 8px;
  1656. border: 1px solid rgba(255, 255, 255, 0.2);
  1657. border-radius: 4px;
  1658. background-color: rgba(0, 0, 0, 0.2);
  1659. color: white;
  1660. font-size: 14px;
  1661. }
  1662.  
  1663. .naimod-input:focus {
  1664. outline: none;
  1665. border-color: rgba(255, 255, 255, 0.4);
  1666. background-color: rgba(0, 0, 0, 0.3);
  1667. }
  1668.  
  1669. .naimod-toggle-button {
  1670. background: none;
  1671. border: none;
  1672. color: white;
  1673. cursor: pointer;
  1674. font-size: 1rem;
  1675. padding: 0 5px;
  1676. z-index: 1;
  1677. }
  1678.  
  1679. /* ==========================================================================
  1680. タグ関連
  1681. ========================================================================== */
  1682. .naimod-tag-button {
  1683. background-color: white;
  1684. border: 1px solid currentColor;
  1685. padding: 3px 8px;
  1686. margin: 3px;
  1687. border-radius: 3px;
  1688. cursor: pointer;
  1689. font-size: 0.9em;
  1690. transition: all 0.2s;
  1691. }
  1692.  
  1693. .naimod-tag-button:hover {
  1694. opacity: 0.8;
  1695. }
  1696.  
  1697. .naimod-tag {
  1698. display: inline-block;
  1699. padding: 2px 8px;
  1700. margin: 2px;
  1701. background-color: rgba(255, 255, 255, 0.1);
  1702. border-radius: 3px;
  1703. color: white;
  1704. }
  1705.  
  1706. /* ==========================================================================
  1707. 画像アップロード関連
  1708. ========================================================================== */
  1709. .naimod-image-source-container {
  1710. background-color: rgba(0, 0, 32, 0.5);
  1711. border-radius: 5px;
  1712. padding: 15px;
  1713. margin-bottom: 20px;
  1714. }
  1715.  
  1716. .naimod-upload-container {
  1717. width: 100%;
  1718. height: 200px;
  1719. border: 2px dashed rgba(255, 255, 255, 0.3);
  1720. display: flex;
  1721. justify-content: center;
  1722. align-items: center;
  1723. margin: 10px 0;
  1724. cursor: pointer;
  1725. position: relative;
  1726. background-color: rgba(0, 0, 0, 0.2);
  1727. border-radius: 5px;
  1728. }
  1729.  
  1730. .naimod-preview-image {
  1731. max-width: 100%;
  1732. max-height: 200px;
  1733. object-fit: contain;
  1734. border-radius: 5px;
  1735. }
  1736.  
  1737. /* ==========================================================================
  1738. スクロールバー
  1739. ========================================================================== */
  1740. .naimod-natural-language-content::-webkit-scrollbar,
  1741. .naimod-pane.right-pane::-webkit-scrollbar {
  1742. width: 8px;
  1743. }
  1744.  
  1745. .naimod-natural-language-content::-webkit-scrollbar-track,
  1746. .naimod-pane.right-pane::-webkit-scrollbar-track {
  1747. background: rgba(0, 0, 0, 0.1);
  1748. border-radius: 4px;
  1749. }
  1750.  
  1751. .naimod-natural-language-content::-webkit-scrollbar-thumb,
  1752. .naimod-pane.right-pane::-webkit-scrollbar-thumb {
  1753. background: rgba(255, 255, 255, 0.2);
  1754. border-radius: 4px;
  1755. }
  1756.  
  1757. .naimod-natural-language-content::-webkit-scrollbar-thumb:hover,
  1758. .naimod-pane.right-pane::-webkit-scrollbar-thumb:hover {
  1759. background: rgba(255, 255, 255, 0.3);
  1760. }
  1761.  
  1762. /* ==========================================================================
  1763. レスポンシブ対応
  1764. ========================================================================== */
  1765. @media screen and (max-width: 1400px) {
  1766. .naimod-settings-content {
  1767. max-width: 1000px;
  1768. }
  1769. }
  1770.  
  1771. @media screen and (max-width: 1200px) {
  1772. .naimod-settings-content {
  1773. max-width: 900px;
  1774. }
  1775. }
  1776.  
  1777. @media screen and (max-width: 1000px) {
  1778. .naimod-settings-content {
  1779. max-width: 800px;
  1780. }
  1781. }
  1782.  
  1783. @media screen and (max-width: 900px) {
  1784. .naimod-settings-content {
  1785. width: 95%;
  1786. height: 95vh;
  1787. margin: 0;
  1788. padding: 10px;
  1789. }
  1790.  
  1791. .naimod-modal-two-pane {
  1792. flex-direction: column;
  1793. gap: 10px;
  1794. min-height: auto;
  1795. }
  1796.  
  1797. .settings-pane,
  1798. .operation-pane {
  1799. width: 100%;
  1800. min-width: 0;
  1801. }
  1802.  
  1803. .naimod-operation-section {
  1804. height: auto;
  1805. min-height: 400px;
  1806. }
  1807. }
  1808.  
  1809. /* ==========================================================================
  1810. セクションとコンテンツ
  1811. ========================================================================== */
  1812. .naimod-section-title {
  1813. color: white;
  1814. font-size: 0.9rem;
  1815. margin: 10px 0 5px 0;
  1816. padding-bottom: 3px;
  1817. border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  1818. }
  1819.  
  1820. .naimod-section {
  1821. margin-bottom: 20px;
  1822. }
  1823.  
  1824. .naimod-controls {
  1825. display: flex;
  1826. gap: 10px;
  1827. margin-bottom: 10px;
  1828. }
  1829.  
  1830. .naimod-chants-field {
  1831. display: flex;
  1832. flex-wrap: wrap;
  1833. gap: 5px;
  1834. margin-bottom: 10px;
  1835. }
  1836.  
  1837. .naimod-suggestion-field {
  1838. overflow-y: auto;
  1839. border-top: 1px solid #ccc;
  1840. padding-top: 10px;
  1841. }
  1842.  
  1843. .naimod-related-tags-field {
  1844. overflow-y: auto;
  1845. margin-bottom: 10px;
  1846. padding: 5px;
  1847. border-radius: 3px;
  1848. background-color: rgba(0, 0, 0, 0.2);
  1849. }
  1850.  
  1851. /* ==========================================================================
  1852. ナチュラルランゲージコンテナ
  1853. ========================================================================== */
  1854. .naimod-natural-language-container {
  1855. background: none;
  1856. padding: 0;
  1857. margin-top: 20px;
  1858. }
  1859.  
  1860. .naimod-natural-language-content {
  1861. max-height: 300px;
  1862. overflow-y: auto;
  1863. padding: 15px;
  1864. background-color: rgba(0, 0, 0, 0.2);
  1865. border-radius: 5px;
  1866. white-space: pre-wrap;
  1867. word-break: break-word;
  1868. color: white;
  1869. font-size: 0.9em;
  1870. line-height: 1.4;
  1871. margin: 10px 0;
  1872. }
  1873.  
  1874. /* ==========================================================================
  1875. ボタンコンテナと操作セクション
  1876. ========================================================================== */
  1877. .naimod-button-container {
  1878. display: flex;
  1879. flex-shrink: 0;
  1880. }
  1881.  
  1882. .naimod-close-button-container {
  1883. position: absolute;
  1884. bottom: 0;
  1885. left: 0;
  1886. right: 0;
  1887. background-color: rgba(0, 0, 64, 0.9);
  1888. padding: 15px;
  1889. border-top: 1px solid rgba(255, 255, 255, 0.2);
  1890. text-align: center;
  1891. }
  1892.  
  1893. .naimod-operation-section {
  1894. background-color: rgba(0, 0, 32, 0.5);
  1895. border-radius: 8px;
  1896. padding: 15px;
  1897. flex-direction: column;
  1898. margin-bottom: 20px;
  1899. }
  1900.  
  1901. /* ==========================================================================
  1902. タグセクション
  1903. ========================================================================== */
  1904. .tag-section {
  1905. margin-bottom: 15px;
  1906. }
  1907.  
  1908. .tag-section h3 {
  1909. color: white;
  1910. font-size: 1.1em;
  1911. margin: 10px 0;
  1912. padding-bottom: 5px;
  1913. border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  1914. }
  1915.  
  1916. /* ==========================================================================
  1917. 右ペイン
  1918. ========================================================================== */
  1919. .naimod-pane.right-pane {
  1920. flex: 1;
  1921. overflow-y: auto;
  1922. background-color: rgba(0, 0, 0, 0.2);
  1923. border-radius: 5px;
  1924. padding: 15px;
  1925. margin-top: 10px;
  1926. margin-bottom: 10px;
  1927. min-height: 200px;
  1928. }
  1929.  
  1930. /* ==========================================================================
  1931. 画像ソース選択
  1932. ========================================================================== */
  1933. .naimod-image-source-select {
  1934. width: 100%;
  1935. padding: 8px;
  1936. margin-bottom: 10px;
  1937. background-color: rgba(0, 0, 0, 0.2);
  1938. border: 1px solid rgba(255, 255, 255, 0.2);
  1939. color: white;
  1940. border-radius: 4px;
  1941. }
  1942.  
  1943. .naimod-image-source-select:focus {
  1944. outline: none;
  1945. border-color: rgba(255, 255, 255, 0.4);
  1946. }
  1947.  
  1948. /* コンテキストメニューのスタイル */
  1949. .naimod-contextmenu {
  1950. background-color: rgba(0, 0, 64, 0.9);
  1951. border: 1px solid #ccc;
  1952. border-radius: 3px;
  1953. padding: 5px;
  1954. color: white;
  1955. user-select: none;
  1956. box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  1957. min-width: 180px;
  1958. font-size: 0.9rem;
  1959. }
  1960.  
  1961. .naimod-search-suggestion-menu {
  1962. padding: 5px 8px;
  1963. cursor: pointer;
  1964. transition: background-color 0.2s;
  1965. }
  1966.  
  1967. .naimod-search-suggestion-menu:hover {
  1968. background-color: rgba(255, 255, 255, 0.1);
  1969. }
  1970.  
  1971. .naimod-contextmenu-separator {
  1972. height: 1px;
  1973. background-color: rgba(255, 255, 255, 0.2);
  1974. margin: 5px 0;
  1975. }
  1976.  
  1977. .naimod-contextmenu-suggestions {
  1978. margin-top: 5px;
  1979. border-top: 1px solid rgba(255, 255, 255, 0.2);
  1980. padding-top: 5px;
  1981. }
  1982.  
  1983. .naimod-contextmenu-suggestion-title {
  1984. font-size: 0.85rem;
  1985. color: rgba(255, 255, 255, 0.7);
  1986. margin-bottom: 5px;
  1987. padding: 0 8px;
  1988. }
  1989.  
  1990. .naimod-contextmenu-suggestion-item {
  1991. font-size: 0.85rem;
  1992. border-radius: 3px;
  1993. margin: 3px 0;
  1994. cursor: pointer;
  1995. transition: opacity 0.2s;
  1996. }
  1997.  
  1998. .naimod-contextmenu-suggestion-item:hover {
  1999. opacity: 0.8;
  2000. }
  2001.  
  2002. /* ==========================================================================
  2003. 関連タグのカテゴリ表示
  2004. ========================================================================== */
  2005. .naimod-category-container {
  2006. margin-bottom: 10px;
  2007. }
  2008.  
  2009. .naimod-category-header {
  2010. transition: background-color 0.2s;
  2011. }
  2012.  
  2013. .naimod-category-header:hover {
  2014. filter: brightness(1.1);
  2015. }
  2016.  
  2017. .naimod-category-content {
  2018. padding: 5px;
  2019. max-height: 300px;
  2020. overflow-y: auto;
  2021. margin-bottom: 10px;
  2022. }
  2023.  
  2024. .naimod-dropdown-icon {
  2025. font-size: 12px;
  2026. transition: transform 0.3s;
  2027. }
  2028.  
  2029. .naimod-related-tags-field {
  2030. max-height: 600px;
  2031. overflow-y: auto;
  2032. }
  2033. `;
  2034. document.head.appendChild(style);
  2035. };
  2036.  
  2037. // Build関数の名前を変更
  2038. const initializeApplication = async () => {
  2039. console.debug("Initializing application");
  2040. console.debug("Application initialization started");
  2041.  
  2042. // スタイルの適用
  2043. addStyles();
  2044.  
  2045. // モーダルの作成
  2046. createSettingsModal();
  2047.  
  2048. // メインUIの作成と配置
  2049. document.body.appendChild(createMainUI());
  2050.  
  2051. document.body.appendChild(createEmbeddingsUI());
  2052.  
  2053. // コンテキストメニューの作成
  2054. createContextMenu();
  2055.  
  2056. // 関連タグの状態を復元
  2057. restoreRelatedTags();
  2058.  
  2059. // アスペクト比の更新
  2060. updateAspectRatio();
  2061.  
  2062.  
  2063. clonePopupContentsToEmbeddings();
  2064. };
  2065.  
  2066. const createDisplayAspect = () => {
  2067. let displayAspect = document.createElement("div");
  2068. displayAspect.id = "displayAspect";
  2069. let container = document.createElement("div");
  2070. container.style.maxWidth = "130px";
  2071. container.style.display = "flex";
  2072. let [widthAspect, heightAspect] = ['width', 'height'].map(type => {
  2073. let input = document.createElement("input");
  2074. input.type = "number";
  2075. return input;
  2076. });
  2077. let largeCheck = document.createElement("input");
  2078. largeCheck.type = "checkbox";
  2079. largeCheck.title = "Check to large size.";
  2080. let submitButton = document.createElement("input");
  2081. submitButton.type = "submit";
  2082. submitButton.value = "Aspect => Pixel";
  2083.  
  2084. [widthAspect, heightAspect].forEach(input => {
  2085. const baseInput = document.querySelector('input[type="number"][step="64"]');
  2086. if (baseInput) {
  2087. baseInput.classList.forEach(x => input.classList.add(x));
  2088. }
  2089. });
  2090.  
  2091. [widthAspect, heightAspect, largeCheck].forEach(el => container.appendChild(el));
  2092. [container, submitButton].forEach(el => displayAspect.appendChild(el));
  2093.  
  2094. submitButton.addEventListener("click", () => {
  2095. let wa = widthAspect.value;
  2096. let ha = heightAspect.value;
  2097. let maxpixel = largeCheck.checked ? 1728 * 1792 : 1024 * 1024;
  2098. let as = aspectList(wa, ha, maxpixel);
  2099. if (as.length) {
  2100. updateImageDimensions(...as[as.length - 1]);
  2101. }
  2102. });
  2103.  
  2104. return displayAspect;
  2105. };
  2106.  
  2107. const updateAspectInputs = () => {
  2108. console.debug("updateAspectInputs");
  2109. let displayAspect = document.querySelector("#displayAspect");
  2110. if (displayAspect) {
  2111. let [widthAspect, heightAspect] = displayAspect.querySelectorAll("input");
  2112. let Aspect = getAspect(Array.from(document.querySelectorAll('input[type="number"][step="64"]')).map(x => x.value));
  2113. [widthAspect.value, heightAspect.value] = Aspect;
  2114. }
  2115. };
  2116.  
  2117. // ヘルパー関数
  2118. const createButton = (text, color, onClick) => {
  2119. let button = document.createElement("button");
  2120. button.textContent = text;
  2121. button.style.color = color;
  2122. button.addEventListener("click", onClick);
  2123. return button;
  2124. };
  2125.  
  2126. // 画像ソース選択UIの作成
  2127. const createImageSourceUI = () => {
  2128. let imageSourceLabel = document.createElement("label");
  2129. imageSourceLabel.textContent = "Image Source: ";
  2130.  
  2131. let imageSourceSelect = document.createElement("select");
  2132. imageSourceSelect.id = "imageSource";
  2133. ["current", "uploaded"].forEach(source => {
  2134. let option = document.createElement("option");
  2135. option.value = source;
  2136. option.textContent = source.charAt(0).toUpperCase() + source.slice(1);
  2137. imageSourceSelect.appendChild(option);
  2138. });
  2139.  
  2140. let uploadContainer = document.createElement("div");
  2141. uploadContainer.className = "naimod-upload-container";
  2142. uploadContainer.textContent = "Drag & Drop or Click to Upload";
  2143.  
  2144. let uploadInput = document.createElement("input");
  2145. uploadInput.type = "file";
  2146. uploadInput.id = "naimodUploadedImage";
  2147. uploadInput.accept = "image/*";
  2148. uploadInput.style.display = "none";
  2149.  
  2150. // 画像アップロードハンドラーの設定
  2151. setupImageUploadHandlers(uploadContainer, uploadInput);
  2152.  
  2153. // 初期状態を設定
  2154. imageSourceSelect.value = "current";
  2155. uploadContainer.style.display = "none";
  2156.  
  2157. imageSourceSelect.addEventListener("change", () => {
  2158. uploadContainer.style.display = imageSourceSelect.value === "uploaded" ? "flex" : "none";
  2159. });
  2160.  
  2161. return { imageSourceSelect, uploadContainer };
  2162. };
  2163.  
  2164. // 画像アップロードハンドラーの設定
  2165. const setupImageUploadHandlers = (uploadContainer, uploadInput) => {
  2166. // ファイル選択時の処理
  2167. uploadInput.addEventListener("change", (e) => {
  2168. if (e.target.files && e.target.files[0]) {
  2169. handleImageUpload(e.target.files[0], uploadContainer);
  2170. } else {
  2171. console.error("No file selected");
  2172. alert("ファイルが選択されていません。");
  2173. }
  2174. });
  2175.  
  2176. // クリックでファイル選択
  2177. uploadContainer.addEventListener("click", () => {
  2178. uploadInput.click();
  2179. });
  2180.  
  2181. // ドラッグ&ドロップ処理
  2182. uploadContainer.addEventListener("dragover", (e) => {
  2183. e.preventDefault();
  2184. uploadContainer.style.borderColor = "#000";
  2185. });
  2186.  
  2187. uploadContainer.addEventListener("dragleave", () => {
  2188. uploadContainer.style.borderColor = "#ccc";
  2189. });
  2190.  
  2191. uploadContainer.addEventListener("drop", (e) => {
  2192. e.preventDefault();
  2193. uploadContainer.style.borderColor = "#ccc";
  2194. if (e.dataTransfer.files && e.dataTransfer.files[0]) {
  2195. handleImageUpload(e.dataTransfer.files[0], uploadContainer);
  2196. } else {
  2197. console.error("No file dropped");
  2198. alert("ファイルのドロップに失敗しました。");
  2199. }
  2200. });
  2201.  
  2202. // クリップボードからの画像貼り付け
  2203. document.addEventListener("paste", (e) => {
  2204. if (document.getElementById("imageSource").value === "uploaded") {
  2205. const items = e.clipboardData.items;
  2206. for (let i = 0; i < items.length; i++) {
  2207. if (items[i].type.indexOf("image") !== -1) {
  2208. const blob = items[i].getAsFile();
  2209. handleImageUpload(blob, uploadContainer);
  2210. break;
  2211. }
  2212. }
  2213. }
  2214. });
  2215.  
  2216. uploadContainer.appendChild(uploadInput);
  2217. };
  2218.  
  2219. // 画像アップロード処理
  2220. const handleImageUpload = (file, uploadContainer) => {
  2221. if (file && file.type.startsWith('image/')) {
  2222. const reader = new FileReader();
  2223. reader.onload = (e) => {
  2224. let previewImage = document.getElementById('naimodPreviewImage');
  2225. if (!previewImage) {
  2226. previewImage = document.createElement('img');
  2227. previewImage.id = 'naimodPreviewImage';
  2228. previewImage.className = 'naimod-preview-image';
  2229. }
  2230. previewImage.src = e.target.result;
  2231. previewImage.style.display = "block";
  2232. uploadContainer.textContent = "";
  2233. uploadContainer.appendChild(previewImage);
  2234. };
  2235. reader.onerror = (error) => {
  2236. console.error("Error reading file:", error);
  2237. alert("画像の読み込み中にエラーが発生しました。");
  2238. };
  2239. reader.readAsDataURL(file);
  2240. } else {
  2241. console.error("Invalid file type:", file ? file.type : "No file");
  2242. alert("有効な画像ファイルを選択してください。");
  2243. }
  2244. };
  2245.  
  2246. // 左ペインの作成を修正
  2247. const createLeftPane = () => {
  2248. const container = document.createElement("div");
  2249. container.className = "naimod-pane-container";
  2250.  
  2251. // Suggest AI Improvementsボタン
  2252. let suggestButton = createButton("Suggest AI Improvements", "blue", async () => {
  2253. console.debug("Suggest AI Improvements clicked");
  2254.  
  2255. const rightPane = document.querySelector(".naimod-pane.right-pane");
  2256. if (!rightPane) {
  2257. console.error("Right pane not found");
  2258. return;
  2259. }
  2260.  
  2261. // 自然言語プロンプトの状態をリセット
  2262. const naturalLanguagePrompt = document.getElementById("naturalLanguagePrompt");
  2263. const copyButton = naturalLanguagePrompt?.parentElement?.querySelector("button");
  2264. if (naturalLanguagePrompt) {
  2265. naturalLanguagePrompt.textContent = "Waiting for AI suggestions...";
  2266. if (copyButton) copyButton.style.display = "none";
  2267. }
  2268.  
  2269. // lastFocusedEditorからタグを取得
  2270. const editor = window.getLastFocusedEditor();
  2271. if (!editor) {
  2272. console.error("No editor is focused");
  2273. return;
  2274. }
  2275.  
  2276. console.debug("Getting tags from editor");
  2277. const tags = editor.textContent.trim();
  2278. console.debug("Current tags:", tags);
  2279.  
  2280. if (tags) {
  2281. rightPane.innerHTML = "<div>Loading AI suggestions...</div>";
  2282. suggestButton.disabled = true;
  2283. suggestButton.textContent = "Processing...";
  2284.  
  2285. console.debug("Getting image source");
  2286. let imageSource = document.getElementById("imageSource").value;
  2287. console.debug("Image source:", imageSource);
  2288.  
  2289. console.debug("Getting image DataURL");
  2290. let imageDataURL = await getImageDataURL(imageSource);
  2291.  
  2292. if (!imageDataURL) {
  2293. console.error("Failed to get image DataURL");
  2294. rightPane.innerHTML = "<div>Failed to get image. Please check your image source.</div>";
  2295. suggestButton.disabled = false;
  2296. suggestButton.textContent = "Suggest AI Improvements";
  2297. return;
  2298. }
  2299. console.debug("Got image DataURL, length:", imageDataURL.length);
  2300.  
  2301. console.debug("Calling ImprovementTags");
  2302. let result = await ImprovementTags(tags, imageDataURL);
  2303. console.debug("ImprovementTags result:", result);
  2304.  
  2305. if (result) {
  2306. displaySuggestions(result, rightPane);
  2307. }
  2308. suggestButton.disabled = false;
  2309. suggestButton.textContent = "Suggest AI Improvements";
  2310. } else {
  2311. console.error("No tags found in editor");
  2312. rightPane.innerHTML = "<div>No tags found in editor</div>";
  2313. }
  2314. });
  2315. suggestButton.style.marginBottom = "10px";
  2316. container.appendChild(suggestButton);
  2317.  
  2318. return container;
  2319. };
  2320.  
  2321. // 右ペインの作成を修正
  2322. const createRightPane = () => {
  2323. const container = document.createElement("div");
  2324. container.className = "naimod-pane-container";
  2325.  
  2326. // Apply Suggestionsボタン
  2327. let applyButton = createButton("Apply Suggestions", "green", () => {
  2328. console.debug("Apply Suggestions clicked");
  2329.  
  2330. const editor = window.getLastFocusedEditor();
  2331. if (!editor) {
  2332. console.error("No editor is focused");
  2333. return;
  2334. }
  2335.  
  2336. const rightPane = document.querySelector(".naimod-pane.right-pane");
  2337. if (!rightPane) {
  2338. console.error("Right pane not found");
  2339. return;
  2340. }
  2341.  
  2342. console.debug("Getting enabled tags");
  2343. let enabledTags = Array.from(rightPane.querySelectorAll('button[data-enabled="true"]'))
  2344. .map(button => button.textContent.replace(/_/g, " "));
  2345. console.debug("Enabled tags:", enabledTags);
  2346.  
  2347. if (enabledTags.length > 0) {
  2348. setEditorContent(enabledTags.join(", ") + ", ", editor);
  2349. console.debug("Applied tags to editor");
  2350.  
  2351. // モーダルを閉じる
  2352. const modal = document.getElementById("naimod-modal");
  2353. if (modal) {
  2354. modal.style.display = "none";
  2355. console.debug("Closed modal");
  2356. }
  2357. } else {
  2358. console.debug("No enabled tags found");
  2359. }
  2360. });
  2361. applyButton.style.marginBottom = "10px";
  2362. container.appendChild(applyButton);
  2363.  
  2364. // 提案タグ表示域
  2365. const rightPane = document.createElement("div");
  2366. rightPane.className = "naimod-pane right-pane";
  2367. rightPane.style.minHeight = "200px";
  2368. rightPane.style.backgroundColor = "rgba(0, 0, 64, 0.8)";
  2369. rightPane.style.padding = "10px";
  2370. rightPane.style.borderRadius = "5px";
  2371. rightPane.style.marginTop = "10px";
  2372. rightPane.style.overflowY = "auto";
  2373. container.appendChild(rightPane);
  2374.  
  2375. return container;
  2376. };
  2377.  
  2378. // displaySuggestionsを修正して自然言語プロンプトを表示
  2379. const displaySuggestions = (result, pane) => {
  2380. console.debug("Displaying suggestions", result);
  2381.  
  2382. if (!result) {
  2383. pane.innerHTML = "";
  2384. return;
  2385. }
  2386.  
  2387. pane.innerHTML = "";
  2388.  
  2389. // Danbooru Tags セクション
  2390. const danbooruSection = document.createElement("div");
  2391. danbooruSection.className = "tag-section";
  2392.  
  2393. // Apply Suggestionsボタンを作成
  2394. const buttonContainer = document.createElement("div");
  2395. buttonContainer.className = "naimod-button-container";
  2396. const applyButton = createButton("Apply Suggestions", "green", () => {
  2397. console.debug("Apply Suggestions clicked");
  2398.  
  2399. const editor = window.getLastFocusedEditor();
  2400. if (!editor) {
  2401. console.error("No editor is focused");
  2402. return;
  2403. }
  2404.  
  2405. const rightPane = document.querySelector(".naimod-pane.right-pane");
  2406. if (!rightPane) {
  2407. console.error("Right pane not found");
  2408. return;
  2409. }
  2410.  
  2411. console.debug("Getting enabled tags");
  2412. let enabledTags = Array.from(rightPane.querySelectorAll('button[data-enabled="true"]'))
  2413. .map(button => button.textContent.replace(/_/g, " "));
  2414. console.debug("Enabled tags:", enabledTags);
  2415.  
  2416. if (enabledTags.length > 0) {
  2417. setEditorContent(enabledTags.join(", ") + ", ", editor);
  2418. console.debug("Applied tags to editor");
  2419.  
  2420. // モーダルを閉じる
  2421. const modal = document.getElementById("naimod-modal");
  2422. if (modal) {
  2423. modal.style.display = "none";
  2424. console.debug("Closed modal");
  2425. }
  2426. } else {
  2427. console.debug("No enabled tags found");
  2428. }
  2429. });
  2430. applyButton.className = "naimod-operation-button";
  2431. buttonContainer.appendChild(applyButton);
  2432. danbooruSection.appendChild(buttonContainer);
  2433.  
  2434. // 既存のタグを表示
  2435. const editor = window.getLastFocusedEditor();
  2436. if (editor) {
  2437. const currentTags = editor.textContent.split(/[,\n]+/).map(t => t.trim()).filter(Boolean);
  2438. const shouldRemoveSet = new Set(result.shouldRemove || []);
  2439.  
  2440. currentTags.forEach(tag => {
  2441. const tagButton = createButton(tag, shouldRemoveSet.has(tag) ? "red" : "#3498db", () => { });
  2442. tagButton.className = "naimod-tag-button";
  2443. tagButton.dataset.enabled = shouldRemoveSet.has(tag) ? "false" : "true";
  2444. tagButton.textContent = tag;
  2445. if (shouldRemoveSet.has(tag)) {
  2446. tagButton.title = "This tag is recommended to be removed";
  2447. }
  2448. danbooruSection.appendChild(tagButton);
  2449. });
  2450. }
  2451.  
  2452. pane.appendChild(danbooruSection);
  2453.  
  2454. // 追加すべきタグ
  2455. if (result.shouldAdd?.length) {
  2456. const addSection = document.createElement("div");
  2457. addSection.className = "tag-section";
  2458. addSection.innerHTML = "<h3 style='color: green;'>Suggested New Tags:</h3>";
  2459. result.shouldAdd.forEach(tag => {
  2460. const tagButton = createButton(tag, "green", () => { });
  2461. tagButton.className = "naimod-tag-button";
  2462. tagButton.dataset.enabled = "true";
  2463. tagButton.textContent = tag;
  2464. addSection.appendChild(tagButton);
  2465. });
  2466. pane.appendChild(addSection);
  2467. }
  2468.  
  2469. // 追加を提案するタグ
  2470. if (result.mayAdd?.length) {
  2471. const mayAddSection = document.createElement("div");
  2472. mayAddSection.className = "tag-section";
  2473. mayAddSection.innerHTML = "<h3 style='color: blue;'>Optional Tags:</h3>";
  2474. result.mayAdd.forEach(tag => {
  2475. const tagButton = createButton(tag, "blue", () => { });
  2476. tagButton.className = "naimod-tag-button";
  2477. tagButton.dataset.enabled = "false";
  2478. tagButton.textContent = tag;
  2479. mayAddSection.appendChild(tagButton);
  2480. });
  2481. pane.appendChild(mayAddSection);
  2482. }
  2483.  
  2484. // 各ボタンにトグル機能を追加
  2485. pane.querySelectorAll('.naimod-tag-button').forEach(button => {
  2486. button.onclick = () => {
  2487. button.dataset.enabled = button.dataset.enabled === "true" ? "false" : "true";
  2488. button.style.opacity = button.dataset.enabled === "true" ? "1" : "0.5";
  2489. console.debug(`Tag ${button.textContent} toggled:`, button.dataset.enabled);
  2490. };
  2491. // 初期状態を反映
  2492. button.style.opacity = button.dataset.enabled === "true" ? "1" : "0.5";
  2493. });
  2494.  
  2495. // 自然言語プロンプトの更新
  2496. const naturalLanguagePrompt = document.getElementById("naturalLanguagePrompt");
  2497. if (naturalLanguagePrompt && result.naturalLanguagePrompt) {
  2498. naturalLanguagePrompt.textContent = result.naturalLanguagePrompt;
  2499.  
  2500. // コピーボタンを動的に作成
  2501. const container = naturalLanguagePrompt.parentElement;
  2502. const buttonContainer = document.createElement("div");
  2503. buttonContainer.className = "naimod-button-container";
  2504. const copyButton = createButton("Copy", "blue", () => {
  2505. console.debug("Copy button clicked");
  2506.  
  2507. const naturalLanguagePrompt = document.getElementById("naturalLanguagePrompt");
  2508. if (!naturalLanguagePrompt) {
  2509. console.error("Natural language prompt element not found");
  2510. return;
  2511. }
  2512.  
  2513. const promptText = naturalLanguagePrompt.textContent;
  2514. if (!promptText) {
  2515. console.debug("No prompt text to copy");
  2516. return;
  2517. }
  2518.  
  2519. // クリップボードへコピー
  2520. navigator.clipboard.writeText(promptText)
  2521. .then(() => {
  2522. console.debug("Text copied to clipboard");
  2523. // 一時的なフィードバックとしてボタンのテキストを変更
  2524. copyButton.textContent = "Copied!";
  2525. setTimeout(() => {
  2526. copyButton.textContent = "Copy";
  2527. }, 2000);
  2528. })
  2529. .catch(err => {
  2530. console.error("Failed to copy text:", err);
  2531. alert("Failed to copy text to clipboard");
  2532. });
  2533. });
  2534. copyButton.className = "naimod-operation-button";
  2535. buttonContainer.appendChild(copyButton);
  2536.  
  2537. // タイトルの直後にボタンを挿入
  2538. const title = container.querySelector(".naimod-section-title");
  2539. title.insertAdjacentElement('afterend', buttonContainer);
  2540. }
  2541. };
  2542.  
  2543. // 自然言語プロンプトセクションの作成を修正
  2544. const createNaturalLanguageSection = () => {
  2545. const container = document.createElement("div");
  2546. container.className = "naimod-natural-language-container";
  2547.  
  2548. const title = document.createElement("h3");
  2549. title.textContent = "Natural Language Prompt";
  2550. title.className = "naimod-section-title";
  2551. container.appendChild(title);
  2552.  
  2553. const content = document.createElement("div");
  2554. content.id = "naturalLanguagePrompt";
  2555. content.className = "naimod-natural-language-content";
  2556. content.textContent = "";
  2557. container.appendChild(content);
  2558.  
  2559. return container;
  2560. };
  2561.  
  2562. // 閉じるボタンセクションの作成を修正
  2563. const createCloseButtonSection = (modal) => {
  2564. const container = document.createElement("div");
  2565. container.className = "naimod-close-button-container";
  2566. container.style.textAlign = "center";
  2567. container.style.marginTop = "20px";
  2568.  
  2569. let closeButton = createButton("Close", "grey", () => modal.style.display = "none");
  2570. closeButton.style.padding = "5px 20px";
  2571.  
  2572. container.appendChild(closeButton);
  2573. return container;
  2574. };
  2575.  
  2576. // アスペクト比の更新
  2577. const updateAspectRatio = () => {
  2578. console.debug("updateAspectRatio");
  2579. const widthInput = document.querySelector('input[type="number"][step="64"]');
  2580. let displayAspect = document.querySelector("#displayAspect");
  2581. if (!displayAspect) {
  2582. console.debug("createDisplayAspect");
  2583. displayAspect = createDisplayAspect();
  2584. }
  2585. if (widthInput) {
  2586. console.debug("appendChild displayAspect");
  2587. widthInput.parentNode.appendChild(displayAspect);
  2588. }
  2589. updateAspectInputs();
  2590. };
  2591.  
  2592. // Chantsボタンの追加
  2593. const addChantsButtons = async (chantsField) => {
  2594. try {
  2595. // chantURLが未定義の場合は取得
  2596. if (!chantURL) {
  2597. chantURL = getChantURL(null);
  2598. }
  2599.  
  2600. // Chantsデータのフェッチ
  2601. const response = await fetch(chantURL);
  2602. chants = await response.json();
  2603. // 各Chantに対応するボタンを作成
  2604. chants.forEach(chant => {
  2605. let button = createButton(
  2606. chant.name,
  2607. colors[chant.color][1],
  2608. () => handleChantClick(chant.name)
  2609. );
  2610. chantsField.appendChild(button);
  2611. });
  2612. } catch (error) {
  2613. console.error("Error fetching chants:", error);
  2614. // エラー時のフォールバック処理
  2615. let errorButton = createButton(
  2616. "Chants Load Error",
  2617. "red",
  2618. () => {
  2619. chantURL = getChantURL(true);
  2620. initializeApplication();
  2621. }
  2622. );
  2623. chantsField.appendChild(errorButton);
  2624. }
  2625. };
  2626.  
  2627. // Chantボタンのクリックハンドラー
  2628. const handleChantClick = (chantName) => {
  2629. const editor = window.getLastFocusedEditor();
  2630. if (!editor) {
  2631. console.error("No editor is focused");
  2632. return;
  2633. }
  2634.  
  2635. const chant = chants.find(x => x.name === chantName.trim());
  2636. if (chant) {
  2637. const tags = chant.content.split(",").map(x => x.trim());
  2638. appendTagsToPrompt(tags, editor);
  2639. }
  2640. };
  2641.  
  2642. // ウィンドウリサイズ時の処理を追加
  2643. window.addEventListener('resize', () => {
  2644. const popup = document.getElementById('naimod-popup');
  2645. if (popup) {
  2646. adjustPopupPosition(popup);
  2647. }
  2648. });
  2649.  
  2650. // キーボードショートカットハンドラー
  2651. document.addEventListener("keydown", e => {
  2652. const editor = window.getLastFocusedEditor();
  2653. if (!editor) return;
  2654.  
  2655. if (e.ctrlKey && e.code === "ArrowUp") {
  2656. e.preventDefault();
  2657. adjustTagEmphasis(1, editor);
  2658. }
  2659. if (e.ctrlKey && e.code === "ArrowDown") {
  2660. e.preventDefault();
  2661. adjustTagEmphasis(-1, editor);
  2662. }
  2663. });
  2664.  
  2665. // unfold/foldボタンを作成
  2666. const createFoldButton = (popup) => {
  2667. const foldButton = document.createElement("button");
  2668. foldButton.className = "naimod-toggle-button";
  2669. foldButton.innerHTML = "🟩"; // 初期状態はunfold
  2670.  
  2671. // unfold/fold処理
  2672. const toggleContent = (e) => {
  2673. e.preventDefault();
  2674. const content = popup.querySelector(".naimod-popup-content");
  2675. if (content.style.display === "none") {
  2676. content.style.display = "block";
  2677. foldButton.innerHTML = "🟩";
  2678. } else {
  2679. content.style.display = "none";
  2680. foldButton.innerHTML = "🟥";
  2681. }
  2682. savePopupState(popup);
  2683. };
  2684.  
  2685. // イベントリスナーの設定
  2686. foldButton.addEventListener('click', toggleContent);
  2687. foldButton.addEventListener('touchend', toggleContent, { passive: false });
  2688.  
  2689. return foldButton;
  2690. };
  2691.  
  2692. // detach/attachボタンを作成
  2693. const createDetachButton = () => {
  2694. const detachButton = document.createElement("button");
  2695. detachButton.className = "naimod-toggle-button";
  2696. detachButton.innerHTML = `<span class="naimod-toggle-button-anchor">⚓</span><span class="naimod-toggle-button-ship">🚢</span>`;
  2697.  
  2698. const toggleAttachment = (e) => {
  2699. e.preventDefault();
  2700. const isAttached = document.body.dataset.naimodAttached === "1";
  2701. document.body.dataset.naimodAttached = isAttached ? "0" : "1";
  2702.  
  2703. // ポップアップの状態を保存
  2704. const popup = document.getElementById('naimod-popup');
  2705. if (popup) {
  2706. savePopupState(popup);
  2707. }
  2708. };
  2709.  
  2710. detachButton.addEventListener('click', toggleAttachment);
  2711. detachButton.addEventListener('touchend', toggleAttachment, { passive: false });
  2712.  
  2713. return detachButton;
  2714. };
  2715.  
  2716. // リサイズハンドルの作成と設定を修正
  2717. const setupResizeHandles = (popup) => {
  2718. const leftHandle = document.createElement('div');
  2719. leftHandle.className = 'naimod-resize-handle left';
  2720.  
  2721. const rightHandle = document.createElement('div');
  2722. rightHandle.className = 'naimod-resize-handle right';
  2723.  
  2724. // ポップアップのposition: fixedを確保
  2725. if (getComputedStyle(popup).position !== 'fixed') {
  2726. popup.style.position = 'fixed';
  2727. }
  2728.  
  2729. popup.appendChild(leftHandle);
  2730. popup.appendChild(rightHandle);
  2731.  
  2732. // リサイズ処理
  2733. const startResize = (clientX, handle, isTouch = false) => {
  2734. const isLeft = handle.classList.contains('left');
  2735. const startX = clientX;
  2736. const startWidth = popup.offsetWidth;
  2737. const startLeft = popup.offsetLeft;
  2738.  
  2739. const resize = (moveEvent) => {
  2740. moveEvent.preventDefault();
  2741. const currentX = isTouch ? moveEvent.touches[0].clientX : moveEvent.clientX;
  2742. const delta = currentX - startX;
  2743. let newWidth;
  2744.  
  2745. if (isLeft) {
  2746. newWidth = startWidth - delta;
  2747. if (newWidth >= 200 && newWidth <= 800) {
  2748. popup.style.width = `${newWidth}px`;
  2749. popup.style.left = `${startLeft + delta}px`;
  2750. }
  2751. } else {
  2752. newWidth = startWidth + delta;
  2753. if (newWidth >= 200 && newWidth <= 800) {
  2754. popup.style.width = `${newWidth}px`;
  2755. }
  2756. }
  2757. };
  2758.  
  2759. const stopResize = () => {
  2760. if (isTouch) {
  2761. document.removeEventListener('touchmove', resize);
  2762. document.removeEventListener('touchend', stopResize);
  2763. } else {
  2764. document.removeEventListener('mousemove', resize);
  2765. document.removeEventListener('mouseup', stopResize);
  2766. }
  2767. // リサイズ終了時のみ状態を保存
  2768. savePopupState(popup);
  2769. };
  2770.  
  2771. if (isTouch) {
  2772. document.addEventListener('touchmove', resize, { passive: false });
  2773. document.addEventListener('touchend', stopResize);
  2774. } else {
  2775. document.addEventListener('mousemove', resize);
  2776. document.addEventListener('mouseup', stopResize);
  2777. }
  2778. };
  2779.  
  2780. // マウスイベントハンドラー
  2781. const mouseDownHandler = (e) => {
  2782. e.preventDefault();
  2783. startResize(e.clientX, e.target);
  2784. };
  2785.  
  2786. // タッチイベントハンドラー
  2787. const touchStartHandler = (e) => {
  2788. e.preventDefault();
  2789. const touch = e.touches[0];
  2790. startResize(touch.clientX, e.target, true);
  2791. };
  2792.  
  2793. // イベントリスナーの設定
  2794. [leftHandle, rightHandle].forEach(handle => {
  2795. handle.addEventListener('mousedown', mouseDownHandler);
  2796. handle.addEventListener('touchstart', touchStartHandler, { passive: false });
  2797. });
  2798. };
  2799.  
  2800. // 関連タグ検索関数
  2801. async function searchRelatedTags(targetTags) {
  2802. try {
  2803. // タグ内の半角スペースをアンダーバーに置換
  2804. const processedTags = targetTags.map(tag => tag.replace(/ /g, '_'));
  2805. const query = processedTags.join(" ");
  2806. const url = `https://danbooru.donmai.us/related_tag?commit=Search&search%5Border%5D=Cosine&search%5Bquery%5D=${encodeURIComponent(query)}`;
  2807. const response = await fetch(url);
  2808. const data = await response.json();
  2809. return data;
  2810. } catch (error) {
  2811. return {
  2812. "post_count": 0,
  2813. "related_tags": []
  2814. };
  2815. }
  2816. }
  2817.  
  2818. // コンテキストメニューの作成関数
  2819. const createContextMenu = () => {
  2820. // 既存のメニューがあれば作成しない
  2821. if (document.getElementById('naimod-contextmenu')) {
  2822. return;
  2823. }
  2824.  
  2825. // メニュー要素の作成
  2826. const menu = document.createElement('div');
  2827. menu.id = 'naimod-contextmenu';
  2828. menu.className = 'naimod-contextmenu';
  2829. menu.style.display = 'none';
  2830. menu.style.position = 'fixed';
  2831. menu.style.zIndex = '10000';
  2832.  
  2833. // 関連タグ検索用のメニュー項目
  2834. const relatedItem = document.createElement('div');
  2835. relatedItem.className = 'naimod-search-suggestion-menu';
  2836.  
  2837. // タグ候補表示用のコンテナ
  2838. const suggestionsContainer = document.createElement('div');
  2839. suggestionsContainer.className = 'naimod-contextmenu-suggestions';
  2840. suggestionsContainer.style.display = 'none';
  2841.  
  2842. // ProseMirrorエディタでの右クリックイベントの処理
  2843. document.addEventListener('contextmenu', (e) => {
  2844. const target = e.target.closest('.ProseMirror');
  2845. if (target) {
  2846. e.preventDefault();
  2847.  
  2848. let targetTags = [];
  2849. const selection = window.getSelection().toString().trim();
  2850.  
  2851. if (selection) {
  2852. // 選択テキストがある場合、それを処理
  2853. targetTags = selection
  2854. .split(/[,\n]/)
  2855. .map(tag => tag.trim())
  2856. .filter(Boolean)
  2857. .slice(0, 2);
  2858. } else {
  2859. // 選択テキストがない場合、カーソル位置のタグを取得
  2860. const position = getAbsoluteCursorPosition(target);
  2861. const targetTag = getCurrentTargetTag(target, position);
  2862. if (targetTag) {
  2863. targetTags = [targetTag];
  2864. }
  2865. }
  2866.  
  2867. if (targetTags.length > 0) {
  2868. // メニュー項目のテキストを更新
  2869. const displayText = targetTags.join(' + ');
  2870. relatedItem.textContent = `Search related tags for "${displayText}"`;
  2871.  
  2872. // クリックイベントを更新
  2873. relatedItem.onclick = async () => {
  2874. const result = await searchRelatedTags(targetTags);
  2875. menu.style.display = 'none';
  2876. showTagRelations(result.related_tags);
  2877. };
  2878.  
  2879. // メニューを表示
  2880. menu.style.display = 'block';
  2881.  
  2882. // タグ候補を取得して表示(最初のタグのみ)
  2883. suggestionsContainer.textContent = '';
  2884. suggestionsContainer.style.display = 'block';
  2885.  
  2886. if (targetTags[0]) {
  2887. const suggestions = getTagSuggestions(targetTags[0], 3); // 上位3つを取得
  2888.  
  2889. if (suggestions.length > 0) {
  2890. const suggestionTitle = document.createElement('div');
  2891. suggestionTitle.className = 'naimod-contextmenu-suggestion-title';
  2892. suggestionTitle.textContent = 'Tag Suggestions:';
  2893. suggestionsContainer.appendChild(suggestionTitle);
  2894.  
  2895. suggestions.forEach(tag => {
  2896. const suggestionItem = document.createElement('div');
  2897. suggestionItem.className = 'naimod-contextmenu-suggestion-item';
  2898. suggestionItem.textContent = tag.name;
  2899. suggestionItem.style.backgroundColor = colors[tag.category][1];
  2900. suggestionItem.style.cursor = 'pointer';
  2901. suggestionItem.style.padding = '4px 8px';
  2902. suggestionItem.style.margin = '2px 0';
  2903. suggestionItem.style.borderRadius = '4px';
  2904.  
  2905. suggestionItem.onclick = () => {
  2906. // クリック時に最新のエディタを取得
  2907. const currentEditor = window.getLastFocusedEditor();
  2908. if (currentEditor) {
  2909. appendTagsToPrompt([tag.name], currentEditor, {
  2910. removeIncompleteTag: targetTags[0]
  2911. });
  2912. } else {
  2913. console.error("No editor is focused");
  2914. }
  2915. menu.style.display = 'none';
  2916. };
  2917.  
  2918. suggestionsContainer.appendChild(suggestionItem);
  2919. });
  2920. }
  2921. }
  2922.  
  2923. // メニューが画面外にはみ出ないように位置を調整
  2924. const x = Math.min(e.clientX, window.innerWidth - menu.offsetWidth);
  2925. const y = Math.min(e.clientY, window.innerHeight - menu.offsetHeight);
  2926. menu.style.left = `${x}px`;
  2927. menu.style.top = `${y}px`;
  2928. }
  2929. }
  2930. });
  2931.  
  2932. // メニュー項目をメニューに追加
  2933. menu.appendChild(relatedItem);
  2934. menu.appendChild(suggestionsContainer);
  2935.  
  2936. // メニュー以外をクリックした時の処理
  2937. document.addEventListener('click', (e) => {
  2938. if (!menu.contains(e.target)) {
  2939. menu.style.display = 'none';
  2940. }
  2941. });
  2942.  
  2943. // メニューを非表示にする追加のイベント
  2944. document.addEventListener('scroll', () => {
  2945. menu.style.display = 'none';
  2946. });
  2947.  
  2948. document.addEventListener('keydown', (e) => {
  2949. if (e.key === 'Escape') {
  2950. menu.style.display = 'none';
  2951. }
  2952. });
  2953.  
  2954. // メニューをbodyに追加
  2955. document.body.appendChild(menu);
  2956. };
  2957.  
  2958. // 設定ボタンを作成する関数
  2959. const createSettingsButton = () => {
  2960. const settingsButton = document.createElement("button");
  2961. settingsButton.className = "naimod-toggle-button";
  2962. settingsButton.innerHTML = "🔧";
  2963. settingsButton.addEventListener("click", () => {
  2964. const modal = document.getElementById("naimod-modal");
  2965. if (modal) modal.style.display = "block";
  2966. });
  2967. return settingsButton;
  2968. };
  2969.  
  2970. // 関連タグを表示する関数
  2971. const showTagRelations = (relatedTags) => {
  2972. console.debug("Showing related tags:", relatedTags);
  2973.  
  2974. const relatedTagsField = document.getElementById("relatedTagsField");
  2975. if (!relatedTagsField) {
  2976. console.error("Related tags field not found");
  2977. return;
  2978. }
  2979.  
  2980. // フィールドをクリア
  2981. relatedTagsField.textContent = "";
  2982.  
  2983. // カテゴリごとにタグを分類
  2984. const tagsByCategory = {};
  2985. relatedTags.forEach(relatedTag => {
  2986. const tag = relatedTag.tag;
  2987. const category = tag.category;
  2988. if (!tagsByCategory[category]) {
  2989. tagsByCategory[category] = [];
  2990. }
  2991. tagsByCategory[category].push(tag);
  2992. });
  2993.  
  2994. // カテゴリごとにプルダウンセクションを作成
  2995. const categoryNames = {
  2996. "-1": "一般",
  2997. "0": "一般",
  2998. "1": "アーティスト",
  2999. "3": "コピーライト",
  3000. "4": "キャラクター",
  3001. "5": "スペック",
  3002. "6": "警告",
  3003. "7": "メタ",
  3004. "8": "ロール"
  3005. };
  3006.  
  3007. // カテゴリの順序を定義
  3008. const categoryOrder = ["0", "4", "3", "1", "5", "8", "7", "6", "-1"];
  3009. // 並べ替えたカテゴリを処理
  3010. categoryOrder.forEach(category => {
  3011. if (!tagsByCategory[category] || tagsByCategory[category].length === 0) {
  3012. return; // 空のカテゴリはスキップ
  3013. }
  3014. // カテゴリコンテナを作成
  3015. const categoryContainer = document.createElement("div");
  3016. categoryContainer.className = "naimod-category-container";
  3017. // カテゴリヘッダーを作成
  3018. const categoryHeader = document.createElement("div");
  3019. categoryHeader.className = "naimod-category-header";
  3020. categoryHeader.style.backgroundColor = colors[category][1];
  3021. categoryHeader.style.color = "white";
  3022. categoryHeader.style.padding = "5px";
  3023. categoryHeader.style.cursor = "pointer";
  3024. categoryHeader.style.marginBottom = "5px";
  3025. categoryHeader.style.borderRadius = "4px";
  3026. categoryHeader.style.display = "flex";
  3027. categoryHeader.style.justifyContent = "space-between";
  3028. categoryHeader.style.alignItems = "center";
  3029. // カテゴリ名とタグ数を表示
  3030. const categoryName = categoryNames[category] || `カテゴリ ${category}`;
  3031. categoryHeader.innerHTML = `
  3032. <span>${categoryName} (${tagsByCategory[category].length})</span>
  3033. <span class="naimod-dropdown-icon">▼</span>
  3034. `;
  3035. // タグコンテンツエリアを作成
  3036. const tagContent = document.createElement("div");
  3037. tagContent.className = "naimod-category-content";
  3038. tagContent.style.display = "none"; // 初期状態では折りたたまれている
  3039. // カテゴリ内のタグを追加
  3040. tagsByCategory[category].forEach(tag => {
  3041. const button = createButton(
  3042. `${tag.name.replace(/_/g, " ")} (${tag.post_count > 1000 ? `${(Math.round(tag.post_count / 100) / 10)}k` : tag.post_count})`,
  3043. colors[category][1],
  3044. () => {
  3045. // クリック時に最新のエディタを取得
  3046. const currentEditor = window.getLastFocusedEditor();
  3047. if (currentEditor) {
  3048. appendTagsToPrompt([tag.name.replace(/_/g, " ")], currentEditor);
  3049. } else {
  3050. console.error("No editor is focused");
  3051. }
  3052. }
  3053. );
  3054. button.title = `Category: ${category}`;
  3055. const tagDataFromAllTags = allTags.find(t => t.name === tag.name);
  3056. if (tagDataFromAllTags) {
  3057. button.title = `${tagDataFromAllTags.terms.filter(Boolean).join(", ")}`;
  3058. }
  3059. tagContent.appendChild(button);
  3060. });
  3061. // ヘッダークリックでコンテンツの表示/非表示を切り替え
  3062. categoryHeader.addEventListener("click", () => {
  3063. const isHidden = tagContent.style.display === "none";
  3064. tagContent.style.display = isHidden ? "block" : "none";
  3065. categoryHeader.querySelector(".naimod-dropdown-icon").textContent = isHidden ? "▲" : "▼";
  3066. });
  3067. // カテゴリセクションを構築
  3068. categoryContainer.appendChild(categoryHeader);
  3069. categoryContainer.appendChild(tagContent);
  3070. relatedTagsField.appendChild(categoryContainer);
  3071. });
  3072.  
  3073. // 関連タグの状態を保存
  3074. saveRelatedTags(relatedTags);
  3075.  
  3076. // Embeddingsの更新
  3077. clonePopupContentsToEmbeddings();
  3078. };
  3079.  
  3080. // 関連タグの状態を保存する関数
  3081. const saveRelatedTags = (relatedTags) => {
  3082. sessionStorage.setItem('naimodRelatedTags', JSON.stringify(relatedTags));
  3083. };
  3084.  
  3085. // 関連タグの状態を復元する関数
  3086. const restoreRelatedTags = () => {
  3087. const savedTags = sessionStorage.getItem('naimodRelatedTags');
  3088. if (savedTags) {
  3089. const relatedTags = JSON.parse(savedTags);
  3090. showTagRelations(relatedTags);
  3091. }
  3092. };
  3093.  
  3094.  
  3095. /**
  3096. * NOVEIAI用のユーザースクリプト - イベント制御
  3097. *
  3098. * このファイルは、global.js、main.jsの後に読み込まれます。
  3099. * 同じスコープで実行されるため、変数や関数は共有されます。
  3100. */
  3101.  
  3102.  
  3103.  
  3104. document.addEventListener("keydown", e => {
  3105. if (e.ctrlKey && e.code === "ArrowUp") {
  3106. e.preventDefault();
  3107. adjustTagEmphasis(1);
  3108. }
  3109. if (e.ctrlKey && e.code === "ArrowDown") {
  3110. e.preventDefault();
  3111. adjustTagEmphasis(-1);
  3112. }
  3113. // 左右の矢印キーが押された時、ProseMirrorにフォーカスがない場合に限り画像の遷移を実行
  3114. if ((e.code === "ArrowLeft" || e.code === "ArrowRight")) {
  3115. // 現在アクティブな要素がProseMirrorエディタ内にあるかチェック
  3116. const activeElement = document.activeElement;
  3117. const isEditorFocused = activeElement &&
  3118. (activeElement.classList.contains('ProseMirror') ||
  3119. activeElement.closest('.ProseMirror') !== null);
  3120. if (!isEditorFocused) {
  3121. const direction = e.code === "ArrowLeft" ? "left" : "right";
  3122. transitionImage(direction);
  3123. }
  3124. }
  3125. });
  3126.  
  3127. // 最後にフォーカスされたエディタとカーソル位置を記録
  3128. let lastFocusedEditor = null;
  3129. let lastCursorPosition = 0;
  3130.  
  3131. // カーソル位置を更新する関数
  3132. const updateCursorPosition = (editor) => {
  3133. if (editor) {
  3134. lastCursorPosition = getAbsoluteCursorPosition(editor);
  3135. }
  3136. };
  3137.  
  3138. const updateFocusedEditor = (editor) => {
  3139. document.querySelectorAll(".ProseMirror").forEach(x => x.style.border = "2px dashed rgba(255, 0, 0, 0.25)");
  3140. editor.style.border = "2px dashed rgba(0, 255, 0, 0.25)";
  3141. lastFocusedEditor = editor;
  3142. }
  3143.  
  3144. // ProseMirrorエディタの監視
  3145. const observeEditor = (editor) => {
  3146. if (editor) {
  3147. // inputとclickではupdateCursorPositionのタイミングが微妙に違う。
  3148. // inputはタイピングで100ms以下で連続実行されることが多く、全く同じにすると動作が重くなる為。
  3149.  
  3150. editor.addEventListener("input", e => {
  3151. updateFocusedEditor(editor);
  3152. const now = new Date();
  3153. lastTyped = now;
  3154. if (now - suggested_at > SUGGESTION_LIMIT) {
  3155. showTagSuggestions(editor, lastCursorPosition);
  3156. clonePopupContentsToEmbeddings();
  3157. suggested_at = now;
  3158. updateCursorPosition(editor);
  3159. } else {
  3160. setTimeout(() => {
  3161. if (lastTyped === now) {
  3162. showTagSuggestions(editor, lastCursorPosition);
  3163. clonePopupContentsToEmbeddings();
  3164. suggested_at = new Date();
  3165. updateCursorPosition(editor);
  3166. }
  3167. }, 1000);
  3168. }
  3169. });
  3170.  
  3171. editor.addEventListener("click", e => {
  3172. updateFocusedEditor(editor);
  3173. updateCursorPosition(editor);
  3174. const now = new Date();
  3175. if (now - suggested_at > SUGGESTION_LIMIT / 2) {
  3176. showTagSuggestions(editor, lastCursorPosition);
  3177. clonePopupContentsToEmbeddings();
  3178. suggested_at = now;
  3179. } else {
  3180. setTimeout(() => {
  3181. if (lastTyped === now) {
  3182. showTagSuggestions(editor, lastCursorPosition);
  3183. clonePopupContentsToEmbeddings();
  3184. suggested_at = new Date();
  3185. }
  3186. }, 1000);
  3187. }
  3188. });
  3189. }
  3190. };
  3191.  
  3192. // DOM変更の監視
  3193. const observeDOM = () => {
  3194. const observer = new MutationObserver((mutations) => {
  3195. mutations.forEach((mutation) => {
  3196. mutation.addedNodes.forEach((node) => {
  3197. if (node.nodeType === 1) { // ELEMENT_NODE
  3198. const editors = node.getElementsByClassName("ProseMirror");
  3199. Array.from(editors).forEach(editor => {
  3200. if (!editor.hasAttribute('data-naimod-observed')) {
  3201. observeEditor(editor);
  3202. editor.setAttribute('data-naimod-observed', 'true');
  3203. }
  3204. });
  3205. }
  3206. if(node.tagName == "SPAN" && node.checkVisibility() && node.textContent && !isNaN(Number(node.textContent))){
  3207. updateAspectRatio();
  3208. }
  3209. });
  3210. mutation.removedNodes.forEach((node) => {
  3211. //console.log("removedNodes", node, node.checkVisibility());
  3212. });
  3213. });
  3214. });
  3215.  
  3216. observer.observe(document.body, {
  3217. childList: true,
  3218. subtree: true
  3219. });
  3220. };
  3221.  
  3222. // タグデータの取得と処理を最適化
  3223. fetch("https://gist.githubusercontent.com/vkff5833/275ccf8fa51c2c4ba767e2fb9c653f9a/raw/danbooru.json?" + Date.now())
  3224. .then(response => response.json())
  3225. .then(data => {
  3226. allTags = data;
  3227. return fetch("https://gist.githubusercontent.com/vkff5833/275ccf8fa51c2c4ba767e2fb9c653f9a/raw/danbooru_wiki.slim.json?" + Date.now());
  3228. })
  3229. .then(response => response.json())
  3230. .then(wikiPages => {
  3231. // wikiPagesをマップに変換して検索を高速化
  3232. const wikiMap = new Map(wikiPages.map(page => [page.name, page]));
  3233. allTags = allTags.map(x => {
  3234. const wikiPage = wikiMap.get(x.name);
  3235. if (wikiPage) {
  3236. // Set操作を1回だけ実行
  3237. const allTerms = new Set(x.terms);
  3238. wikiPage.otherNames.forEach(name => allTerms.add(name));
  3239. x.terms = Array.from(allTerms);
  3240. }
  3241. return x;
  3242. });
  3243. buildTagIndices();
  3244. clonePopupContentsToEmbeddings();
  3245. });
  3246.  
  3247. // 初期化処理を最適化
  3248. let init = setInterval(() => {
  3249. const editors = document.getElementsByClassName("ProseMirror");
  3250. if (editors.length > 0) {
  3251. clearInterval(init);
  3252. chantURL = getChantURL(null);
  3253. // エディタの監視を一括で設定
  3254. const observedEditors = new Set();
  3255. Array.from(editors).forEach(editor => {
  3256. if (!observedEditors.has(editor)) {
  3257. observeEditor(editor);
  3258. editor.setAttribute('data-naimod-observed', 'true');
  3259. observedEditors.add(editor);
  3260. }
  3261. });
  3262. initializeApplication();
  3263. observeDOM();
  3264. }
  3265. }, 100);
  3266.  
  3267. // lastFocusedEditorをグローバルに公開
  3268. window.getLastFocusedEditor = () => lastFocusedEditor;
  3269.  
  3270. // lastCursorPositionをグローバルに公開
  3271. window.getLastCursorPosition = () => lastCursorPosition;
  3272.  
  3273. // 画像を遷移させる関数
  3274. function transitionImage(direction) {
  3275. // 現在の画像URLを取得
  3276. const currentImageURL = getCurrentImageURL();
  3277. if (currentImageURL) {
  3278. // まず現在の画像をクリック
  3279. const currentImg = document.querySelector(`img[src="${currentImageURL}"]`);
  3280. if (currentImg) {
  3281. // 現在の画像数を記録
  3282. const initialImageCount = document.querySelectorAll('img').length;
  3283. // 画像をクリック
  3284. currentImg.click();
  3285. // カウンター初期化
  3286. let checkCount = 0;
  3287. const MAX_CHECKS = 300; // 最大300回まで確認
  3288. // 画像数の変化を監視
  3289. const imageCheckInterval = setInterval(() => {
  3290. checkCount++;
  3291. const currentImageCount = document.querySelectorAll('img').length;
  3292. // 画像数が変化した、または最大チェック回数に達した場合
  3293. if ((currentImageCount > initialImageCount && currentImageCount >= 2) || checkCount >= MAX_CHECKS) {
  3294. // インターバルを停止
  3295. clearInterval(imageCheckInterval);
  3296. if (currentImageCount >= 2) {
  3297. const allImages = document.querySelectorAll('img');
  3298. // 現在表示中の画像のインデックスを探す
  3299. let currentIndex = -1;
  3300. for (let i = 0; i < allImages.length; i++) {
  3301. if (allImages[i].src === currentImageURL) {
  3302. currentIndex = i;
  3303. break;
  3304. }
  3305. }
  3306. if (currentIndex !== -1) {
  3307. let nextIndex;
  3308. // 方向に基づいて次の画像のインデックスを計算(ループ処理)
  3309. if (direction === "left") {
  3310. nextIndex = (currentIndex - 1 + allImages.length) % allImages.length;
  3311. } else { // right
  3312. nextIndex = (currentIndex + 1) % allImages.length;
  3313. }
  3314. // 次の画像をクリック
  3315. allImages[nextIndex].click();
  3316. console.debug(`画像遷移: ${direction}方向の画像に移動しました(${checkCount}回目のチェックで検出)`, allImages[nextIndex].src);
  3317. }
  3318. } else {
  3319. console.debug(`遷移可能な画像が見つかりませんでした(${checkCount}回のチェック後)`);
  3320. }
  3321. }
  3322. }, 0); // できるだけ短い間隔でチェック
  3323. }
  3324. } else {
  3325. console.debug("現在の画像URLが取得できませんでした");
  3326. }
  3327. }
  3328.  
  3329. // 現在表示されている画像のURLを取得
  3330. function getCurrentImageURL(){
  3331. if(Array.from(document.querySelectorAll('img')).filter(x => x.parentElement.getAttribute("class")).length == 1){
  3332. const src = Array.from(document.querySelectorAll('img')).filter(x => x.parentElement.getAttribute("class"))[0].getAttribute("src");
  3333. return src;
  3334. }
  3335. return null;
  3336. }
  3337.  
  3338.  
  3339.