22

The close/flag dialog should only be dismissed when explicitly clicking on the "close" UI element (the little "x" on the upper right)

enter image description here

Most of the time accidental dismissal of the dialog is harmless (the harm is at most re-navigating to the appropriate flag/close option)

But it can be very frustrating when it happens when one is on the process of trying to write a detailed custom flag. All the links and witticisms disappear in a puff of figurative smoke because an absurd misclick, which may even happen because one is trying to gather more data to add to the flag message.

I see very little benefit for this dialog to be dismissed to easily, particularly when the opportunity exists to waste a flagger's time in the process, and a clear, explicit UI alternative is already provided.

Alternatives like:

  • Persisting the written text in local-storage
  • Prompt the user for confirmation if there is already text written, as suggested here on this very old, very closely related feature-request.1

Would also be acceptable. I just figure that removing the magic dialog dismissal provides the same benefits for less work. But anything that prevents this kind of thing would be welcome in any case.

1: Comments on that question already mention this applies to other dialogs, and that the simpler solution is the one I naively propose here:

comments on linked question

13
  • 20
    Ah, so you're the one behind those flags written in Latin!
    – Cody Gray Mod
    Commented Jun 10, 2021 at 6:09
  • 9
    And you must be the one declining them! Gotcha!
    – yivi
    Commented Jun 10, 2021 at 6:10
  • 4
    Related (same UX bug): Should user be prompted when starting a bounty and clicking away from popup? An alternative would be to persist this text, and bring it back up when you invoked the dialog for a second time after inadvertently dismissing it.
    – Cody Gray Mod
    Commented Jun 10, 2021 at 6:11
  • Yup, could be understood as a dupe, no issues with that. I had trouble believing nobody had reported this yet. Thought about persisting the text, but imagined that removing a feature (the dismissal of the dialog because of clicking somewhere has to be coded) might be cheaper than adding one.
    – yivi
    Commented Jun 10, 2021 at 6:12
  • 3
    I would like to +1 this but feel like it puts way too much weight on the "no closing" solution. Both "Persisting the written text in local-storage" and "closing a dialog by clicking outside it" seem to be standard UI practice these days. It would be weird if only the dialogs with text cannot be closed by clicking outside, and annoying if no dialogs can be closed like this. Commented Jun 10, 2021 at 7:22
  • 2
    @MisterMiyagi - well, true, but it is also a good practice nowadays to preserve the text if the user already started writing it, be it them navigating from the page, accidentally hitting page refresh, or closing the modal. Methinks it is really easy to provide those who have access to localStorage/sessionStorage with persistent text. There is also a friendlier solution of not removing the modal from the DOM but collapsing it instead thus keeping the text should the user open the modal again. P.s. yivi, have another +1 for the request
    – 0Valt
    Commented Jun 10, 2021 at 9:37
  • 4
    The inadvertent loss of text you've entered into a textarea is a common issue across many sites. Personally, I use a browser extension which automatically saves data entered into textarea elements. The last I searched for them, there were a few available. The one I use, Textarea Cache, is available for Chrome and Firefox. Having a cache available has saved me many times from having to re-compose input. It's not perfect, but it's helpful.
    – Makyen Mod
    Commented Jun 10, 2021 at 17:22
  • @Makyen I also use Textarea Cache and it helps a lot. Not only for accidentally loosing comments but also if I want to find something I've written, then I search through its database. I do agree it can be better and it's a bit annoying that I need a third party thing to handle what seems like a rather basic UX thing (accidentally losing text). Especially since accidentally dismissing a modal is a very common way of losing it. Yet, here we are. At least there is an alternative.
    – VLAZ
    Commented Jun 11, 2021 at 6:27
  • 3
    It's great that third party alternatives exist. It's not great that a modal that requires actionable input can be dismissed without an explicit user action. There is a "close dialog" element, just use that. Or if for some weird UX nightmarish thing one doesn't want to, just store things in local storage. Although I think would still be the wrong tool for the problem. Or better put: it's a good tool for the problem, but not having the problem in the first place would be nice.
    – yivi
    Commented Jun 11, 2021 at 6:34
  • @yivi "It's not great that a modal that requires actionable input can be dismissed without an explicit user action." I fully agree. The first time I installed a third party alternative (Lazarus - to this day the best plugin I've used. Sadly out of support) was after I spent about 40 minutes typing something in a modal window and accidentally clicked outside. That was around 15 years ago. It's like we haven't really progressed when we still have the same issues today. These issues are well known as well. I think everybody I know has at least one similar experience.
    – VLAZ
    Commented Jun 11, 2021 at 6:56
  • @OlegValter I completely agree, that's why I had an "and" between "persisting the text" and "closing the dialog". I would just strongly prefer to see this solved properly, i.e. persisting on close, instead of applying a bandaid, i.e. disabling simple close. Commented Jun 11, 2021 at 7:00
  • 1
    @MisterMiyagi yeah, me too. It's just that I am a little past the point where I believe SE has an interest in solving anything properly even in the usual 6-8 weeks... yivi's feature request is probably easily solvable via a userscript for now with ease (and I think a couple already exist) but, well, I agree that's not a proper solution.
    – 0Valt
    Commented Jun 11, 2021 at 12:15
  • 2
    Similar MSE request: Save custom flag content if dialog is dismissed
    – Tomerikoo
    Commented Jun 12, 2021 at 14:59

1 Answer 1

8

The behavior is certainly annoying but nothing that could not be solved without a userscript. Below is a script that preserves text entered in any input of the flag modal (including custom reasons in submodals) while allowing the modal to be closed upon clicking away from it.

Script Preview:

flag input preservation preview

TypeScript source:

type Inputs = HTMLTextAreaElement | HTMLInputElement;

type Data = { [name: string]: string };

((_w, d) => {
    const flagModalQueries = ["#popup-flag-post", "#popup-close-question"];
    const submitBtnQuery = ".js-popup-submit";
    const skey = "_flag-overcharged";

    const save = (data: Data) => {
        try {
            localStorage.setItem(skey, JSON.stringify(data));
        } catch (error) {
            console.debug(`failed to persist input data: ${error}`);
        }
    };

    const load = () => JSON.parse(localStorage.getItem(skey) || "{}");

    const findRecord = (records: MutationRecord[], skipped: number[]) => {
        return records.find(({ addedNodes }) =>
            [...addedNodes].some(
                (node) =>
                    !skipped.includes(node.nodeType) &&
                    flagModalQueries.some((query) =>
                        (<HTMLElement>node).matches(query)
                    )
            )
        );
    };

    const throttle = <T extends (...args: any[]) => any>(
        cbk: T,
        period = 100
    ) => {
        let throttled = false;
        return (...args: Parameters<T>) => {
            if (!throttled) {
                throttled = true;
                setTimeout(() => (throttled = false), period);
                return cbk(...args);
            }
        };
    };

    const savedData: Data = load();

    const skippedNodeTypes = [Node.COMMENT_NODE, Node.TEXT_NODE];

    const obs = new MutationObserver((records) => {
        const record = findRecord(records, skippedNodeTypes);
        if (!record) return;

        const {
            addedNodes: [flagModule],
        } = record;

        const modal = <HTMLDivElement>flagModule;

        modal.addEventListener(
            "input",
            throttle(({ target }) => {
                const { name, value } = <HTMLInputElement>target;
                savedData[name] = value;
                save(savedData);
            })
        );

        modal.addEventListener("click", ({ target }) => {
            if (!(<HTMLElement>target).matches(submitBtnQuery)) return;

            const inputs = [
                ...modal.querySelectorAll<Inputs>("input, textarea"),
            ];
            inputs.forEach(
                (input) => (input.value = savedData[input.name] = "")
            );
        });

        Object.entries(savedData).forEach(([name, value]) => {
            const input = modal.querySelector<Inputs>(`[name=${name}]`);
            if (!input) return;
            input.value = value;
        });
    });

    obs.observe(d, {
        subtree: true,
        childList: true,
    });
})(window, document);

Compiled and minified version:

"use strict";(e=>{const s=["#popup-flag-post","#popup-close-question"],r="_flag-overcharged";const n=JSON.parse(localStorage.getItem(r)||"{}"),t=[Node.COMMENT_NODE,Node.TEXT_NODE],o=new MutationObserver(e=>{var o,e=(e=e,o=t,e.find(({addedNodes:e})=>[...e].some(t=>!o.includes(t.nodeType)&&s.some(e=>t.matches(e)))));if(e){var{addedNodes:[e]}=e;const a=e;a.addEventListener("input",((t,o=100)=>{let a=!1;return(...e)=>{if(!a)return a=!0,setTimeout(()=>a=!1,o),t(...e)}})(({target:e})=>{var{name:t,value:e}=e;n[t]=e,(e=>{try{localStorage.setItem(r,JSON.stringify(e))}catch(e){console.debug(`failed to persist input data: ${e}`)}})(n)})),a.addEventListener("click",({target:e})=>{if(e.matches(".js-popup-submit")){const t=[...a.querySelectorAll("input, textarea")];t.forEach(e=>e.value=n[e.name]="")}}),Object.entries(n).forEach(([e,t])=>{const o=a.querySelector(`[name=${e}]`);o&&(o.value=t)})}});o.observe(e,{subtree:!0,childList:!0})})((window,document));

Compiled and minified ES5 version:

"use strict";var __read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,a,o=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=o.next()).done;)i.push(n.value)}catch(e){a={error:e}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(a)throw a.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r){for(var t=0,n=r.length,a=e.length;t<n;t++,a++)e[a]=r[t];return e};!function(e){var a=["#popup-flag-post","#popup-close-question"],o="_flag-overcharged",i=JSON.parse(localStorage.getItem(o)||"{}"),r=[Node.COMMENT_NODE,Node.TEXT_NODE];new MutationObserver(function(e){var t,n,e=(t=r,e.find(function(e){e=e.addedNodes;return __spreadArray([],__read(e)).some(function(r){return!t.includes(r.nodeType)&&a.some(function(e){return r.matches(e)})})}));e&&((n=__read(e.addedNodes,1)[0]).addEventListener("input",function(t,n){void 0===n&&(n=100);var a=!1;return function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];if(!a)return a=!0,setTimeout(function(){return a=!1},n),t.apply(void 0,__spreadArray([],__read(e)))}}(function(e){var r=e.target,e=r.name,r=r.value;i[e]=r,function(e){try{localStorage.setItem(o,JSON.stringify(e))}catch(e){console.debug("failed to persist input data: "+e)}}(i)})),n.addEventListener("click",function(e){e.target.matches(".js-popup-submit")&&__spreadArray([],__read(n.querySelectorAll("input, textarea"))).forEach(function(e){return e.value=i[e.name]=""})}),Object.entries(i).forEach(function(e){var r=__read(e,2),e=r[0],r=r[1],e=n.querySelector("[name="+e+"]");e&&(e.value=r)}))}).observe(e,{subtree:!0,childList:!0})}((window,document));

Unminified version with userscript headers: snippet is for the spoiler only

// ==UserScript==
// @author          Oleg Valter
// @description     Enhancements for flagging experience
// @homepage        https://github.com/userscripters/flag-overcharged#readme
// @match           ://*.askubuntu.com/*
// @match           ://*.mathoverflow.net/*
// @match           ://*.serverfault.com/*
// @match           ://*.stackapps.com/*
// @match           ://*.stackexchange.com/*
// @match           ://*.stackoverflow.com/*
// @match           ://*.superuser.com/*
// @name            flag-overcharged
// @source          git+https://github.com/userscripters/flag-overcharged.git
// @supportURL      https://github.com/userscripters/flag-overcharged/issues
// @version         1.1.0
// ==/UserScript==

"use strict";
((_w, d) => {
    const flagModalQueries = ["#popup-flag-post", "#popup-close-question"];
    const submitBtnQuery = ".js-popup-submit";
    const skey = "_flag-overcharged";
    const save = (data) => {
        try {
            localStorage.setItem(skey, JSON.stringify(data));
        }
        catch (error) {
            console.debug(`failed to persist input data: ${error}`);
        }
    };
    const load = () => JSON.parse(localStorage.getItem(skey) || "{}");
    const findRecord = (records, skipped) => {
        return records.find(({ addedNodes }) => [...addedNodes].some((node) => !skipped.includes(node.nodeType) &&
            flagModalQueries.some((query) => node.matches(query))));
    };
    const throttle = (cbk, period = 100) => {
        let throttled = false;
        return (...args) => {
            if (!throttled) {
                throttled = true;
                setTimeout(() => (throttled = false), period);
                return cbk(...args);
            }
        };
    };
    const savedData = load();
    const skippedNodeTypes = [Node.COMMENT_NODE, Node.TEXT_NODE];
    const obs = new MutationObserver((records) => {
        const record = findRecord(records, skippedNodeTypes);
        if (!record)
            return;
        const { addedNodes: [flagModule], } = record;
        const modal = flagModule;
        modal.addEventListener("input", throttle(({ target }) => {
            const { name, value } = target;
            savedData[name] = value;
            save(savedData);
        }));
        modal.addEventListener("click", ({ target }) => {
            if (!target.matches(submitBtnQuery))
                return;
            const inputs = [
                ...modal.querySelectorAll("input, textarea"),
            ];
            inputs.forEach((input) => (input.value = savedData[input.name] = ""));
        });
        Object.entries(savedData).forEach(([name, value]) => {
            const input = modal.querySelector(`[name=${name}]`);
            if (!input)
                return;
            input.value = value;
        });
    });
    obs.observe(d, {
        subtree: true,
        childList: true,
    });
})(window, document);

2
  • 1
    Thanks, this works really well! Could you add the @match headers for the rest of the network in the Tampermonkey script?
    – Ollie
    Commented Jun 18, 2021 at 16:03
  • @Ollie - done, headers updated! Had to update the generator package first - do let me know if @match headers should cover more sites of the network, or there is a more effective way I am missing.
    – 0Valt
    Commented Jun 20, 2021 at 20:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .