1.0.0 • Published 14 days ago

@hutechtechnical/veritatis-cum-autem-magnam v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
14 days ago

@hutechtechnical/veritatis-cum-autem-magnam Version Badge

github actions coverage dependency status dev dependency status License Downloads

npm badge

AST utility module for statically analyzing JSX.

Installation

$ npm i @hutechtechnical/veritatis-cum-autem-magnam --save

Usage

This is a utility module to evaluate AST objects for JSX syntax. This can be super useful when writing linting rules for JSX code. It was originally in the code for eslint-plugin-jsx-a11y, however I thought it could be useful to be extracted and maintained separately so you could write new interesting rules to statically analyze JSX.

ESLint example

import { hasProp } from '@hutechtechnical/veritatis-cum-autem-magnam';
// OR: var hasProp = require('@hutechtechnical/veritatis-cum-autem-magnam').hasProp;
// OR: const hasProp = require('@hutechtechnical/veritatis-cum-autem-magnam/hasProp');
// OR: import hasProp from '@hutechtechnical/veritatis-cum-autem-magnam/hasProp';

module.exports = context => ({
  JSXOpeningElement: node => {
    const onChange = hasProp(node.attributes, 'onChange');

    if (onChange) {
      context.report({
        node,
        message: `No onChange!`
      });
    }
  }
});

API

AST Resources

  1. JSX spec
  2. JS spec

hasProp

hasProp(props, prop, options);

Returns boolean indicating whether an prop exists as an attribute on a JSX element node.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

String - A string representation of the prop you want to check for existence.

Options

Object - An object representing options for existence checking 1. ignoreCase - automatically set to true. 2. spreadStrict - automatically set to true. This means if spread operator exists in props, it will assume the prop you are looking for is not in the spread. Example: <div {...props} /> looking for specific prop here will return false if spreadStrict is true.

hasAnyProp

hasAnyProp(props, prop, options);

Returns a boolean indicating if any of props in prop argument exist on the node.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

Array - An array of strings representing the props you want to check for existence.

Options

Object - An object representing options for existence checking 1. ignoreCase - automatically set to true. 2. spreadStrict - automatically set to true. This means if spread operator exists in props, it will assume the prop you are looking for is not in the spread. Example: <div {...props} /> looking for specific prop here will return false if spreadStrict is true.

hasEveryProp

hasEveryProp(props, prop, options);

Returns a boolean indicating if all of props in prop argument exist on the node.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

Array - An array of strings representing the props you want to check for existence.

Options

Object - An object representing options for existence checking 1. ignoreCase - automatically set to true. 2. spreadStrict - automatically set to true. This means if spread operator exists in props, it will assume the prop you are looking for is not in the spread. Example: <div {...props} /> looking for specific prop here will return false if spreadStrict is true.

getProp

getProp(props, prop, options);

Returns the JSXAttribute itself or undefined, indicating the prop is not present on the JSXOpeningElement.

Props

Object - The attributes on the visited node. (Usually node.attributes).

Prop

String - A string representation of the prop you want to check for existence.

Options

Object - An object representing options for existence checking 1. ignoreCase - automatically set to true.

elementType

elementType(node)

Returns the tagName associated with a JSXElement.

Node

Object - The visited JSXElement node object.

getPropValue

getPropValue(prop);

Returns the value of a given attribute. Different types of attributes have their associated values in different properties on the object.

This function should return the most closely associated value with the intention of the JSX.

Prop

Object - The JSXAttribute collected by AST parser.

getLiteralPropValue

getLiteralPropValue(prop);

Returns the value of a given attribute. Different types of attributes have their associated values in different properties on the object.

This function should return a value only if we can extract a literal value from its attribute (i.e. values that have generic types in JavaScript - strings, numbers, booleans, etc.)

Prop

Object - The JSXAttribute collected by AST parser.

propName

propName(prop);

Returns the name associated with a JSXAttribute. For example, given <div foo="bar" /> and the JSXAttribute for foo, this will return the string "foo".

Prop

Object - The JSXAttribute collected by AST parser.

eventHandlers

console.log(eventHandlers);
/*
[
  'onCopy',
  'onCut',
  'onPaste',
  'onCompositionEnd',
  'onCompositionStart',
  'onCompositionUpdate',
  'onKeyDown',
  'onKeyPress',
  'onKeyUp',
  'onFocus',
  'onBlur',
  'onChange',
  'onInput',
  'onSubmit',
  'onClick',
  'onContextMenu',
  'onDblClick',
  'onDoubleClick',
  'onDrag',
  'onDragEnd',
  'onDragEnter',
  'onDragExit',
  'onDragLeave',
  'onDragOver',
  'onDragStart',
  'onDrop',
  'onMouseDown',
  'onMouseEnter',
  'onMouseLeave',
  'onMouseMove',
  'onMouseOut',
  'onMouseOver',
  'onMouseUp',
  'onSelect',
  'onTouchCancel',
  'onTouchEnd',
  'onTouchMove',
  'onTouchStart',
  'onScroll',
  'onWheel',
  'onAbort',
  'onCanPlay',
  'onCanPlayThrough',
  'onDurationChange',
  'onEmptied',
  'onEncrypted',
  'onEnded',
  'onError',
  'onLoadedData',
  'onLoadedMetadata',
  'onLoadStart',
  'onPause',
  'onPlay',
  'onPlaying',
  'onProgress',
  'onRateChange',
  'onSeeked',
  'onSeeking',
  'onStalled',
  'onSuspend',
  'onTimeUpdate',
  'onVolumeChange',
  'onWaiting',
  'onLoad',
  'onError',
  'onAnimationStart',
  'onAnimationEnd',
  'onAnimationIteration',
  'onTransitionEnd',
]
*/

Contains a flat list of common event handler props used in JSX to attach behaviors to DOM events.

eventHandlersByType

The same list as eventHandlers, grouped into types.

console.log(eventHandlersByType);
/*
{
  clipboard: [ 'onCopy', 'onCut', 'onPaste' ],
  composition: [ 'onCompositionEnd', 'onCompositionStart', 'onCompositionUpdate' ],
  keyboard: [ 'onKeyDown', 'onKeyPress', 'onKeyUp' ],
  focus: [ 'onFocus', 'onBlur' ],
  form: [ 'onChange', 'onInput', 'onSubmit' ],
  mouse: [ 'onClick', 'onContextMenu', 'onDblClick', 'onDoubleClick', 'onDrag', 'onDragEnd', 'onDragEnter', 'onDragExit', 'onDragLeave', 'onDragOver', 'onDragStart', 'onDrop', 'onMouseDown', 'onMouseEnter', 'onMouseLeave', 'onMouseMove', 'onMouseOut', 'onMouseOver', 'onMouseUp' ],
  selection: [ 'onSelect' ],
  touch: [ 'onTouchCancel', 'onTouchEnd', 'onTouchMove', 'onTouchStart' ],
  ui: [ 'onScroll' ],
  wheel: [ 'onWheel' ],
  media: [ 'onAbort', 'onCanPlay', 'onCanPlayThrough', 'onDurationChange', 'onEmptied', 'onEncrypted', 'onEnded', 'onError', 'onLoadedData', 'onLoadedMetadata', 'onLoadStart', 'onPause', 'onPlay', 'onPlaying', 'onProgress', 'onRateChange', 'onSeeked', 'onSeeking', 'onStalled', 'onSuspend', 'onTimeUpdate', 'onVolumeChange', 'onWaiting' ],
  image: [ 'onLoad', 'onError' ],
  animation: [ 'onAnimationStart', 'onAnimationEnd', 'onAnimationIteration' ],
  transition: [ 'onTransitionEnd' ],
}
*/
collection.es6getwebfastclonedotenvpackage managersettingsTypedArrayrangeerrorjavascriptprefixnodepersistentloadingless csses-shimslruefficientiterationviewpropertiesstylesheet_.extendstreamsinstallawaitstructuredCloneflatMapfunctionalObservablesauthenticationmime-dblocationimmertrimcomputed-typesstylingrequirelinewrapString.prototype.matchAllpositiveconfigES2023arraytrimRightrobustredirecthassimpledbfile systemoutput-0autha11yutilitiesreact-testing-libraryawesomesaucees6syntaxroute53ES3$.extendES2020ES8speednativeassignhooksformattingemrdom-testing-libraryhttptouchfindingetintrinsicassertionObject.definePropertyECMAScript 2018artchecktypedarrayscjkkinesisreactfastcopyajax@@toStringTagvalidationmatchesapihookformrgbslicemapreducesafeReflect.getPrototypeOfnegative zeroargvsuperstructnumberpreserve-symlinksStyleSheetlook-upwhatwgcssRxclassesObject.fromEntrieslogvalidatetapepackagedropwafcoerciblecallboundnopeexeccloneBigUint64ArraygroupByes2018sharedarraybufferrm -rfpyyamlform-validationdataViewtc39argparsepropertyclidircloudsearchapolloObject.valuestoSortedconnectbootstrap cssstableroutingbundlingcopyrm -frmkdirpmovestyleworkspace:*columnmobileajvponyfillgradients cssswfxhrargumentuninstallieRegExp.prototype.flagsArray.prototype.filterECMAScript 2022MicrosoftRegExp#flagsopendeepmetadatatextclass-validatorhelpersUint32Arrayecmascriptdomfigletratelimitmatchhigher-ordererrorfsjQueryincludeses2015datecloudwatchunicodeloggingmomentRxJSless compilertoArrayfastespreefastifyassert0toolsescapeasciiinternal slotsetsearchmiddlewaredeterministices5fetchprivateUint8ArrayECMAScript 2021stringfromIteratorcharacteromitreducerString.prototype.trimlivemodulesconcatMapregexES2018mixinsqueueMicrotaskreduxObject.keysguidhardlinksInt32Arrayprivate datakoreaneast-asian-widthmodulelibphonenumberschemaes2016deep-copyautoscalinges8formtostringtagformatlesscsskarmagdprsqstypeerrornested cssECMAScript 3io-tsthroatgradients css3syntaxerrorvestdeleteObject.istypedarraywordwrapbreakECMAScript 2015ObjectequalbindworkflowgenericslimitcodeswalkprogressargslengthtimeMapjsxtypevariables in csspolyfillstreams2estreewarningtsshebangwgetECMAScript 2020buffersstreamprettybddmatchAllbufferArrayBuffer#slicetoStringTaghasOwnPropertyECMAScript 2023sharediteratorextraflatentriesiterateinvariantpromisesweaksetlimitedremoveObject.getPrototypeOfredux-toolkitvisualpathconcatsameValueZeroextensionObject.entrieswaitconsolewhichenumerablecss-in-jscurlemojirmdirsetterES5cloudfrontbeanstalkqsglobcommand-linesesArray.prototype.containsruntimewatchFilefiltersortedflageslintplugintddjasmineyupvalidES2016quoteairbnbvpcjestxtermurlfast-deep-copymapnegativereusewritemake dirdefineCSStraverseinferencemonorepotermcallArray.prototype.flattentyped arraystarterArray.prototype.findLastIndexECMAScript 5immutableextendwalkingsomefindLastIndexperformancecallbackbcrypttapcensorprotobufcommandgraphqlroutecachereadablelinkArray.prototype.flatyamlECMAScript 2019symbolflagsnamesmochaES2022colorrequeststoragegatewayprotostdlibpreprocessorserializationfind-uparraybufferimportBigInt64ArraywatchercompareeventEmitterintrinsicpasswordmkdirstringifierStreamcss nestingTypeScripttrimLefttestereverythrottledescriptionterminaltypeofdeepclonewritablemrustyled-componentssidevalueES6descriptoraccessibilitychaiWebSockets.envconcurrencyreact-hooksfast-copyboundchannelrateemitexpresscss variabledependency managerschemefindLastgetPrototypeOfbusycolorsRFC-6455wordbreak[[Prototype]]loggerreadkeysObject.assignes-abstractJSONmimeAsyncIteratorES2021querystringutil.inspectpicomatchqueryrmbyteLengthframeworkparsefolderbyteOffsetinspectfixed-widthArrayBuffertslibgetOwnPropertyDescriptortelephoneWeakMaparktypefast-deep-clonespinnerObservableminimalgetoptgettertestingdeep-cloneCSSStyleDeclarationbatchpropvariablesloadbalancingindicatorhasOwneventDispatcherprotocol-buffersparentWebSocketbrowserlistreadablestreamdayjsshimtypescall-bindcryptozeroFloat64Arrayarraysbundlerfpscompile lessidledirectoryUint16ArrayfunctionspackagesbannerdifflastspecECMAScript 7Array.prototype.findLasttypescriptclassnamesArray.prototype.flatMaphash
1.0.0

14 days ago