File size: 53,762 Bytes
c8e4e29 bcccbd1 3bd9141 12c2d4f 27b2b89 3bd9141 12c2d4f 3bd9141 12c2d4f 3bd9141 12c2d4f 3bd9141 12c2d4f 3bd9141 12c2d4f 3bd9141 12c2d4f 27b2b89 3bd9141 27b2b89 3bd9141 12c2d4f 27b2b89 12c2d4f 27b2b89 3bd9141 12c2d4f 3bd9141 c8e4e29 bcccbd1 27b2b89 bcccbd1 27b2b89 bcccbd1 c8e4e29 3bd9141 c8e4e29 3bd9141 c8e4e29 b0e88e3 c8e4e29 45da44d c8e4e29 b0e88e3 45da44d b0e88e3 c8e4e29 12c2d4f 45da44d b0e88e3 45da44d 27b2b89 45da44d 12c2d4f b6bf7d9 12c2d4f c8e4e29 bcccbd1 4d1db98 bcccbd1 c8e4e29 bcccbd1 c8e4e29 27b2b89 c8e4e29 27b2b89 c8e4e29 27b2b89 c8e4e29 27b2b89 c8e4e29 45da44d f542108 c8e4e29 f542108 c8e4e29 b0e88e3 c8e4e29 45da44d c8e4e29 45da44d c8e4e29 45da44d b0e88e3 45da44d b0e88e3 45da44d c8e4e29 f542108 c8e4e29 f542108 c8e4e29 f542108 c8e4e29 f542108 c8e4e29 f542108 c8e4e29 f542108 c8e4e29 45da44d 27b2b89 45da44d 3bd9141 45da44d f542108 45da44d 3bd9141 45da44d 3bd9141 45da44d f542108 45da44d f542108 45da44d f542108 45da44d f542108 45da44d f542108 45da44d f542108 3bd9141 f542108 45da44d bcccbd1 c8e4e29 b0e88e3 3bd9141 bcccbd1 3bd9141 b0e88e3 27b2b89 b0e88e3 3bd9141 b0e88e3 bcccbd1 b0e88e3 45da44d 27b2b89 b0e88e3 27b2b89 b0e88e3 bcccbd1 27b2b89 b0e88e3 27b2b89 b0e88e3 27b2b89 b0e88e3 27b2b89 b0e88e3 27b2b89 45da44d c8e4e29 45da44d c8e4e29 45da44d c8e4e29 f542108 c8e4e29 45da44d c8e4e29 45da44d c8e4e29 45da44d c8e4e29 45da44d c8e4e29 3bd9141 c8e4e29 45da44d bcccbd1 3bd9141 b0e88e3 bcccbd1 3bd9141 b0e88e3 3bd9141 bcccbd1 b0e88e3 bcccbd1 b0e88e3 3bd9141 bcccbd1 3bd9141 9a2861e 3bd9141 9a2861e 3bd9141 bcccbd1 9a2861e bcccbd1 9a2861e bcccbd1 9a2861e bcccbd1 3bd9141 9a2861e 3bd9141 9a2861e 3bd9141 bcccbd1 b0e88e3 bcccbd1 9a2861e b0e88e3 3bd9141 b0e88e3 bcccbd1 12c2d4f c8e4e29 bcccbd1 45da44d 3bd9141 45da44d 27b2b89 c8e4e29 45da44d c8e4e29 3bd9141 c8e4e29 45da44d 27b2b89 bcccbd1 12c2d4f 27b2b89 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 |
let lastSaveTimestamp = 0;
let controller;
let lastTokenUpdateTimestamp = 0;
let summeries = {};
let lastIndexUpdateTimestamp = 0;
let replaceProofReadHistory = [];
// 画像アップロード関連の機能
let imageCounter = 0;
function addImageInput() {
const container = document.getElementById('imageInputsContainer');
const imageInputGroup = document.createElement('div');
imageInputGroup.className = 'input-group mb-2';
imageInputGroup.id = `imageGroup_${imageCounter}`;
const input = document.createElement('input');
input.type = 'file';
input.className = 'form-control';
input.accept = 'image/*';
input.id = `imageInput_${imageCounter}`;
const deleteButton = document.createElement('button');
deleteButton.className = 'btn btn-outline-danger';
deleteButton.innerHTML = '<i class="fas fa-trash"></i>';
deleteButton.onclick = function() {
removeImageInput(this.parentElement);
};
imageInputGroup.appendChild(input);
imageInputGroup.appendChild(deleteButton);
container.appendChild(imageInputGroup);
imageCounter++;
}
function removeImageInput(element) {
if (element) {
element.remove();
}
}
function getAttachedImages() {
const images = [];
const container = document.getElementById('imageInputsContainer');
const inputs = container.getElementsByTagName('input');
for (let input of inputs) {
if (input.files && input.files[0]) {
images.push(input.files[0]);
}
}
return images;
}
function replaceProofRead(textarea, proofReadText) {
let novelContent1TextLines = document.getElementById("novelContent1").value.split("\n");
let proofReadTextLines = proofReadText.split("\n");
let textareaTextLines = textarea.value.split("\n");
let start = novelContent1TextLines.indexOf(textareaTextLines[0]);
let end = novelContent1TextLines.indexOf(textareaTextLines[textareaTextLines.length - 1]);
console.log(start, end);
// 差し替え前のテキストを保存
let originalText = novelContent1TextLines.slice(start, end + 1);
replaceProofReadHistory.push([originalText, proofReadTextLines]);
// novelContent1TextLinesから該当部分を削除し、proofReadTextLinesを挿入
novelContent1TextLines.splice(start, end - start + 1, ...proofReadTextLines);
// 更新された内容をnovelContent1に反映
document.getElementById("novelContent1").value = novelContent1TextLines.join("\n");
// textareaの内容も更新
textarea.value = proofReadTextLines.join("\n");
console.log("校正が完了しました。");
}
async function getModelList() {
const url = 'https://generativelanguage.googleapis.com/v1beta/models?key=' + document.getElementById('geminiApiKey').value;
const response = await fetch(url);
const data = await response.json();
return data.models
.filter(x => x.supportedGenerationMethods.includes("generateContent"))
.filter(x => {
return x.name.match(/^models\/gemini/);
});
}
function getSafetySettings(endpoint) {
const threshold = endpoint.startsWith('models/model-exp-') ? 'OFF' : 'BLOCK_NONE';
return [
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": threshold
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": threshold
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": threshold
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": threshold
}
];
}
async function proofRead(textarea) {
let content = textarea.value;
const ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=${document.getElementById('geminiApiKey').value}`;
let prompt = `以下の文章を校正してください。文法がおかしい、誤字脱字、冗長な表現などを校正するのみに留め、内容は一切変更しないでください。\n\n${content}`;
const payload = {
method: 'POST',
headers: {},
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
"temperature": parseFloat(document.getElementById('temperature').value),
"max_output_tokens": 8192
},
safetySettings: getSafetySettings('models/gemini-2.0-flash-exp')
})
};
let proofReadText;
const response = await fetch(ENDPOINT, payload);
try {
const data = await response.json();
proofReadText = data.candidates[0].content.parts[0].text;
} catch (error) {
console.error('校正エラー:', error);
return '';
}
if (proofReadText) {
return replaceProofRead(textarea, proofReadText);
} else {
return '';
}
}
function formatText() {
const textOrg = document.getElementById('novelContent1').value;
let text = textOrg.replace(/[」。)]/g, '$&\n');
while (text.includes('\n\n')) {
text = text.replace(/\n\n/g, '\n');
}
text = text.replace(/「([^」\n]*)\n([^」\n]*)」/g, '「$1$2」');
text = text.replace(/(([^)\n]*)\n([^)\n]*))/g, '($1$2)');
while (text.search(/「[^「\n]*。\n/) >= 0) {
text = text.replace(/「([^「\n]*。)\n/, '「$1');
}
text = text.replace(/\n/g, "\n\n");
text = text.replace(/\n#/g, "\n\n#");
document.getElementById('novelContent1').value = text;
}
function unmalform(text) {
let result = null;
while (!result && text) {
try {
result = decodeURI(text);
} catch (error) {
text = text.slice(0, -1);
}
}
return result || '';
}
async function summerize(text) {
const ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=${document.getElementById('geminiApiKey').value}`;
const prompt = `以下の文章を240文字程度に要約してください:\n\n${text}`;
const payload = {
method: 'POST',
headers: {},
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
temperature: parseFloat(document.getElementById('temperature').value),
max_output_tokens: 512
},
safetySettings: getSafetySettings('models/gemini-2.0-flash-exp')
})
};
try {
const response = await fetch(ENDPOINT, payload);
const data = await response.json();
return data.candidates[0].content.parts[0].text;
} catch (error) {
console.error('要約エラー:', error);
return '';
}
}
function partialEncodeURI(text) {
if (!document.getElementById("partialEncodeToggle").checked) {
return text;
}
let length = parseInt(document.getElementById("encodeLength").value);
const chunks = [];
for (let i = 0; i < text.length; i += 1) {
chunks.push(text.slice(i, i + 1));
}
const encodedChunks = chunks.map((chunk, index) => {
if (index % length === 0) {
return encodeURI(chunk);
}
return chunk;
});
const result = encodedChunks.join('');
return result;
}
function saveToJson() {
const novelContent1 = document.getElementById('novelContent1').value;
const novelContent2 = document.getElementById('novelContent2').value;
const generatePrompt = document.getElementById('generatePrompt').value;
const nextPrompt = document.getElementById('nextPrompt').value;
const savedTitle = document.getElementById('savedTitle').value;
const jsonData = JSON.stringify({
novelContent1: novelContent1,
novelContent2: novelContent2,
generatePrompt: generatePrompt,
nextPrompt: nextPrompt,
savedTitle: savedTitle
});
const blob = new Blob([jsonData], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'novel_data.json';
if (savedTitle) {
a.download = savedTitle + '.json';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function loadFromJson() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.json,.txt';
fileInput.style.display = 'none';
document.body.appendChild(fileInput);
fileInput.addEventListener('change', function (event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
if (file.name.endsWith('.txt')) {
document.getElementById('novelContent1').value = e.target.result;
alert('テキストファイルを正常に読み込みました');
} else {
try {
const jsonData = JSON.parse(e.target.result);
if (jsonData.novelContent1) {
document.getElementById('novelContent1').value = jsonData.novelContent1;
}
if (jsonData.novelContent2) {
document.getElementById('novelContent2').value = jsonData.novelContent2;
}
if (jsonData.generatePrompt) {
document.getElementById('generatePrompt').value = jsonData.generatePrompt;
}
if (jsonData.nextPrompt) {
document.getElementById('nextPrompt').value = jsonData.nextPrompt;
}
if (jsonData.savedTitle) {
document.getElementById('savedTitle').value = jsonData.savedTitle;
}
generateIndexMenu(true);
alert('JSONファイルを正常に読み込みました');
} catch (error) {
alert('無効なJSONファイルです。');
}
}
};
reader.readAsText(file);
}
});
fileInput.click();
}
function saveToUserStorage(force = false) {
const currentTime = Date.now();
if (currentTime - lastSaveTimestamp < 5000 && !force) {
console.debug('セーブをスキップします');
return;
}
console.debug('セーブを実行します');
// 既存のデータを取得
const geminiClientData = JSON.parse(localStorage.getItem('geminiClient') || '{}');
const newData = {};
Array.from(document.querySelectorAll("input[id], textarea[id], select[id]")).forEach(el => {
if (el.id) {
newData[el.id] = el.type === 'checkbox' ? el.checked : el.value;
}
});
Object.assign(geminiClientData, newData);
console.log(geminiClientData);
localStorage.setItem('geminiClient', JSON.stringify(geminiClientData));
lastSaveTimestamp = currentTime;
}
function loadFromUserStorage() {
const savedData = localStorage.getItem('geminiClient');
if (savedData) {
const geminiClientData = JSON.parse(savedData);
Object.keys(geminiClientData).filter(key => key != "endpointSelect").forEach(key => {
const elem = document.getElementById(key);
if (elem) {
if (elem.type === 'checkbox') {
elem.checked = geminiClientData[key];
} else {
elem.value = geminiClientData[key];
}
// 特別な処理が必要な要素
if (key === 'encodeLength' || key === 'contentWidth') {
const inputElem = document.getElementById(`${key}Input`);
if (inputElem) {
inputElem.value = geminiClientData[key];
}
}
} else {
console.debug(`要素が見つかりません: ${key}`);
}
});
getModelList().then(models => {
const endpointSelect = document.getElementById('endpointSelect');
//endpointSelect.innerHTML = '';
models.forEach(model => {
const option = document.createElement('option');
option.value = model.name;
option.textContent = model.name;
endpointSelect.appendChild(option);
});
endpointSelect.value = geminiClientData.endpointSelect;
});
}
}
function createSummarizedText() {
const indexOffcanvasBody = document.querySelector('#indexOffcanvas .offcanvas-body');
const rootUl = indexOffcanvasBody.querySelector('ul.list-unstyled');
let summarizedText = '';
function processUl(ul, level = 0) {
const items = ul.children;
for (let item of items) {
const a = item.querySelector(':scope > a');
if (a) {
summarizedText += '#'.repeat(level + 1) + ' ' + a.textContent + '\n';
}
const contentItem = item.querySelector(':scope > ul > li');
if (contentItem) {
const fullText = contentItem.querySelector('.full-text');
const summaryText = contentItem.querySelector('.summery-text');
if (summaryText && summaryText.value.trim()) {
summarizedText += summaryText.value + '\n\n';
} else if (fullText) {
summarizedText += fullText.value + '\n\n';
}
}
const subUl = item.querySelector(':scope > ul');
if (subUl) {
processUl(subUl, level + 1);
}
}
}
if (rootUl) {
processUl(rootUl);
}
if (summarizedText) {
return summarizedText.trim();
} else {
return document.getElementById('novelContent1').value;
}
}
function createPayload() {
const novelContent1 = document.getElementById('novelContent1');
let text = novelContent1.value;
if (document.getElementById('summerizedPromptToggle').checked) {
text = createSummarizedText();
}
const lines = text.split('\n').filter(x => x);
let systemPrompt = `${partialEncodeURI(document.getElementById('generatePrompt').value)}`;
let prompt = `続きを書いて。${partialEncodeURI(document.getElementById('nextPrompt').value)} ${systemPrompt}`;
// 画像の取得と変換
const attachedImages = getAttachedImages();
const imagePromises = attachedImages.map(file => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
// Base64エンコードされた画像データを取得("data:image/jpeg;base64,"などのプレフィックスを除去)
const base64Data = reader.result.split(',')[1];
resolve({
inline_data: {
data: base64Data,
mime_type: file.type
}
});
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
});
// 画像の処理が完了してからペイロードを作成
return Promise.all(imagePromises).then(imageParts => {
let messages = [
{
"role": "user",
"parts": [{ "text": "." }]
},
{
"role": "model",
"parts": [{ "text": partialEncodeURI(lines.join("\n")) }]
},
{
"role": "user",
"parts": [
{ "text": prompt },
...imageParts
]
}
];
let max_output_tokens = 4096;
let selectedEndpoint = document.getElementById('endpointSelect').value;
if (selectedEndpoint.match(/^models\/gemini-2\.0/)) {
max_output_tokens = 8192;
}
if (selectedEndpoint.match(/^models\/gemini-2\.0-flash-thinking/)) {
max_output_tokens = 65536;
}
return {
method: 'POST',
headers: {},
body: JSON.stringify({
contents: messages,
generationConfig: {
"temperature": parseFloat(document.getElementById('temperature').value),
"max_output_tokens": max_output_tokens
},
safetySettings: getSafetySettings(selectedEndpoint)
}),
mode: 'cors'
};
});
}
function debugPrompt() {
console.log({
"gemini": JSON.parse(createPayload().body),
"openai": JSON.parse(createOpenAIPayload().body)
});
}
// 新しい関数を追加
function updateRequestButtonState(state, flashClass = null) {
const requestButton = document.getElementById('requestButton');
const stopButton = document.getElementById('stopButton');
switch (state) {
case 'generating':
requestButton.disabled = true;
stopButton.classList.remove('d-none');
break;
case 'idle':
requestButton.disabled = false;
stopButton.classList.add('d-none');
break;
case 'error':
requestButton.disabled = false;
stopButton.classList.add('d-none');
break;
}
if (flashClass) {
requestButton.classList.add(flashClass);
setTimeout(() => {
requestButton.classList.remove(flashClass);
}, 2000);
}
}
function fetchStream(ENDPOINT, payload) {
const novelContent2 = document.getElementById('novelContent2');
updateRequestButtonState('generating');
controller = new AbortController();
const signal = controller.signal;
fetch(ENDPOINT, { ...payload, signal })
.then(response => {
if (!response.ok) {
throw new Error('ネットワークの応答が正常ではありません');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
function readStream() {
reader.read().then(({ done, value }) => {
if (done) {
console.debug('ストリームが完了しました');
document.getElementById('stopButton').classList.add('d-none');
requestButton.disabled = false;
return;
}
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
console.debug('チャンクを受信しまし:', chunk);
// バッファから完全なJSONオブジェクトを抽出して処理
let startIndex = 0;
while (true) {
const endIndex = buffer.indexOf('\n', startIndex);
if (endIndex === -1) break;
const line = buffer.slice(startIndex, endIndex).trim();
startIndex = endIndex + 1;
if (line.startsWith('data: ')) {
const jsonString = line.slice(5);
if (jsonString === '[DONE]') {
console.debug('Received [DONE] signal');
break;
}
try {
const data = JSON.parse(jsonString);
console.debug('解析されたJSON:', data);
if (data.candidates && data.candidates[0].content && data.candidates[0].content.parts) {
data.candidates[0].content.parts.forEach(part => {
if (part.text) {
console.debug('出力にテキストを追加:', part.text);
novelContent2.value += part.text;
novelContent2.scrollTop = novelContent2.scrollHeight;
}
});
}
// finishReasonとblockReasonをチェック
if (data.candidates && data.candidates[0]) {
if (data.candidates[0].finishReason) {
if (data.candidates[0].finishReason === 'STOP') {
requestButton.classList.add('green-flash-bg');
setTimeout(() => {
requestButton.classList.remove('green-flash-bg');
}, 2000);
} else {
requestButton.classList.add('red-flash-bg');
setTimeout(() => {
requestButton.classList.remove('red-flash-bg');
}, 2000);
}
}
if (data.candidates[0].blockReason) {
requestButton.classList.add('red-flash-bg');
setTimeout(() => {
requestButton.classList.remove('red-flash-bg');
}, 2000);
}
}
} catch (error) {
console.error('JSONパースエラー:', error);
}
}
}
// 処理済みの部分をバッファから削除
buffer = buffer.slice(startIndex);
readStream();
}).catch(error => {
if (error.name === 'AbortError') {
console.log('フェッチがユーザーによって中止されました');
updateRequestButtonState('idle');
} else {
console.error('ストリーム読み取りエラー:', error);
updateRequestButtonState('error', 'red-flash-bg');
}
});
}
readStream();
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('フェッチがユーザーよって中止されました');
updateRequestButtonState('idle');
} else {
console.error('フェッチエラー:', error);
updateRequestButtonState('error', 'red-flash-bg');
}
});
}
async function fetchNonStream(ENDPOINT, payload) {
const novelContent2 = document.getElementById('novelContent2');
updateRequestButtonState('generating');
try {
const response = await fetch(ENDPOINT, payload);
const data = await response.json();
if (data && data.candidates && data.candidates[0].content && data.candidates[0].content.parts && data.candidates[0].content.parts[0].text) {
novelContent2.value += data.candidates[0].content.parts[0].text;
novelContent2.scrollTop = novelContent2.scrollHeight;
updateRequestButtonState('idle', 'green-flash-bg');
} else {
throw new Error('予期しないレスポンス形式');
}
} catch (error) {
console.error('エラー:', error);
updateRequestButtonState('error', 'red-flash-bg');
}
}
function createOpenAIPayload() {
const novelContent1 = document.getElementById('novelContent1');
const text = novelContent1.value;
const lines = text.split('\n').filter(x => x);
let lastPart = lines.pop() || '';
let messages = [
{
"content": document.getElementById('generatePrompt').value || ".",
"role": "system"
},
{
"content": ".",
"role": "user"
},
{
"content": partialEncodeURI(lines.join("\n")) || ".",
"role": "assistant"
},
{
"content": `続きを書いてください。${partialEncodeURI(document.getElementById('nextPrompt').value)}`,
"role": "user"
},
{
"content": lastPart,
"role": "assistant"
}
];
let jsonBody = JSON.parse(document.getElementById('openaiJsonBody').value);
jsonBody.messages = messages;
jsonBody.stream = document.getElementById('streamToggle').checked;
return {
method: 'POST',
headers: JSON.parse(document.getElementById('openaiHeaders').value),
body: JSON.stringify(jsonBody),
mode: 'cors',
credentials: 'same-origin'
};
}
function fetchOpenAIStream(ENDPOINT, payload) {
const novelContent2 = document.getElementById('novelContent2');
updateRequestButtonState('generating');
controller = new AbortController();
const signal = controller.signal;
payload.signal = signal;
fetch(ENDPOINT, payload)
.then(response => {
if (!response.ok) {
throw new Error('ネットワークの応答が常ではありません');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
function readStream() {
reader.read().then(({ done, value }) => {
if (done) {
console.debug('ストリームが完了しました');
document.getElementById('stopButton').classList.add('d-none');
requestButton.disabled = false;
return;
}
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop();
lines.forEach(line => {
if (line.startsWith('data: ')) {
const jsonString = line.slice(6);
if (jsonString === '[DONE]') {
console.debug('Received [DONE] signal');
return;
}
try {
const data = JSON.parse(jsonString);
if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
novelContent2.value += data.choices[0].delta.content;
novelContent2.scrollTop = novelContent2.scrollHeight;
}
} catch (error) {
console.error('JSONパースエラー:', error);
}
}
});
readStream();
}).catch(error => {
if (error.name === 'AbortError') {
console.log('フェッチがユーザーによって中止されました');
updateRequestButtonState('idle');
} else {
console.error('ストリーム読み取りエラー:', error);
updateRequestButtonState('error', 'red-flash-bg');
}
});
}
readStream();
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('フェッチがユーザーよって中止されました');
updateRequestButtonState('idle');
} else {
console.error('フェッチエラー:', error);
updateRequestButtonState('error', 'red-flash-bg');
}
});
}
async function fetchOpenAINonStream(ENDPOINT, payload) {
const novelContent2 = document.getElementById('novelContent2');
updateRequestButtonState('generating');
try {
const signal = controller.signal;
payload.signal = signal;
const response = await fetch(ENDPOINT, payload);
const data = await response.json();
if (data && data.choices && data.choices[0].message && data.choices[0].message.content) {
novelContent2.value += data.choices[0].message.content;
novelContent2.scrollTop = novelContent2.scrollHeight;
updateRequestButtonState('idle', 'green-flash-bg');
} else {
throw new Error('予期しないレスポンス形式');
}
} catch (error) {
console.error('エラー:', error);
updateRequestButtonState('error', 'red-flash-bg');
}
}
async function tokenCount() {
const selectedEndpoint = document.getElementById('endpointSelect').value;
let payload = createPayload();
payload.body = {
"contents": JSON.parse(payload.body).contents
};
payload.body = JSON.stringify(payload.body);
if (selectedEndpoint.startsWith('models/gemini')) {
const ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/${selectedEndpoint}:countTokens?key=` + document.getElementById('geminiApiKey').value;
try {
const response = await fetch(ENDPOINT, payload);
const data = await response.json();
return data.totalTokens;
} catch (error) {
console.error('エラー:', error);
return null;
}
} else {
return -1;
}
}
async function createDraft() {
const ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=` + document.getElementById('geminiApiKey').value;
let payload = createPayload();
const response = await fetch(ENDPOINT, payload);
const data = await response.json();
const text = data.candidates[0].content.parts[0].text;
return text
}
async function Request() {
generateIndexMenu(true);
let selectedEndpoint = document.getElementById('endpointSelect').value;
const requestButton = document.getElementById('requestButton');
requestButton.disabled = true;
document.getElementById('novelContent2').value = '';
const outputAccordion = document.querySelector('#content2Collapse');
if (outputAccordion) {
const bsCollapse = new bootstrap.Collapse(outputAccordion, { toggle: false });
bsCollapse.show();
}
let ENDPOINT;
let payload;
if (selectedEndpoint.startsWith('models/gemini')) {
ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/${selectedEndpoint}:generateContent?key=` + document.getElementById('geminiApiKey').value;
payload = await createPayload(); // 非同期処理を待機
} else if (selectedEndpoint === 'restart') {
ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=` + document.getElementById('geminiApiKey').value;
document.getElementById('novelContent2').value = '(下書き中)';
try {
draft = await createDraft();
} catch (error) {
console.error('エラー:', error);
requestButton.disabled = false;
requestButton.classList.add('green-flash-bg');
setTimeout(() => {
requestButton.classList.remove('green-flash-bg');
}, 2000);
return;
}
//document.getElementById('novelContent2').value = `# 下書き\n${draft}\n\n# リライト\n`;
document.getElementById('novelContent2').value = "";
const prompt = `以下の文章を、要件を満たす形に直したものを返信してください。\n返信内容は直した後のテキストのみになるようにし他の内容が混ざらないようにしてください。\n\n# 要件\n- 元の文章や会話の言い回しは不自然な日本語になっている部分もかなり多いので、根本的に書き替えること。ただし、登場人物の一人称や他者への呼称は変更しないこと。\n- 物語の大筋やキャラクターの性格は保ったまま、文章は全く別物に書き換える必要がある。元のテキストそのものはなるべく流用しないで新規に書くよう心掛ける。\n- 随所にレトリックを駆使しつつも凝り過ぎて読み辛くなることのないシンプルな美文になることを意識する。\n- 登場人物の会話を重視し、文脈を読み取り元のキャラクター設定に合った台詞回しを保ちつつ、より生き生きとした魅力的な物像に仕上がるようにする。\n- 細かい動作や心理描写のディテールを重視し、よりリアルな描写になるようにする。\n- 文章の終わりに「。」をつける、字下げをするなど、一般的な小説のフォーマットに従う書き方にする。\n\n# 文章\n${draft}`;
payload = {
method: 'POST',
headers: {},
body: JSON.stringify({
contents: [
{
"parts": [
{
"text": prompt
}
],
"role": "user"
}
],
generationConfig: {
"temperature": 1.0,
"max_output_tokens": 8192
},
safetySettings: getSafetySettings('models/gemini-2.0-flash-exp')
}),
mode: 'cors'
};
selectedEndpoint = 'models/gemini-2.0-flash-exp';
} else {
ENDPOINT = document.getElementById('openaiEndpoint').value;
payload = createOpenAIPayload();
}
let stream = document.getElementById('streamToggle').checked;
if (stream) {
if (selectedEndpoint.startsWith('models/gemini')) {
ENDPOINT = ENDPOINT.replace(':generateContent', ':streamGenerateContent') + '&alt=sse';
fetchStream(ENDPOINT, payload);
} else {
fetchOpenAIStream(ENDPOINT, payload);
}
document.getElementById('stopButton').classList.remove('d-none');
} else {
if (selectedEndpoint.startsWith('models/gemini')) {
fetchNonStream(ENDPOINT, payload);
} else {
fetchOpenAINonStream(ENDPOINT, payload);
}
}
}
function stopGeneration() {
if (controller) {
controller.abort();
controller = null;
}
updateRequestButtonState('idle');
}
// 新しい関数を追加
function handleKeyPress(event) {
if (event.ctrlKey && event.key === 'Enter') {
Request();
}
}
function syncInputs() {
const inputs = document.querySelectorAll('input[type="range"], input[type="number"]');
inputs.forEach(input => {
const baseId = input.id.replace('Input', '');
const pairedInput = document.getElementById(baseId + (input.type === 'range' ? 'Input' : ''));
if (pairedInput) {
input.addEventListener('input', function () {
pairedInput.value = this.value;
});
}
});
}
function openNextAccordion() {
const accordions = document.querySelectorAll('#mainAccordion .accordion-item');
let currentIndex = -1;
// 現在開いているアコーディオンのインデックスを見つける
for (let i = 0; i < accordions.length; i++) {
if (!accordions[i].querySelector('.accordion-button').classList.contains('collapsed')) {
currentIndex = i;
break;
}
}
// 次のアコーディオンを開く
if (currentIndex < accordions.length - 1) {
new bootstrap.Collapse(accordions[currentIndex].querySelector('.accordion-collapse')).hide();
new bootstrap.Collapse(accordions[currentIndex + 1].querySelector('.accordion-collapse')).show();
} else {
// もう次がない場合、ボタンを赤く点滅させる
const nextButton = document.getElementById('nextAccordion');
nextButton.classList.add('red-flash-bg');
setTimeout(() => {
nextButton.classList.remove('red-flash-bg');
}, 2000);
}
}
function openPreviousAccordion() {
const accordions = document.querySelectorAll('#mainAccordion .accordion-item');
let currentIndex = -1;
// 現在開いているアコーディオンのインデックスを見つける
for (let i = 0; i < accordions.length; i++) {
if (!accordions[i].querySelector('.accordion-button').classList.contains('collapsed')) {
currentIndex = i;
break;
}
}
// 前のアコーディオンを開く
if (currentIndex > 0) {
new bootstrap.Collapse(accordions[currentIndex].querySelector('.accordion-collapse')).hide();
new bootstrap.Collapse(accordions[currentIndex - 1].querySelector('.accordion-collapse')).show();
} else {
// もう前がない場合、ボタンを赤く点滅させる
const prevButton = document.getElementById('prevAccordion');
prevButton.classList.add('red-flash-bg');
setTimeout(() => {
prevButton.classList.remove('red-flash-bg');
}, 2000);
}
}
function moveToInput() {
const content1 = document.getElementById('novelContent1');
const content2 = document.getElementById('novelContent2');
let content1Lines = content1.value.trim().split('\n');
let content2Lines = content2.value.trim().split('\n');
// content1の最後の行とcontent2の先頭行が完全に一致する場合、content2から削除
if (content1Lines[content1Lines.length - 1] === content2Lines[0]) {
content2Lines.shift();
} else {
// 分的な重複を検出して削除
const lastLine = content1Lines[content1Lines.length - 1];
const firstLine = content2Lines[0];
const overlapIndex = firstLine.indexOf(lastLine);
if (overlapIndex !== -1) {
content2Lines[0] = firstLine.slice(overlapIndex + lastLine.length).trim();
if (content2Lines[0] === '') {
content2Lines.shift();
}
}
}
// content2の内容をcontent1の末尾に追加
content1.value = content1Lines.join('\n') + '\n' + content2Lines.join('\n');
// content2を空にする
content2.value = '';
// content1Collapseを開く
const content1Collapse = new bootstrap.Collapse(document.getElementById('content1Collapse'), {
show: true
});
}
function updateNavbarBrand() {
const endpointSelect = document.getElementById('endpointSelect');
const navbarBrand = document.querySelector('.navbar-brand');
const googleIcon = navbarBrand.querySelector('.fa-google');
const robotIcon = navbarBrand.querySelector('.fa-robot');
if (endpointSelect.value.startsWith('models/gemini')) {
navbarBrand.style.color = '#4285F4'; // Googleブルー
googleIcon.classList.remove('d-none');
robotIcon.classList.add('d-none');
} else {
navbarBrand.style.color = '#00FF00'; // 明るい緑色
googleIcon.classList.add('d-none');
robotIcon.classList.remove('d-none');
}
}
async function updateTokenCount(force = false) {
const currentTime = Date.now();
if (currentTime - lastTokenUpdateTimestamp < 60000 && !force) {
console.debug('トークン数更新をスキップします');
return;
}
console.debug('トークン数更新を実行します');
const count = await tokenCount();
const indexOffcanvasLabel = document.getElementById('indexOffcanvasLabel');
indexOffcanvasLabel.textContent = `目次 (${count}トークン)`;
lastTokenUpdateTimestamp = currentTime;
}
function generateIndexMenu(force = false) {
const currentTime = Date.now();
if (currentTime - lastIndexUpdateTimestamp < 60000 && !force) {
console.debug('目次更新をスキップします');
return;
}
console.debug('目次更新を実行します');
const content = document.getElementById('novelContent1').value;
const tokens = marked.lexer(content);
const indexOffcanvasBody = document.querySelector('#indexOffcanvas .offcanvas-body');
indexOffcanvasBody.innerHTML = '';
const rootUl = document.createElement('ul');
rootUl.className = 'list-unstyled';
let stack = [{ ul: rootUl, level: 0 }];
let lastHeading = null;
let contentBuffer = '';
tokens.forEach((token, index) => {
if (token.type === 'heading') {
if (lastHeading && contentBuffer.trim()) {
addTextarea(lastHeading.querySelector('ul'), contentBuffer.trim());
}
contentBuffer = '';
while (stack.length > 1 && stack[stack.length - 1].level >= token.depth) {
stack.pop();
}
const li = document.createElement('li');
const toggleBtn = document.createElement('button');
toggleBtn.className = 'btn btn-sm btn-outline-secondary me-2 toggle-btn';
const icon = document.createElement('i');
icon.className = 'fas fa-plus'; // Font Awesomeのプラスアイコン
toggleBtn.appendChild(icon);
toggleBtn.onclick = () => toggleSubMenu(li);
const a = document.createElement('a');
a.href = '#';
a.textContent = token.text;
a.onclick = (e) => {
e.preventDefault();
scrollToHeading(token.text);
};
li.appendChild(toggleBtn);
li.appendChild(a);
const subUl = document.createElement('ul');
subUl.className = 'list-unstyled ms-3 d-none';
li.appendChild(subUl);
stack[stack.length - 1].ul.appendChild(li);
if (token.depth > stack[stack.length - 1].level) {
stack.push({ ul: subUl, level: token.depth });
}
lastHeading = li;
} else if (token.type === 'text' || token.type === 'paragraph') {
contentBuffer += token.text + '\n';
}
});
if (lastHeading && contentBuffer.trim()) {
addTextarea(lastHeading.querySelector('ul'), contentBuffer.trim());
}
if (rootUl.children.length > 0) {
indexOffcanvasBody.appendChild(rootUl);
} else {
indexOffcanvasBody.textContent = '目次がありません';
}
updateTokenCount(force);
lastIndexUpdateTimestamp = currentTime;
}
function toggleSubMenu(li) {
const subUl = li.querySelector('ul');
const toggleBtn = li.querySelector('.toggle-btn');
const icon = toggleBtn.querySelector('i');
subUl.classList.toggle('d-none');
icon.className = subUl.classList.contains('d-none') ? 'fas fa-plus' : 'fas fa-minus';
}
function addTextarea(ul, content) {
const li = document.createElement('li');
// テキストエリアの作成
const textarea = document.createElement('textarea');
textarea.readOnly = true;
textarea.className = 'form-control mt-2 full-text';
textarea.value = content;
textarea.rows = 3;
// 要約用のテキストエリアの作成
const summaryInput = document.createElement('textarea');
summaryInput.className = 'form-control mt-2 summery-text';
summaryInput.placeholder = '要約';
summaryInput.rows = 3;
if (summeries[content]) {
summaryInput.value = summeries[content];
}
// ボタン用のコンテナ作成
const buttonContainer = document.createElement('div');
buttonContainer.className = 'mt-2';
// 要約取得ボタンの作成
const summaryButton = document.createElement('button');
summaryButton.textContent = '要約を取得';
summaryButton.className = 'btn btn-secondary me-2';
summaryButton.onclick = async () => {
summaryButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...';
summaryButton.disabled = true;
try {
const summary = await summerize(content);
summaryInput.value = summary;
summeries[content] = summary;
updateTokenCount(true);
} finally {
summaryButton.innerHTML = '要約を取得';
summaryButton.disabled = false;
}
};
// 要約削除ボタンの作成
const deleteSummaryButton = document.createElement('button');
deleteSummaryButton.textContent = '要約を削除';
deleteSummaryButton.className = 'btn btn-danger';
deleteSummaryButton.onclick = () => {
summaryInput.value = '';
delete summeries[content];
updateTokenCount(true);
};
// 校正ボタンの作成
const proofReadButton = document.createElement('button');
proofReadButton.textContent = '校正';
proofReadButton.className = 'btn btn-secondary me-2';
proofReadButton.onclick = async () => {
proofReadButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 校正中...';
proofReadButton.disabled = true;
try {
await proofRead(textarea);
} finally {
proofReadButton.innerHTML = '校正';
proofReadButton.disabled = false;
}
};
const hr = document.createElement('hr');
// ボタンをコンテナに追加
buttonContainer.appendChild(summaryButton);
buttonContainer.appendChild(deleteSummaryButton);
buttonContainer.appendChild(hr);
buttonContainer.appendChild(proofReadButton);
// 要素の追加
li.appendChild(textarea);
li.appendChild(summaryInput);
li.appendChild(buttonContainer);
ul.appendChild(li);
}
function scrollToHeading(headingText) {
const content1 = document.getElementById('novelContent1');
const content1Collapse = document.getElementById('content1Collapse');
const accordion = new bootstrap.Collapse(content1Collapse, { toggle: false });
// テキストエリアの内容を行ごとに分割
const lines = content1.value.split('\n');
// 見出しテキストを含む行のインデックスを探す
const headingIndex = lines.findIndex(line => line.includes(headingText));
if (headingIndex !== -1) {
// 一時的な要素を作成してテキストエリアの内容をコピー
const tempDiv = document.createElement('div');
tempDiv.style.cssText = `
position: absolute;
top: -9999px;
left: -9999px;
width: ${content1.clientWidth}px;
font-size: ${window.getComputedStyle(content1).fontSize};
font-family: ${window.getComputedStyle(content1).fontFamily};
line-height: ${window.getComputedStyle(content1).lineHeight};
white-space: pre-wrap;
word-wrap: break-word;
visibility: hidden;
`;
document.body.appendChild(tempDiv);
// 見出しまでの内容を一時的な要素に挿入
tempDiv.textContent = lines.slice(0, headingIndex).join('\n');
// 見出しまでの高さを計算
const scrollPosition = tempDiv.clientHeight;
// 一時的な要素を削除
document.body.removeChild(tempDiv);
// アコーディオンが既に開かれているかチェック
if (content1Collapse.classList.contains('show')) {
// 既に開かれている場合は直接スクロール
content1.scrollTop = scrollPosition;
} else {
// 閉じている場合はアコーディオンを開いてからスクロール
accordion.show();
content1Collapse.addEventListener('shown.bs.collapse', function onShown() {
content1.scrollTop = scrollPosition;
content1Collapse.removeEventListener('shown.bs.collapse', onShown);
}, { once: true });
}
}
}
function updateAccordionHeaderCount(accordionId) {
const accordionItem = document.getElementById(accordionId).closest('.accordion-item');
if (!accordionItem) return;
const textarea = accordionItem.querySelector('.accordion-body textarea');
const header = accordionItem.querySelector('.accordion-header button');
if (textarea && header) {
const charCount = textarea.value.length;
const originalText = header.textContent.split('(')[0].trim();
header.textContent = `${originalText} (${charCount}文字)`;
}
}
function updateAllAccordionHeaderCounts() {
const accordionIds = ['promptsCollapse', 'content1Collapse', 'nextPromptCollapse', 'content2Collapse'];
accordionIds.forEach(updateAccordionHeaderCount);
}
function showDiffModal() {
const diffContainer = document.getElementById('diffContainer');
diffContainer.innerHTML = '';
if (replaceProofReadHistory.length === 0) {
diffContainer.innerHTML = '<p>校正履歴がありません。</p>';
return;
}
replaceProofReadHistory.forEach((entry, index) => {
const [original, corrected] = entry;
const diff = Diff.diffLines(original.join('\n'), corrected.join('\n'));
const diffHtml = diff.map(part => {
const color = part.added ? 'green' : part.removed ? 'red' : 'grey';
const prefix = part.added ? '+' : part.removed ? '-' : ' ';
return `<span style="color: ${color}">${prefix} ${part.value}</span>`;
}).join('');
const entryDiv = document.createElement('div');
entryDiv.innerHTML = `<h6>校正 ${index + 1}</h6><pre>${diffHtml}</pre><hr>`;
diffContainer.appendChild(entryDiv);
});
const modal = new bootstrap.Modal(document.getElementById('diffModal'));
modal.show();
}
document.addEventListener('DOMContentLoaded', function () {
// ページ読み込み時にデータを復元
loadFromUserStorage();
// メイン画面の要素のイベントリスナー。inputイベントが発生する頻度が非常に高いのでこちらの発動は60秒に1回に制限する
['novelContent1', 'novelContent2', 'generatePrompt', 'nextPrompt', 'savedTitle'].forEach(id => {
document.getElementById(id).addEventListener('input', () => {
saveToUserStorage(false);
generateIndexMenu(false);
updateAllAccordionHeaderCounts();
});
});
// 設定画面の要素のイベントリスナー
['memo', 'geminiApiKey', 'endpointSelect', 'openaiEndpoint', 'openaiHeaders', 'openaiJsonBody', 'encodeLength', 'temperature'].forEach(id => {
document.getElementById(id).addEventListener('input', () => {
saveToUserStorage(true);
});
});
['partialEncodeToggle', 'streamToggle'].forEach(id => {
document.getElementById(id).addEventListener('change', () => {
saveToUserStorage(true);
});
});
document.getElementById('novelContent1').addEventListener('keydown', handleKeyPress);
document.querySelectorAll('[data-modal-text]').forEach(element => {
element.addEventListener('click', function () {
document.querySelectorAll(".modal-text").forEach(el => {
el.classList.add("d-none");
if (el.classList.contains(this.getAttribute('data-modal-text'))) {
el.classList.remove("d-none");
}
});
});
});
syncInputs();
// 60秒ごとに自動保存実行
setInterval(() => {
saveToUserStorage();
generateIndexMenu(true);
updateAllAccordionHeaderCounts();
}, 60000);
// 基本設定のアコーディオンを開く
const basicSettingsAccordion = document.querySelector('#promptsCollapse');
if (basicSettingsAccordion) {
new bootstrap.Collapse(basicSettingsAccordion).show();
}
// ナビゲーションボタンのイベントリスナーを設定
document.getElementById('prevAccordion').addEventListener('click', openPreviousAccordion);
document.getElementById('nextAccordion').addEventListener('click', openNextAccordion);
// エンドポイント選択が変更されたときにnavbar-brandを更新
document.getElementById('endpointSelect').addEventListener('change', updateNavbarBrand);
// 初期表示時にも実行
updateNavbarBrand();
//generateIndexMenu(true);
updateAllAccordionHeaderCounts();
// diff2htmlライブラリの読み込み
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jsdiff/5.1.0/diff.min.js';
document.head.appendChild(script);
});
|