Giter VIP home page Giter VIP logo

unist-util-select's Introduction

unist-util-select

Build Coverage Downloads Size Sponsors Backers Chat

unist utility with equivalents for querySelector, querySelectorAll, and matches.

Contents

What is this?

This package lets you find nodes in a tree, similar to how querySelector, querySelectorAll, and matches work with the DOM.

One notable difference between DOM and hast is that DOM nodes have references to their parents, meaning that document.body.matches(':last-child') can be evaluated to check whether the body is the last child of its parent. This information is not stored in hast, so selectors like that don’t work.

When should I use this?

This utility works on any unist syntax tree and you can select all node types. If you are working with hast, and only want to select elements, use hast-util-select instead.

This is a small utility that is quite useful, but is rather slow if you use it a lot. For each call, it has to walk the entire tree. In some cases, walking the tree once with unist-util-visit is smarter, such as when you want to change certain nodes. On the other hand, this is quite powerful and fast enough for many other cases.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install unist-util-select

In Deno with esm.sh:

import {matches, select, selectAll} from "https://esm.sh/unist-util-select@5"

In browsers with esm.sh:

<script type="module">
  import {matches, select, selectAll} from "https://esm.sh/unist-util-select@5?bundle"
</script>

Use

import {u} from 'unist-builder'
import {matches, select, selectAll} from 'unist-util-select'

const tree = u('blockquote', [
  u('paragraph', [u('text', 'Alpha')]),
  u('paragraph', [u('text', 'Bravo')]),
  u('code', 'Charlie'),
  u('paragraph', [u('text', 'Delta')]),
  u('paragraph', [u('text', 'Echo')]),
  u('paragraph', [u('text', 'Foxtrot')]),
  u('paragraph', [u('text', 'Golf')])
])

console.log(matches('blockquote, list', tree)) // => true

console.log(select('code ~ :nth-child(even)', tree))
// The paragraph with `Delta`

console.log(selectAll('code ~ :nth-child(even)', tree))
// The paragraphs with `Delta` and `Foxtrot`

API

This package exports the identifiers matches, select, and selectAll. There is no default export.

matches(selector, node)

Check that the given node matches selector.

This only checks the node itself, not the surrounding tree. Thus, nesting in selectors is not supported (paragraph strong, paragraph > strong), neither are selectors like :first-child, etc. This only checks that the given node matches the selector.

Parameters
  • selector (string) — CSS selector, such as (heading, link, linkReference).
  • node (Node, optional) — node that might match selector
Returns

Whether node matches selector (boolean).

Example
import {u} from 'unist-builder'
import {matches} from 'unist-util-select'

matches('strong, em', u('strong', [u('text', 'important')])) // => true
matches('[lang]', u('code', {lang: 'js'}, 'console.log(1)')) // => true

select(selector, tree)

Select the first node that matches selector in the given tree.

Searches the tree in preorder.

Parameters
  • selector (string) — CSS selector, such as (heading, link, linkReference).
  • tree (Node, optional) — tree to search
Returns

First node in tree that matches selector or undefined if nothing is found.

This could be tree itself.

Example
import {u} from 'unist-builder'
import {select} from 'unist-util-select'

console.log(
  select(
    'code ~ :nth-child(even)',
    u('blockquote', [
      u('paragraph', [u('text', 'Alpha')]),
      u('paragraph', [u('text', 'Bravo')]),
      u('code', 'Charlie'),
      u('paragraph', [u('text', 'Delta')]),
      u('paragraph', [u('text', 'Echo')])
    ])
  )
)

Yields:

{type: 'paragraph', children: [{type: 'text', value: 'Delta'}]}

selectAll(selector, tree)

Select all nodes that match selector in the given tree.

Searches the tree in preorder.

Parameters
  • selector (string) — CSS selector, such as (heading, link, linkReference).
  • tree (Node, optional) — tree to search
Returns

Nodes in tree that match selector.

This could include tree itself.

Example
import {u} from 'unist-builder'
import {selectAll} from 'unist-util-select'

console.log(
  selectAll(
    'code ~ :nth-child(even)',
    u('blockquote', [
      u('paragraph', [u('text', 'Alpha')]),
      u('paragraph', [u('text', 'Bravo')]),
      u('code', 'Charlie'),
      u('paragraph', [u('text', 'Delta')]),
      u('paragraph', [u('text', 'Echo')]),
      u('paragraph', [u('text', 'Foxtrot')]),
      u('paragraph', [u('text', 'Golf')])
    ])
  )
)

Yields:

[
  {type: 'paragraph', children: [{type: 'text', value: 'Delta'}]},
  {type: 'paragraph', children: [{type: 'text', value: 'Foxtrot'}]}
]

Support

  • * (universal selector)
  • , (multiple selector)
  • paragraph (type selector)
  • blockquote paragraph (combinator: descendant selector)
  • blockquote > paragraph (combinator: child selector)
  • code + paragraph (combinator: adjacent sibling selector)
  • code ~ paragraph (combinator: general sibling selector)
  • [attr] (attribute existence, checks that the value on the tree is not nullish)
  • [attr=value] (attribute equality, this stringifies values on the tree)
  • [attr^=value] (attribute begins with, only works on strings)
  • [attr$=value] (attribute ends with, only works on strings)
  • [attr*=value] (attribute contains, only works on strings)
  • [attr~=value] (attribute contains, checks if value is in the array, if there’s an array on the tree, otherwise same as attribute equality)
  • :is() (functional pseudo-class)
  • :has() (functional pseudo-class; also supports a:has(> b))
  • :not() (functional pseudo-class)
  • :blank (pseudo-class, blank and empty are the same: a parent without children, or a node without value)
  • :empty (pseudo-class, blank and empty are the same: a parent without children, or a node without value)
  • :root (pseudo-class, matches the given node)
  • :scope (pseudo-class, matches the given node)
  • * :first-child (pseudo-class)
  • * :first-of-type (pseudo-class)
  • * :last-child (pseudo-class)
  • * :last-of-type (pseudo-class)
  • * :only-child (pseudo-class)
  • * :only-of-type (pseudo-class)
  • * :nth-child() (functional pseudo-class)
  • * :nth-last-child() (functional pseudo-class)
  • * :nth-last-of-type() (functional pseudo-class)
  • * :nth-of-type() (functional pseudo-class)
Notes
  • * — not supported in matches
  • :any() and :matches() are renamed to :is() in CSS

Types

This package is fully typed with TypeScript. It exports no additional types.

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, unist-util-select@^5, compatible with Node.js 16.

Related

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Eugene Sharygin

unist-util-select's People

Contributors

ayc0 avatar christianmurphy avatar eush77 avatar peterbabic avatar wooorm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unist-util-select's Issues

Missing package dependency

Subject of the issue

Missing package dependency.

Your environment

  • OS: Windows
  • Packages: 3.0.1
  • Env: node v12.14.0 , npm 6.13.4

Steps to reproduce

import {Node} from 'unist'

import {Node} from 'unist'

unist isn't included as a dependency in packages.json

Tried to use v3 in place of v2 in gatsby-remark-images-anywhere, got a warning about missing package dependencies.

Expected behaviour

required package dependency stored in packages.json

Actual behaviour

Missing package dependency, fails to run

Circular dependency any.js -> pseudo.js -> any.js using rollup

Circular dependency any.js -> pseudo.js -> any.js using rollup

The rollup bundler is printing warnings about the detected circular dependency:

Circular dependency: node_modules/unist-util-select/lib/any.js -> node_modules/unist-util-select/lib/pseudo.js -> node_modules/unist-util-select/lib/any.js
Circular dependency: node_modules/unist-util-select/lib/any.js -> node_modules/unist-util-select/lib/pseudo.js -> /home/delmadord/work/sapper-blog/node_modules/unist-util-select/lib/any.js?commonjs-proxy -> node_modules/unist-util-select/lib/any.js

I will provide MVE to reproduce as soon as confirmed it is necessary. I may be mistaken of course, but from what I believe right now, any code analysis tool that would check for circular dependency issues should be able to spot this, not just rollup.

Lines that I believe lead to this behavior:

var pseudo = require('./pseudo')

var anything = require('./any')

Thank you for your work

Compile selectors

Currently selectors are interpreted when they execute. This is suboptimal because the same analyses must be performed each time and, more importantly, every new type of selector punishes all consumers regardless of whether they use it or not.

A better opportunity lies in compiling selectors to functions (agnostic of any actual unist tree) and having a module-local cache of those.

Include `@types/unist` in dependencies

Initial checklist

Affected packages and versions

3.0.1 but I think it's still the case in the v4

Link to runnable example

I don't have any 😕

Steps to reproduce

When using a TS project that depends on unist-util-select, TypeScript throws this error:

unist-util-select/types/index.d.ts:3:20 - error TS2307: Cannot find module 'unist' or its corresponding type declarations.

3 import {Node} from 'unist'
                     ~~~~~~~

To fix that, we could include @types/unist in the dependencies (not devDeps) or in the peerDependencies of unist-util-select, so that it'll be shipped / will notify the package manager that it needs @types/unist

Expected behavior

It shouldn't throw any error

Actual behavior

It throws this error:

unist-util-select/types/index.d.ts:3:20 - error TS2307: Cannot find module 'unist' or its corresponding type declarations.

3 import {Node} from 'unist'
                     ~~~~~~~

Runtime

Node v16

Package manager

yarn v2

OS

macOS

Build and bundle tools

Webpack

Support structural pseudo-classes

Spec: http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#structural-pseudos

  • 6.6.5.1. :root pseudo-class
  • 6.6.5.2. :nth-child() pseudo-class
  • 6.6.5.3. :nth-last-child() pseudo-class
  • 6.6.5.4. :nth-of-type() pseudo-class
  • 6.6.5.5. :nth-last-of-type() pseudo-class
  • 6.6.5.6. :first-child pseudo-class
  • 6.6.5.7. :last-child pseudo-class
  • 6.6.5.8. :first-of-type pseudo-class
  • 6.6.5.9. :last-of-type pseudo-class
  • 6.6.5.10. :only-child pseudo-class
  • 6.6.5.11. :only-of-type pseudo-class
  • 6.6.5.12. :empty pseudo-class

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.