Skip to content

Wrap selector-observer to add AbortSignal, better types, etc #5874

Closed

Description

@fregante

I recently mentioned this in a comment but I can't find it anymore. @cheap-glitch also mentioned it in #5726 (review)

Here's part of what I had in mind for a such a wrapper:

Activity

  1. added
    meta
    on Jul 30, 2022
  2. kidonng commented on Jul 31, 2022

    @kidonng
    Member
    • better API (observeElement('a', cb) instead of observe('a',{add: cb}))

    Actually, this already exists in selector-observer, same as:

    observe(selector, {
        initialize(el) {}
    })

    initialize is supposed to only run once, but unfortunately it is still haunted by josh/selector-observer#30 so we can't drop those rgh-* classes.

  3. fregante commented on Jul 31, 2022

    @fregante
    MemberAuthor

    I only suggested an API change, not a behavior change:

    export function observe(selector, cb, signal) {
      const o = selectorObserver.observe(
        selector,
        {add: cb}
      )
      onAbort(signal, o)
    }

    👆 this piece of code covers 2 of the points I suggested.

    Also that reminded of another thing I wanted:

    • automatic class generation and exclusion from the selector

    Also in the future it’d be good to extend attachElements with an observe: true option that queries the selector via selector-observer instead of select.all, but that’s unrelated to this change.

  4. kidonng commented on Jul 31, 2022

    @kidonng
    Member

    not a behavior change

    Sorry if I'm being misleading, "only run once" means for each element, so if we only use add there's no behavior difference from initialize. Though I digged in GitHub's code and they use both (initialize or just add).

    Also, it seems GitHub never teardown their selector-observers?

    image

  5. kidonng commented on Jul 31, 2022

    @kidonng
    Member

    Found an example how GitHub uses AbortController with selector-observer:

    // https://github.githubassets.com/assets/app/assets/modules/github/issues/convert-to-issue-button.ts
    const abortControllers = new WeakMap()
    
    observe('.js-convert-task-to-issue-enabled .comment-body', {
      add(el) {
        const taskItems = getTaskListItems(el)
        decorateItems(el, taskItems)
    
        const abortController = new AbortController()
        abortControllers.set(el, abortController)
        addModifierKeyEventListener(el, abortController.signal)
      },
      remove(el) {
        const controller = abortControllers.get(el)
        if (controller) {
          controller.abort()
        }
      }
    })
  6. fregante commented on Jul 31, 2022

    @fregante
    MemberAuthor

    Honestly I wonder if we should just drop the library and look for alternatives. I feel that having to add the class only to avoid a new call nullifies any speed improvements we get from using the library (if any at all). Also the lib is dead.

    Alternatives:

    • different library?
    • go full MutationObserver in the end (childTree: true 🥲)
    • come up with an animationend-based solution (we add a 1ms animation the selector + listen to the event globally and catch its target)
  7. kidonng commented on Jul 31, 2022

    @kidonng
    Member

    Also the lib is dead.

    GitHub is still happily using it unmodified 🤷‍♂️ I think the lib is fine, it's just different expectations (anything may throw in our case).

    • come up with an animationend-based solution (we add a 1ms animation the selector + listen to the event globally and catch its target)

    That's neat but if there are hundreds of elements, does it impact speed?

  8. fregante commented on Jul 31, 2022

    @fregante
    MemberAuthor

    That's neat but if there are hundreds of elements, does it impact speed?

    This is by far the most efficient, it has 3 parts:

    1. Matching CSS selectors "live" (one of the most optimized paths in the browser)
    2. animationend is triggered even with an empty @keyframes lol {}, which means it doesn't trigger layout/render operations
    3. Event bubbling and listening is far more efficient than MutationObserver

    The best part is that the animation name (keyframes) is part of the event itself, so all we need is something like:

    @keyframes collapsible-element-button {}
    md-ref {animation: 1ms collapsible-element-button}
    const tracked = new WeakMap()
    document.addEventListener('animationstart', {target, animationName} => {
    	if (animationName !== 'collapsible-element-button' || tracked.has(target)) {
    		return
    	}
    	tracked.add(target);
    	attachElement({anchor: target, after: () => <CollapsibleButton/>)})
    });

    If it really is this simple and efficient, Refined GitHub (and other extensions) could become an order or magnitude easier to manage. Imagine making every feature "declarative" this way, no more wonky listeners.

    We can start by adding the CSS to our CSS files for now and maybe later wrap it all in a helper that generates the CSS rules as well as the listener. The only drawback of a dynamic CSS generator is that the CSS would need to be inserted as a literal style tag in the document, but that's not something we need to deal with right now.

  9. kidonng commented on Jul 31, 2022

    @kidonng
    Member

    I also made one:

    import { css } from 'code-tag'
    import type { ParseSelector } from 'typed-query-selector/parser'
    
    export function observe<
        Selector extends string,
        TElement extends Element = ParseSelector<Selector, HTMLElement>
    >(selector: Selector | Selector[], callback: (element: TElement) => void) {
        const name = `animation-observer-${Math.random().toString(36).slice(2)}`
        const style = document.createElement('style')
        style.innerHTML = css`
            @keyframes ${name} {
            }
    
            ${Array.isArray(selector) ? selector.join() : selector} {
                animation-name: ${name};
            }
        `
        document.head.append(style)
        document.addEventListener('animationstart', (e) => {
            if (e.animationName !== name) return
            callback(e.target as TElement)
        })
    }
  10. fregante commented on Jul 31, 2022

    @fregante
    MemberAuthor

    🔥

    Mind a PR? Would be great to see it working on a feature that already uses observe. The problem with the style tag is that it introduces some complexity to this code1 which could save for later, but that's up to you

    Footnotes

    1. they start to pile up in the head after multiple navigations, whereas the static CSS wouldn't — but that wouldn't actually cause any bugs ↩

  11. kidonng commented on Jul 31, 2022

    @kidonng
    Member
    1. they start to pile up in the head after multiple navigations

    Return a cleanup function to remove the style element 😂

    I agree static CSS is better, but that needs to write a separator separate generator, while this works anywhere.

  12. fregante commented on Jul 31, 2022

    @fregante
    MemberAuthor

    The only issue I see with static CSS is that:

    • it requires a CSS to include the keyframes
    • the animation name needs to be specified in 2 places
  13. fregante commented on Jul 31, 2022

    @fregante
    MemberAuthor

    write a separate generator

    Are you referring to the class name? It doesn’t need to be generated, as shown in my example. It would be convenient and ideal, but not required.

  14. cheap-glitch commented on Jul 31, 2022

    @cheap-glitch
    Contributor

    Love the animationend hack!

    The only issue I see with static CSS

    I wonder how hard it'd be to write a Webpack (or maybe PostCSS) plugin to generate the required CSS at build time 🤔

  15. kidonng commented on Jul 31, 2022

    @kidonng
  16. fregante commented on Aug 1, 2022

    @fregante
    MemberAuthor

    Uhm it’s a bit early to put code I imagined and wrote onto npm before knowing whether it works and what its limitations are (because I know it won’t work on every website)

  17. fregante commented on Aug 3, 2022

    @fregante
    MemberAuthor

    See #5886 (comment)

    This is why I wanted to keep things simple for a first pass, it was an experimental idea and it turns out it's not safe to use.

    Will have to revert to the original scope:

    • wrap selector-observer
  18. kidonng commented on Aug 16, 2022

    @kidonng
    Member

    Uhm it’s a bit early to put code I imagined and wrote onto npm before knowing whether it works and what its limitations are (because I know it won’t work on every website)

    I am sorry for this 😔 but I do want to clarify the first prototype I posted here is done separately (and slightly different).

    I'm excited because I really love this idea and am gonna use it a lot. You nailed it here:

    If it really is this simple and efficient, Refined GitHub (and other extensions) could become an order or magnitude easier to manage. Imagine making every feature "declarative" this way, no more wonky listeners.

    I've since incorporated the awesome improvements in #5886 into my library, credits to you ✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedmetaunder discussion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions