BIC EDIT

Latest version: 1.7

Do not copy the whole page. Read the guide.

Features

  • Regenerate an image with an additional style prompt as a landscape or portrait
  • Prompt character limit can be increased from 480 to 850
  • Prompt without consuming boosts/credits

QOL

  • Multi-line prompt input for easier typing
  • Prompt length is shown as you type
  • Poll non-boosted generations status so you don't have to manually refresh the page

Changelog

1.1
  • Added alerts for a couple of known error codes when an edit request is unsuccessful
  • Script will no longer refresh the page every 7 seconds by default. Now, it will check if generation was successful or not and either display the image or let you know that generation was blocked. If said check fails for some reason, it will go back to the old behavior of refreshing the page every 7 seconds

1.2

  • Removed a couple generation id checks which caused the script to stop working

1.3

  • NEW: Code mess has been mostly refactored
  • NEW: (Experimental) Prompt 480 character limit has been increased to 850. Must be manually turned on
  • NEW: (Experimental) Enabling the large prompts feature also changes the prompt input to a multi-line textarea to make it easier to type large prompts
  • NEW: Random style button has been added, making it easier to create variations of the same image
  • FIX: copilot(.)microsoft(.)com/images/create single result image thumbnail fixed
  • FIX: Fixed an issue where some regenerations were mistakenly labeled as blocked
  • MISC: Colors were changed a bit to match BIC dark colors
  • MISC: Changed the way the script checks whether a generation was edited or not
  • MISC: Message at the bottom of editing feature has been removed since there is now a FAQ section
  • MISC: Added option to remember your last submitted prompt

1.4

  • FIX: Fixed non-boost generations when using the large prompts feature

1.5

  • FIX: Tabs opened by the edit feature stuck at "Page not found" when website language is not English

1.6

  • NEW: Added an option to prompt without consuming boosts/credits (Read more)
  • NEW: Added an option to hide insights (Related content from the web) panel shown below image viewer (enabled by default)
  • FIX: Unable to regenerate the first image after swiping to the next image

1.7

  • NEW: Added an option to force BIC to poll low-priority/non-boosted generations (Enabled by default)
  • NEW: Ability to edit already edited generations
  • FIX: Duplication bug with HTML elements from the edit feature when an anchor tag is added to the URL
  • MISC: Config clean-up, savingCredits now defaults to false and a couple of config names has been changed. New Config section added to the rentry.
  • (update 05/12) FIX: Edit feature doesn't loads after reopening image viewer

Known issues

  • If you are using the multi-line input, adding line breaks (\n) to your prompt might break BIC and your generation might suddenly disappear
  • If you are using the multi-line input, enter key doesn't submits the prompt on some cases and you have to manually click the Create button
  • Currently doesn't works on the phone version of the site.

Regarding the edit feature

  • Filter is believed to be stricter for edits
  • Each edit request counts towards your account daily limit regardless of whether it was successfully generated or blocked
  • Just as it happens with Copilot, fidelity towards the original generation can be hit-or-miss. Sometimes it will generate an entirely different thing

FAQ

How does the prompt character limit increase works?

It adds a few query params to the creation request which makes BIC believe it is creating for Copilot.

Once a request is sent, BIC will think it is generating for copilot so you might see briefly the white copilot layout. The script will immediately redirect back to the default layout except when there is an error message (You can't submit more prompts, unsafe prompt, etc).

How well do long (500+ characters) prompts work?

Not as good as it sounds. Words towards the end of a long prompt have little to no impact on the result. Might be useful to add some noise to the prompt in case you are doing risqué stuff and getting dogged a lot.

How do I enable longer prompts?

Open the script source code and change enableLongPrompts to true

enableLongPrompts: true,

Save the changes and reload the page. You will notice some changes in the page like the multi-line prompt input, the removal of some stuff to make up for the extra space used by the new input and the prompt length being displayed inside the Create button..

Why is the edit feature not appearing when I open an image?

Some possible reasons from most-likely to least-likely:

  • Script was unable to check whether the image was already edited or not. Try refreshing the page
  • MS did a change to the frontend which broke the script

What is copilot.microsoft.com/images/create?

Alternative frontend that doesn't has IP rate limits (the panda) yet.

My edits are getting dogged. What can I do?

If you your prompt is 'safe' (doesn't includes a depiction of a woman):

  • Click the random button and try again. This is enough to change the seed and attempt to generate a different variation of the same picture

If your prompt is unsafe:

  • Specifying a positive mood helps a lot. Try adding words like: smiling, happily, joyful, celebration and so on
  • Add visual noise

How does the style prompt works?

There is no information publicly available about this so this is my assumption. Every time an image is going to be regenerated, it is sent to GPT first to "deconstruct" it based on the image itself and the original prompt in order to write a new prompt with the addition of the style prompt you provided. Original prompt has much more weight over the generation than the style prompt so you cannot use the style to override stuff in the original prompt though you can use the style to further complement or fix/improve the result. E.G:
Original prompt:

35mm photograph of frog still on a waterlily in the middle of a lake

If you were to use the following style:

animated 3d cgi

Since the original prompt already specifies that the picture must be in the style of a 35mm photograph, there is a conflict between the two prompts. Either it will completely ignore the specified style or it will attempt to combine both prompts which might lead to unexpected results.

If you were to use the following style instead:

Frog is iridescent with golden eyes and has a huge mustache

This will work as it doesn't conflict with the original prompt. Writing stuff like "beautiful delicate hands" or "detailed face of pure joy" can be used (with a bit of luck) to fix bad-anatomy.

What does the random style button do?

It writes a random GUID to the style field. It doesn't makes any sense but this is enough to change the internal seed and force BIC to generate a different variation of the same picture.

About saving credits

Microsoft is currently A/B testing an update in some countries where boosts had been removed and replaced with credits. Credits are now required in order to generate images. Each free copilot account is given 15 credits and once the user has used all of them, they won't be able prompt anymore until the credits replenishes the next day.

1.6 adds the option saveCredits which is enabled by default as the update is expected to be pushed to everyone soon. When enabled, the script will force BIC to generate images in low-priority mode (same thing as when you run out of boost) and won't consume any credits. This works with both the long prompt feature enabled and the default input. When enabled, the number of boosts/credits you have will appear in bold green. Note that if you are in a country where this update is live, your account must have at least 1 credit for this to work.

If you are still seeing boosts instead of credits, you might want to disable this by opening the script source code and editing this at line 24
This can be enabled at the config section by setting the value of saveCredits to true

saveCredits: true,

Config

You can adjust the configuration by opening the script source code in your userscript manager. After you edit the config, make sure to save the changes and reload all tabs where you are using Bing Image Creator.

Name Description
enableLongPrompts Valid values: true and false. Setting the value to true will allow you to send longer prompts up to 850 characters (Read more).
enableStyleSuggestions Valid values: true and false. Setting the value to true will make use of the built-in autocomplete function of your browser to suggest style prompts.
forcePollingLowPriorityGens Valid values: true and false. Setting the value to true will force BIC to actively check the status of a non-boosted generation so you don't have to manually refresh the page.
hideInsightsPanel Valid values: true and false. Setting the value to true will hide the insights panel (Related content from the web) from the image viewer.
rememberLastSubmittedPrompt Valid values: true and false. Setting the value to true will automatically write your last submitted prompt to the prompt field when you are on the homepage. Requires enableLongPrompts to be enabled as it is intended to be useful when you get hard blocked with the Copilot layout (and the prompt input doesn't appears) so you don't lose your prompt. Note that prompts are saved only when you click the create button.
saveCredits Valid values: true and false. Setting the value to true will force every generation to be generated in low-priority mode so boosts/credits aren't used (Read more).
styleSuggestions Valid value: string array. This is the list of suggestions to be used by the browser autocomplete when using the style input in the edit feature. Requires enableStyleSuggestions to be enabled.

How to install

Scroll down until you find the code section and copy everything you see inside the box. If you are on desktop, you can hover the mouse over the code to make a small icon appear on the top right, click it and the code will be automatically copied to your clipboard.

If you already have a previous version installed, make sure to backup your styles suggestions if you are using that feature and then simply delete everything and paste the new code.

If you don't have a previous version installed, install an userscript addon. Script was tested and works on Firefox + FireMonkey and Brave/Edge + TamperMonkey. Open your userscript menu and create a new script. Since it will most likely open a template, make sure to delete everything before pasting the code.

After that simply save the script and refresh the page.

Code

  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
// ==UserScript==
// @name             BIC EDIT
// @version          1.7
// @match            https://copilot.microsoft.com/images/create*
// @match            https://www.bing.com/images/create*
// @grant            GM.setValue
// @grant            GM.getValue
// @grant            unsafeWindow
// @grant            GM.xmlHttpRequest
// @run-at           document-idle
// ==/UserScript==

// See rentry.org/bicedit#config
var config = {
    forcePollingLowPriorityGens: true,
    enableLongPrompts: false,
    rememberLastSubmittedPrompt: true,
    saveCredits: false,
    hideInsightsPanel: true,
    enableStyleSuggestions: false,
    styleSuggestions: [
    "(Open this userscript source code to edit these suggestions)",
    "monochrome dot-printed manga",
    "watercolor",
    "cgi 3d render",
    "fiery colors",
    ],
}


var refreshIterationsNeeded = 7;
var editContainer = null;
var styleTb = null;
var aspectRatioCb = null;
var lastRegen = 0;
var createBtnText = null;
var newPromptInput = null;
var mainInterval = null;
var generationInfo = [];

(function () {
    if (!shouldExecuteScript()) {
        return;
    }
    if (config.enableLongPrompts) {
        enableLongerPrompts();
    } else if (config.saveCredits) {
        saveCreditsDefaultInput();
    }
    if (isCustomGen()) {
        customGenerationInProgress();
    }
    thumbnailStuff(false);
    mainInterval = setInterval(update, 1000);
    window.addEventListener('popstate', function () {
        if (mainInterval == null) {
            console.log("started interval");
            editContainer.remove();
            mainInterval = setInterval(update, 1000);
        }
    });
})();

// Regeneration in progress
function customGenerationInProgress() {
    const urlParams = new URLSearchParams(window.location.search);
    const errorMsg = document.getElementsByClassName("gil_err_mt");
    const errorDesc = document.getElementsByClassName("gil_err_sbt");
    const errorImg = document.getElementsByClassName("gil_err_img rms_img");
    const notFound = errorMsg.length > 0 && errorImg[0].src.includes("dtahmJyCX5kbcYNFtsv00qhgfAc.jpg");
    if (!notFound) {
        thumbnailStuff(true);
        return true;
    }
    let useOldBehavior = false;
    let refreshInterval = null;
    errorImg[0].src = "https://r.bing.com/rp/TX9QuO3WzcCJz1uaaSwQAz39Kb0.jpg";
    const updateText = function () {
        errorMsg[0].innerText = "Image generation in progress";
        errorDesc[0].innerText = useOldBehavior ? "This page will refresh automatically every 7 seconds. If the image doesn't appears within 40 seconds, it was most likely filtered and you can close this tab. Refreshing in " + refreshIterationsNeeded + "s..." : "Periodically checking this image generation status...";
    }
    const oldBehavior = function () {
        if (--refreshIterationsNeeded <= 0) {
            location.reload();
            clearInterval(refreshInterval);
        } else {
            updateText();
        }
    };
    const ontick = function () {
        if (useOldBehavior) {
            oldBehavior();
            return;
        }
        checkEditStatus(skey, genId, onsuccess, onblocked, onfailed);
        if (refreshInterval == null) {
            restartInterval();
        }
    };
    const restartInterval = function () {
        if (refreshInterval != null) {
            clearInterval(refreshInterval);
        }
        refreshInterval = setInterval(ontick, useOldBehavior ? 1000 : 2500);
    };
    const genId = getGenId();
    const skey = urlParams.get("skey");
    const onsuccess = function () {
        location.reload();
        clearInterval(refreshInterval);
    };
    const onblocked = function () {
        clearInterval(refreshInterval);
        errorImg[0].src = "https://r.bing.com/rp/in-2zU3AJUdkgFe7ZKv19yPBHVs.png";
        errorMsg[0].innerText = "Image was blocked";
        errorDesc[0].innerText = "";
        document.title = "(Blocked) " + document.title;
    };
    const onfailed = function () {
        useOldBehavior = true;
        restartInterval();
    };
    if (skey == null) {
        useOldBehavior = true;
    }
    updateText();
    ontick();
    return true;
}

// Editing feature
function update() {
    const frameElm = getDocument();
    const detailsElm = frameElm.getElementById("detailMeta");
    const imgd = frameElm.getElementById("msz");
    if (detailsElm != null && imgd != null && imgd.innerText != null) {
        clearInterval(mainInterval);
        mainInterval = null;
        console.log("stopped interval");
        hideInsights();
        checkEditedGenerations(getGenId(), checkEditedGenerationsCallback);
    }
}

function checkEditedGenerationsCallback(result) {
    generationInfo = result;
    addContent(getDocument().getElementById("detailMeta"));
}

function prepare() {
    const imageWinElm = getDocument().getElementById("mainImageWindow");
    const meta = JSON.parse(imageWinElm.getAttribute("data-m").replaceAll("&quot;", "\""));
    let thumb = meta.ClickThroughUrl.match(/(OIG.+?)(&|$)/)[1];
    if (thumb.includes("%2e")) {
        thumb = decodeURI(thumb);
    }
    const imgInfo = getImgInfo(thumb);
    if (imgInfo == null) {
        alert("Image mismatch. Refresh the page");
        return;
    }
    const imgId = imgInfo.isEdited ? imgInfo.editImgId : imgInfo.imgId;
    const querystrings = getWindow().ImageDetailReducers.g_PageConfig.persistedQueryStrings;
    const genId = getGenId();
    const skey = /skey=(.+?)&/.exec(querystrings)[1];
    const query = getDocument().getElementsByClassName("ptitle nolink")[0].innerText;
    if (imgId == null || imgId.length < 5 || skey == null || skey.length < 5) {
        alert("Something went wrong");
        return;
    }
    sendResizeRequest(encodeURIComponent(genId), encodeURIComponent(imgId), encodeURIComponent(skey), encodeURIComponent(query));
}

function addContent(detailsElm) {
    const main = detailsElm.getElementsByClassName("actn_container")[0];
    editContainer = document.createElement("div");
    const generateBtn = createButton("generatebtn", "Generate", onGenerateBtnClick, {"width": "150px"});
    const randomizeBtn = createButton("randomizeBtn", "Random", onRandomizeBtnClick, {"width": "95px"});
    aspectRatioCb = createCombobox("aspectrationcb", ["Square (1024x1024)", "Landscape (1792x1024)", "Portrait (1024x1792)"]);
    editContainer.setAttribute("style", "margin-top:15px;");
    addPromptTextbox(editContainer);
    editContainer.append(randomizeBtn, document.createElement("br"), aspectRatioCb, generateBtn);
    main.appendChild(editContainer);
    detailsElm.firstChild.setAttribute("style", "line-height: 20px;font-size:16px; width: 90%;");
    (async () => {
        await updateEditElements();
    })();
}

async function updateEditElements() {
    const lastUsedStyle = await GM.getValue("style", "original");
    const lastUsedAspectRatio = await GM.getValue("aspectratio", 1);
    if (lastUsedStyle !== undefined && lastUsedStyle.toLowerCase() !== "original") {
        styleTb.value = lastUsedStyle;
    }
    if (lastUsedAspectRatio >= 0 && lastUsedAspectRatio <= 2) {
        aspectRatioCb.children[lastUsedAspectRatio].setAttribute("selected", "selected");
    }
}

// Longer prompts feature
function enableLongerPrompts() {
    const form = document.getElementById("sb_form");
    const container = document.getElementById("b_searchboxForm");
    const promptInput = document.getElementById("sb_form_q");
    const submitButton = document.getElementById("create_btn_c");
    const clearButton = document.getElementById("gi_clear");
    newPromptInput = document.createElement("textarea");
    const surpriseMeButton = document.getElementById("surprise-me");
    if (form === null || promptInput === null) {
        console.log("form or input is null");
        return;
    }
    const oldValue = promptInput.value;
    container.removeChild(promptInput);
    container.setAttribute("style", "border-radius: unset; height:125px; margin-bottom: 45px;");
    clearButton.setAttribute("style", "display:none;");
    surpriseMeButton.setAttribute("style", "display:none;");
    document.getElementById("b_footer").setAttribute("style", "display:none;");
    document.getElementById("fbpgbt").setAttribute("style", "display:none;");
    form.setAttribute("method", "get");
    form.setAttribute("action", "/images/create?q=%QUERY%&rt=%RequestTier%"); //remove FORM=GENCRE
    form.appendChild(createHiddenInput("partner", "Sydney"));
    form.appendChild(createHiddenInput("gptexp", "designer"));
    form.appendChild(createHiddenInput("showselective", "1"));
    form.appendChild(createHiddenInput("rt", getRequestTier()));
    newPromptInput.value = oldValue;
    newPromptInput.setAttribute("style", "background-color:#625f5f; color:#f7f1de;");
    newPromptInput.setAttribute("name", "q");
    newPromptInput.setAttribute("class", "b_searchbox gi_sb");
    newPromptInput.setAttribute("id", "sb_form_q");
    newPromptInput.setAttribute("title", "");
    newPromptInput.setAttribute("placeholder", "Type anything");
    newPromptInput.setAttribute("autocapitalize", "none");
    newPromptInput.setAttribute("autocorrect", "true");
    newPromptInput.setAttribute("autocomplete", "off");
    newPromptInput.setAttribute("spellcheck", "true");
    newPromptInput.setAttribute("aria-live", "polite");
    newPromptInput.setAttribute("maxlength", "850");
    newPromptInput.setAttribute("data-maxlength", "850");
    newPromptInput.addEventListener("input", () => {
        updateCreateButtonText();
    });
    container.insertBefore(newPromptInput, container.firstChild);
    submitButton.addEventListener("click", () => {
        if (/\S/.test(newPromptInput.value)) {
            GM.setValue("lastUsedPrompt", newPromptInput.value);
        }
        form.submit();
    });
    submitButton.classList.remove("disabled");
    updateCreateButtonText();
    if (/^\s*$/.test(newPromptInput.value) && config.rememberLastSubmittedPrompt) {
        (async () => {
            const lastUsedPrompt = await GM.getValue("lastUsedPrompt");
            if (lastUsedPrompt !== undefined) {
                newPromptInput.value = lastUsedPrompt;
                updateCreateButtonText();
            }
        })();
    }
}

function updateCreateButtonText() {
    const buttonText = document.getElementById("create_btn");
    if (createBtnText === null) {
        createBtnText = buttonText.innerText;
    }
    buttonText.innerHTML = `${createBtnText}<br/>(${newPromptInput.value.length}/850)`;
}

// misc
function getImgInfo(thumb) {
    for (let i = 0; i < generationInfo.length; i++) {
        if (generationInfo[i].thumb.includes(thumb)) {
            return generationInfo[i];
        }
    }
    return null;
}

function saveCreditsDefaultInput() {
    const formElm = document.getElementById("sb_form");
    if (formElm === null) {
        return;
    }
    const attr = formElm.getAttribute("data-actn");
    if (attr.includes("%RequestTier%")) {
        formElm.setAttribute("data-actn", attr.replace("%RequestTier%", "3"));
        editCreditsText();
    }
}

function editCreditsText() {
    const creditsElm = document.getElementById("token_bal");
    if (creditsElm === null) {
        return;
    }
    creditsElm.setAttribute("style", "color:#35f96e;font-weight:bold;")
}

function hideInsights() {
    if (!config.hideInsightsPanel) {
        return;
    }
    const imageDiv = getDocument().getElementsByClassName("idp-refresh-page-main-line");
    if (imageDiv.length > 0) {
        imageDiv[0].setAttribute("style", "height: 100%;");
    }
    const insightsDiv = getDocument().getElementsByClassName("idp-refresh-page-bottom-page");
    if (insightsDiv.length > 0) {
        insightsDiv[0].remove();
    }
}

function thumbnailStuff(addQueryParam) {
    let results = document.getElementsByClassName("single-img-link");
    for (var i = 0; i < results.length; i++) {
        var element = results[i];
        if (addQueryParam) {
            element.href = element.href + "&_dbe=1";
        }
        const src = element.firstChild.getAttribute("src");
        if (location.hostname === "copilot.microsoft.com" && src.startsWith("/th/")) {
            element.firstChild.src = "https://www.bing.com" + src;
        }
    }
}

function shouldExecuteScript() {
    return window.top === window.self && !checkShouldRedirect();
}

function checkShouldRedirect() {
    const url = new URL(window.location.href);
    const params = new URLSearchParams(window.location.search);
    const errDiv = document.getElementById("girer");
    if (errDiv !== null && params.get("_dbe") !== "1") {
        // hide report button if there is one
        const reportButton = document.getElementsByClassName("gie_btns");
        for (const button of reportButton) {
            button.setAttribute("style", "display:none;");
        }
        return true;
    }
    let selective = false;
    let rt3 = false;
    if (params.get("showselective") === "1") {

        params.delete("showselective");
        selective = true;
    }
    if (params.get("rt") === "3" && config.forcePollingLowPriorityGens && (isLoadingGen() || selective)) {
        params.set("rt", "4");
        rt3 = true;
    }
    if (selective || rt3) {
        url.search = params.toString();
        window.location.href = url.toString();
        return true;
    }
    return false;
}

function getDocument() {
    return unsafeWindow.document.getElementById("OverlayIFrame")?.contentWindow?.document ?? unsafeWindow.document;
}

function getWindow() {
    return unsafeWindow.document.getElementById("OverlayIFrame")?.contentWindow?.window ?? unsafeWindow;
}

function getGenId() {
    const pathSplit = window.location.pathname.split('/');
    return pathSplit[pathSplit.length - 1];
}

function isCustomGen() {
    const params = new URLSearchParams(window.location.search);
    return params.get("_dbe") === "1";
}

function isLoadingGen() {
    const loadDiv = document.getElementById("giloader");
    if (loadDiv == null || document.getElementById("giloadimg") == null) {
        return false;
    }
    return !loadDiv.getAttribute("style").includes("display: none") && document.getElementById("giloadimg")?.getAttribute("src")?.includes("-3tvyvtIq4VNBjzovLgjO68NrLg");
}

function getRequestTier() {
    if (config.saveCredits) {
        editCreditsText();
        return "3";
    }
    const element = document.getElementById("token_bal");
    if (element === null) {
        return "3";
    }
    return parseInt(element.innerText) > 0 ? "4" : "3";
}

function createButton(id, text, onclick, additionalCSSDiv = null, additionalCSSSpan = null) {
    const defaultCSSDiv = {
        "background-color": "#656565",
        "display": "inline-block",
        "margin-left": "20px",
        "text-align": "center"
    };
    const defaultCSSSpan = {
        "color": "#fff",
        "font-size": "17px",
        "font-weight": "bold"
    };
    const newButton = document.createElement("div");
    const newButtonText = document.createElement("span");
    newButtonText.setAttribute("id", `${id}_text`);
    newButtonText.innerText = text;
    newButton.setAttribute("class", "action nofocus");
    newButton.setAttribute("id", id);
    newButton.onclick = onclick;
    stylize(newButton, defaultCSSDiv, additionalCSSDiv);
    stylize(newButtonText, defaultCSSSpan, additionalCSSSpan);
    newButton.appendChild(newButtonText);
    return newButton;
}

function createTextbox(id, placeholder, maxlength = 100, spellcheck = true, additionalCSS = null) {
    const defaultCSS = {
        "background-color": "#f7e6d2",
        "color": "#535151",
        "font-size": "15px",
        "font-weight": "bold"
    };
    const newTextbox = document.createElement("input");
    newTextbox.setAttribute("type", "text");
    newTextbox.setAttribute("placeholder", placeholder);
    newTextbox.setAttribute("id", id);
    newTextbox.setAttribute("maxlength", maxlength);
    newTextbox.setAttribute("spellcheck", spellcheck);
    stylize(newTextbox, defaultCSS, additionalCSS);
    return newTextbox;
}

function createCombobox(id, items, additionalCSS = null) {
    const defaultCSS = {
        "background-color": "#f7e6d2",
        "color": "#535151",
        "font-size": "13px",
        "font-weight": "bold"
    };
    const newCombobox = document.createElement("select");
    newCombobox.setAttribute("id", id);
    for (let i = 0; i < items.length; i++) {
        var option = document.createElement("option");
        option.setAttribute("value", i.toString());
        option.innerText = items[i];
        newCombobox.appendChild(option);
    }
    stylize(newCombobox, defaultCSS, additionalCSS)
    return newCombobox;
}

function createHiddenInput(name, value) {
    const newInput = document.createElement("input");
    newInput.setAttribute("type", "hidden");
    newInput.setAttribute("name", name);
    newInput.setAttribute("value", value);
    return newInput;
}

function addPromptTextbox(container) {
    const additionalCSS = {
        "width": "310px",
        "text-align": "center",
        "margin-bottom": "14px"
    }
    styleTb = createTextbox("bicprompt", "Style prompt. See rentry page for more info", 270, true, additionalCSS);
    container.appendChild(styleTb);
    if (config.enableStyleSuggestions) {
        styleTb.setAttribute("list", "styleSuggestions");
        const dl = document.createElement("datalist");
        dl.setAttribute("id", "styleSuggestions");
        for (let i = 0; i < config.styleSuggestions.length; i++) {
            const opt = document.createElement("option");
            opt.setAttribute("value", config.styleSuggestions[i]);
            dl.appendChild(opt);
        }
        container.appendChild(dl);
    }
}

function stylize(element, defaultStyle, newStyle) {
    let style = "";
    if (defaultStyle != null) {
        for (let i = 0; i < Object.keys(defaultStyle).length; i++) {
            const key = Object.keys(defaultStyle)[i];
            if (newStyle != null && newStyle[key] != null) {
                continue;
            }
            style += `${key}:${defaultStyle[key]};`;
        }
    }
    if (newStyle != null) {
        for (let i = 0; i < Object.keys(newStyle).length; i++) {
            const key = Object.keys(newStyle)[i];
            style += `${key}:${newStyle[key]};`;
        }
    }
    if (style.length > 0) {
        element.setAttribute("style", style);
    }
}

// requests
function checkEditedGenerations(genid, callback) {
    GM.xmlHttpRequest({
        method: "GET",
        url: `/images/create/detail/async/${genid}?imageId=qrvSx5UnVFBE3jM3T1uD5g%3D%3D`,
        onload: function (response) {
            checkEditedGenerationsResponse(response, callback);
        },
        error: function () {
            console.log("Failed generation metadata request");
        }
    });
}

function sendResizeRequest(genid, imgid, skey, query) {
    query = "-";
    let style = "original";
    let aspectratio = 1;
    if (styleTb != null && /\S/.test(styleTb.value)) {
        style = styleTb.value;
    }
    if (aspectRatioCb != null && aspectRatioCb.selectedIndex !== -1) {
        aspectratio = aspectRatioCb.value;
    }
    console.log("Generating this image with an aspect ratio value of '" + aspectratio + "' with the style '" + style + "'.");
    GM.setValue("style", style);
    GM.setValue("aspectratio", aspectratio);
    GM.xmlHttpRequest({
        method: "POST",
        url: `/images/edit/resize?iid=${imgid}&skey=${skey}&id=${genid}&q=${query}&partner=Sydney&ar=${aspectratio}&s=${style}&rt=3`,
        onload: function (response) {
            sendResizeRequestResponse(response, skey);
        },
        error: function () {
            alert("Couldn't send request.");
        }
    });
}

function checkEditStatus(skey, genid, onsuccess, onblocked, onfailed) {
    GM.xmlHttpRequest({
        method: "GET",
        url: `/images/edit/poll?iid=ey%3D%3D&skey=${skey}&id=${genid}&q=-&partner=Sydney`,
        onload: function (response) {
            checkEditStatusResponse(response, onsuccess, onblocked, onfailed);
        },
        error: function () {
            onfailed();
        }
    });
}

// events
function checkEditedGenerationsResponse(response, callback) {
    if (response.status === 200) {
        const jsonRes = JSON.parse(response.responseText);
        if (jsonRes.totalEstimatedMatches === 0) {
            callback([]);
            return;
        }
        const generationInfo = [];
        for (const img of jsonRes.value) {
            generationInfo.push({
                "imgId": img.imageId,
                "editImgId": img.latestEditedImageId,
                "thumb": img.thumbnailUrl,
                "isEdited": img.style !== ""
            });
        }
        callback(generationInfo);
    }
}

function sendResizeRequestResponse(response, skey) {
    var jsonRes = JSON.parse(response.responseText);
    if (response.status === 200) {
        const urlSplit = jsonRes.webSearchUrl.split('/');
        window.open(`/images/create/-/${urlSplit[urlSplit.length - 1]}?_dbe=1&skey=${skey}`, '_blank');
    } else if (jsonRes.errors[0].message.includes("InvalidOwner")) {
        alert("Request was unsuccessful: You are trying to edit an image that doesn't belongs to the current account you are using.");
    } else if (jsonRes.errors[0].code === ("RateLimitExceeded")) {
        alert("Request was unsuccessful: Your account exceeded rate limit.");
    } else if (jsonRes.error[0].message === "Missing createImageV3Response") {
        alert("Request was unsuccessful: Server returned a generic error. Try again.");
    } else {
        alert("Request was unsuccessful: Unknown error.");
    }
}

function checkEditStatusResponse(response, onsuccess, onblocked, onfailed) {
    if (response.status === 404) {
        onfailed();
        return;
    }
    const jsonRes = JSON.parse(response.responseText);
    if (jsonRes._type === "RetrieveImagesResponse" && jsonRes.images != null && jsonRes.images.length > 0) {
        onsuccess();
    } else if (jsonRes._type === "ErrorResponse") {
        for (const error of jsonRes.errors) {
            if (error.subCode === "ContentPolicy" && error.message === "Blocked by DallE") {
                onblocked();
            }
        }
    }
}

function onGenerateBtnClick() {

    const now = performance.now();
    if (lastRegen + 450 < now) {
        lastRegen = now;
        prepare();
    }
}

function onRandomizeBtnClick() {
    styleTb.value = crypto.randomUUID();
}
Edit
Pub: 22 Mar 2024 03:54 UTC
Edit: 12 May 2024 18:14 UTC
Views: 5913