@ng-native/eslint-plugin 0.22.2 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.mjs +300 -62
  2. package/package.json +4 -1
package/index.mjs CHANGED
@@ -6,45 +6,15 @@
6
6
  * never sent, the button draws as a plain view and `document` is undefined. Each rule names what
7
7
  * to write instead.
8
8
  */
9
- import { readFileSync } from 'node:fs';
9
+ import { readFileSync, statSync } from 'node:fs';
10
+ import { dirname, join } from 'node:path';
11
+ import domEvents from '@ng-native/metro/dom-events.cjs';
10
12
  import angular from 'angular-eslint';
11
13
  import tseslint from 'typescript-eslint';
12
14
 
13
- const PRESS = '(press) on a <pressable>, or <text pressable (press)="...">';
14
-
15
- /**
16
- * DOM events no native view sends, with what to listen for instead. An event the renderer is
17
- * given is the native one of the same name (`(scroll)` is `topScroll`), so only names no native
18
- * view or Angular Native component uses are here: `change`, `load`, `error`, `focus` and `blur`
19
- * are outputs or native events of some element and are left alone.
20
- */
21
- const DOM_EVENTS = new Map([
22
- ['click', PRESS],
23
- ['dblclick', PRESS],
24
- ['contextmenu', '(longPress) on a <pressable>'],
25
- ['mousedown', '(pressIn) on a <pressable>'],
26
- ['mouseup', '(pressOut) on a <pressable>'],
27
- ['input', '(changeText) or [(value)] on a <text-input>'],
28
- ['beforeinput', '(changeText) on a <text-input>'],
29
- ['keydown', '(keyPress) or (submitEditing) on a <text-input>'],
30
- ['keyup', '(keyPress) or (submitEditing) on a <text-input>'],
31
- ['keypress', '(keyPress) on a <text-input>'],
32
- ['submit', '(submitEditing) on a <text-input>, or (press) on a submit <pressable>'],
33
- ['wheel', '(scroll) on a <scroll-view>'],
34
- ...['mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'].map((name) => [
35
- name,
36
- 'a [gesture] from @ng-native/components',
37
- ]),
38
- ...['drag', 'dragstart', 'dragend', 'dragenter', 'dragleave', 'dragover', 'drop'].map((name) => [
39
- name,
40
- 'a pan [gesture] from @ng-native/components',
41
- ]),
42
- ...['copy', 'cut', 'paste'].map((name) => [name, '(changeText) on a <text-input>']),
43
- ]);
44
-
45
15
  /** HTML elements that draw as a plain view or text, without the behaviour they have in a browser. */
46
16
  const HTML_CONTROLS = new Map([
47
- ['button', '<pressable>'],
17
+ ['button', '<native-button>, or <pressable> for a look of your own'],
48
18
  [
49
19
  'a',
50
20
  '<text pressable (press)="...">, opening the link with DeepLinks.open from @ng-native/device',
@@ -163,31 +133,46 @@ const DOM_MEMBERS = new Map([
163
133
  ].map((name) => [name, 'a binding in the template: [class.name], [style.name] or an input']),
164
134
  ]);
165
135
 
136
+ const { DOM_EVENTS, DESKTOP_PLATFORMS, isNativeElement } = domEvents;
137
+
166
138
  /**
167
- * The elements from @ng-native/components whose names have a hyphen. An element without one is
168
- * HTML's or a primitive's; any other hyphenated one is a component, which may declare an output
169
- * called `drag` or `drop`, so its events are its own business.
139
+ * `expo.platforms` by `app.json` path, with the modification time and size it was read at, so an
140
+ * editor's long-lived process reads the file again when it changes.
170
141
  */
171
- const NATIVE_ELEMENTS = new Set([
172
- 'activity-indicator',
173
- 'gesture-root',
174
- 'gradient-text',
175
- 'image-background',
176
- 'input-accessory-view',
177
- 'keyboard-avoiding-view',
178
- 'keyboard-controller-view',
179
- 'keyboard-dock',
180
- 'keyboard-gesture-area',
181
- 'keyboard-motion-view',
182
- 'refresh-control',
183
- 'safe-area-provider',
184
- 'safe-area-view',
185
- 'scroll-view',
186
- 'section-list',
187
- 'text-input',
188
- 'touchable-opacity',
189
- 'virtual-list',
190
- ]);
142
+ const PLATFORMS = new Map();
143
+
144
+ /**
145
+ * Whether the project a file is in builds for a desktop OS: one the nearest `app.json` lists in
146
+ * `expo.platforms`. A project with no `app.json`, or none listed, builds for iOS and Android,
147
+ * Expo's default.
148
+ */
149
+ function buildsForDesktop(context) {
150
+ const filename = context.physicalFilename ?? context.filename;
151
+ return platformsAbove(dirname(filename)).some((os) => DESKTOP_PLATFORMS.has(os));
152
+ }
153
+
154
+ function platformsAbove(directory) {
155
+ const file = join(directory, 'app.json');
156
+ const stat = statSync(file, { throwIfNoEntry: false });
157
+ if (!stat) {
158
+ PLATFORMS.delete(file);
159
+ const parent = dirname(directory);
160
+ return parent === directory ? [] : platformsAbove(parent);
161
+ }
162
+ const cached = PLATFORMS.get(file);
163
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
164
+ return cached.platforms;
165
+ }
166
+ let platforms;
167
+ try {
168
+ platforms = JSON.parse(readFileSync(file, 'utf8'))?.expo?.platforms;
169
+ } catch {
170
+ platforms = undefined;
171
+ }
172
+ if (!Array.isArray(platforms)) platforms = [];
173
+ PLATFORMS.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, platforms });
174
+ return platforms;
175
+ }
191
176
 
192
177
  const DOCS = 'https://ng-native.com/packages/eslint-plugin';
193
178
 
@@ -221,6 +206,8 @@ const noDomEvents = {
221
206
  routerLink:
222
207
  'routerLink listens for a DOM click and never navigates on a device. Use nativeRouterLink from @ng-native/router, on a <pressable>.',
223
208
  event: '({{name}}) is a DOM event and never fires on a device. Use {{instead}}.',
209
+ desktop:
210
+ '({{name}}) fires only on macOS, and expo.platforms in app.json lists no desktop OS, so it never fires here. Use {{instead}}.',
224
211
  global:
225
212
  '({{target}}:{{name}}) never fires: there is no {{target}} on a device. Use @ng-native/device for app-wide events.',
226
213
  },
@@ -228,6 +215,7 @@ const noDomEvents = {
228
215
  },
229
216
  create(context) {
230
217
  if (isDomComponent(context)) return {};
218
+ const desktop = () => buildsForDesktop(context);
231
219
  /**
232
220
  * Report the event `name` on `target` (a global's name, or null for the element's own), with
233
221
  * `fixes` naming the replacement of an event a fix or a suggestion can rename.
@@ -239,9 +227,12 @@ const noDomEvents = {
239
227
  }
240
228
  // `(keydown.enter)` is the event `keydown` with a key filter.
241
229
  const event = name.split('.')[0];
242
- const instead = DOM_EVENTS.get(event);
243
- if (!instead) return;
244
- const report = { ...where, messageId: 'event', data: { name: event, instead } };
230
+ const known = DOM_EVENTS.get(event);
231
+ if (!known) return;
232
+ // One a desktop sends is `desktop-only-events`' where the project builds for one.
233
+ if (known.desktop && desktop()) return;
234
+ const messageId = known.desktop ? 'desktop' : 'event';
235
+ const report = { ...where, messageId, data: { name: event, instead: known.instead } };
245
236
  if (fixes.press) report.fix = fixes.press;
246
237
  if (fixes.changeText) report.suggest = [{ messageId: 'changeText', fix: fixes.changeText }];
247
238
  context.report(report);
@@ -253,8 +244,7 @@ const noDomEvents = {
253
244
  },
254
245
  BoundEvent(event) {
255
246
  const element = event.parent?.type === 'Element' ? event.parent : null;
256
- const native =
257
- element && (!element.name.includes('-') || NATIVE_ELEMENTS.has(element.name));
247
+ const native = element && isNativeElement(element.name);
258
248
  if (event.target || native) {
259
249
  const fixes = element ? renames(context, element, event) : {};
260
250
  check({ loc: spanLoc(event) }, event.target, event.name, fixes);
@@ -277,6 +267,54 @@ const noDomEvents = {
277
267
  },
278
268
  };
279
269
 
270
+ /** @type {import('eslint').Rule.RuleModule} */
271
+ const desktopOnlyEvents = {
272
+ meta: {
273
+ type: 'suggestion',
274
+ docs: {
275
+ description: 'Warn of a DOM event only a desktop OS sends, in a project that builds for one',
276
+ url: `${DOCS}#desktop-only-events`,
277
+ },
278
+ messages: {
279
+ event:
280
+ '({{name}}) fires only on macOS: iOS and Android never send it. Where it has to work there too, use {{instead}} as well.',
281
+ },
282
+ schema: [],
283
+ },
284
+ create(context) {
285
+ if (isDomComponent(context) || !buildsForDesktop(context)) return {};
286
+ const check = (where, name) => {
287
+ const event = name.split('.')[0];
288
+ const known = DOM_EVENTS.get(event);
289
+ if (!known?.desktop) return;
290
+ context.report({
291
+ ...where,
292
+ messageId: 'event',
293
+ data: { name: event, instead: known.instead },
294
+ });
295
+ };
296
+ return {
297
+ BoundEvent(event) {
298
+ const element = event.parent?.type === 'Element' ? event.parent : null;
299
+ if (!event.target && element && isNativeElement(element.name)) {
300
+ check({ loc: spanLoc(event) }, event.name);
301
+ }
302
+ },
303
+ 'Decorator > CallExpression > ObjectExpression > Property[key.name="host"] > ObjectExpression > Property'(
304
+ property,
305
+ ) {
306
+ const key = property.key.type === 'Literal' ? String(property.key.value) : '';
307
+ const listener = /^\(([^:)]+)\)$/.exec(key);
308
+ if (listener) check({ node: property.key }, listener[1]);
309
+ },
310
+ 'Decorator > CallExpression[callee.name="HostListener"] > Literal:first-child'(literal) {
311
+ const name = String(literal.value);
312
+ if (!name.includes(':')) check({ node: literal }, name);
313
+ },
314
+ };
315
+ },
316
+ };
317
+
280
318
  /** @type {import('eslint').Rule.RuleModule} */
281
319
  const noHtmlControls = {
282
320
  meta: {
@@ -474,6 +512,199 @@ const noDomNodeAccess = {
474
512
  },
475
513
  };
476
514
 
515
+ /**
516
+ * Whether `node` is read for its truth: the test of an `if`, a loop or a `?:`, the operand of `!`,
517
+ * the left operand of `&&` or `||`, which is tested, or the right one where the whole is itself a
518
+ * condition: `const shown = ready && x` keeps `x`'s value.
519
+ */
520
+ function readAsCondition(node) {
521
+ let at = node;
522
+ while (at.parent?.type === 'ChainExpression') at = at.parent;
523
+ const { parent } = at;
524
+ if (!parent) return false;
525
+ if (TESTED.has(parent.type)) return parent.test === at;
526
+ if (parent.type === 'UnaryExpression') return parent.operator === '!';
527
+ if (parent.type !== 'LogicalExpression') return false;
528
+ if (parent.operator !== '&&' && parent.operator !== '||') return false;
529
+ return parent.left === at || readAsCondition(parent);
530
+ }
531
+
532
+ /** What reads its `test` for its truth. */
533
+ const TESTED = new Set([
534
+ 'IfStatement',
535
+ 'WhileStatement',
536
+ 'DoWhileStatement',
537
+ 'ForStatement',
538
+ 'ConditionalExpression',
539
+ ]);
540
+
541
+ /** The variable `name` refers to from `scope`, or undefined for a global or a typo. */
542
+ function variableOf(scope, name) {
543
+ for (let at = scope; at; at = at.upper) {
544
+ const found = at.set.get(name);
545
+ if (found) return found;
546
+ }
547
+ return undefined;
548
+ }
549
+
550
+ /** Whether the name `identifier` reads is imported from an `@ng-native/` package. */
551
+ function isNgNativeImport(context, identifier) {
552
+ const variable = variableOf(context.sourceCode.getScope(identifier), identifier.name);
553
+ const [def] = variable?.defs ?? [];
554
+ return def?.type === 'ImportBinding' && String(def.parent.source.value).startsWith('@ng-native/');
555
+ }
556
+
557
+ /** Whether `node` is `inject(X)` for an `X` imported from `@ng-native/`. */
558
+ const isInjectedService = (context, node) =>
559
+ node?.type === 'CallExpression' &&
560
+ node.callee.type === 'Identifier' &&
561
+ node.callee.name === 'inject' &&
562
+ node.arguments[0]?.type === 'Identifier' &&
563
+ isNgNativeImport(context, node.arguments[0]);
564
+
565
+ /** Whether a declaration's type annotation names a type imported from `@ng-native/`. */
566
+ function typedAsService(context, annotation) {
567
+ const type = annotation?.typeAnnotation;
568
+ return (
569
+ type?.type === 'TSTypeReference' &&
570
+ type.typeName.type === 'Identifier' &&
571
+ isNgNativeImport(context, type.typeName)
572
+ );
573
+ }
574
+
575
+ /** Whether a class field or parameter property named `name` holds an `@ng-native/` service. */
576
+ function classHolds(context, body, name) {
577
+ for (const member of body.body) {
578
+ if (member.type === 'PropertyDefinition' && !member.computed && member.key.name === name) {
579
+ return (
580
+ isInjectedService(context, member.value) || typedAsService(context, member.typeAnnotation)
581
+ );
582
+ }
583
+ const held = member.kind === 'constructor' ? parameterProperty(member, name) : null;
584
+ if (held) return typedAsService(context, held.typeAnnotation);
585
+ }
586
+ return false;
587
+ }
588
+
589
+ /** The parameter property a constructor declares as `name`, if it declares one. */
590
+ function parameterProperty(constructor, name) {
591
+ for (const param of constructor.value.params) {
592
+ const held = param.type === 'TSParameterProperty' ? param.parameter : null;
593
+ if (held?.type === 'Identifier' && held.name === name) return held;
594
+ }
595
+ return null;
596
+ }
597
+
598
+ /** The class body `this` is the instance of at `node`, or null where a function binds its own. */
599
+ function thisClass(node) {
600
+ for (let at = node.parent; at; at = at.parent) {
601
+ if (at.type === 'ClassBody') return at;
602
+ const own = at.type === 'FunctionExpression' || at.type === 'FunctionDeclaration';
603
+ if (own && at.parent?.type !== 'MethodDefinition') return null;
604
+ }
605
+ return null;
606
+ }
607
+
608
+ /**
609
+ * Whether `receiver`, what `available` is read off, is known to be an `@ng-native/` service: an
610
+ * `inject()` of one, a name or a `this.` field initialised with one or typed as one, or a name
611
+ * imported from the package itself, such as `splashScreen`. Only then is a read reported: anything
612
+ * else named `available` may be a plain boolean, which a call would break.
613
+ */
614
+ function isService(context, receiver) {
615
+ if (isInjectedService(context, receiver)) return true;
616
+ if (receiver.type === 'Identifier') return nameHolds(context, receiver);
617
+ const field =
618
+ receiver.type === 'MemberExpression' &&
619
+ receiver.object.type === 'ThisExpression' &&
620
+ !receiver.computed &&
621
+ receiver.property.type === 'Identifier';
622
+ const body = field ? thisClass(receiver) : null;
623
+ return body !== null && classHolds(context, body, receiver.property.name);
624
+ }
625
+
626
+ /** Whether the name `identifier` reads is declared holding an `@ng-native/` service. */
627
+ function nameHolds(context, identifier) {
628
+ const variable = variableOf(context.sourceCode.getScope(identifier), identifier.name);
629
+ const [def] = variable?.defs ?? [];
630
+ switch (def?.type) {
631
+ case 'ImportBinding':
632
+ return isNgNativeImport(context, identifier);
633
+ case 'Variable':
634
+ return (
635
+ isInjectedService(context, def.node.init) ||
636
+ typedAsService(context, def.node.id.typeAnnotation)
637
+ );
638
+ case 'Parameter':
639
+ return def.name.type === 'Identifier' && typedAsService(context, def.name.typeAnnotation);
640
+ default:
641
+ return false;
642
+ }
643
+ }
644
+
645
+ /** @type {import('eslint').Rule.RuleModule} */
646
+ const noUncalledAvailable = {
647
+ meta: {
648
+ type: 'problem',
649
+ docs: {
650
+ description: "Disallow a service's available signal read as a condition without calling it",
651
+ url: `${DOCS}#no-uncalled-available`,
652
+ },
653
+ messages: {
654
+ uncalled: 'available is a signal, so it is always truthy. Call it: available().',
655
+ },
656
+ fixable: 'code',
657
+ schema: [],
658
+ },
659
+ create(context) {
660
+ return {
661
+ // Every service's `available` is a `Signal<boolean>`: a function, and so always truthy.
662
+ // ponytail: read from the syntax, not by type, so a service reached any other way, or a
663
+ // signal kept under another name, is not followed; that would need the type checker, which
664
+ // the recommended config does not set up.
665
+ 'MemberExpression[computed=false][property.name="available"]'(node) {
666
+ if (node.parent?.type === 'CallExpression' && node.parent.callee === node) return;
667
+ if (!readAsCondition(node) || !isService(context, node.object)) return;
668
+ context.report({
669
+ node: node.property,
670
+ messageId: 'uncalled',
671
+ fix: (fixer) => fixer.insertTextAfter(node, '()'),
672
+ });
673
+ },
674
+ };
675
+ },
676
+ };
677
+
678
+ /** @type {import('eslint').Rule.RuleModule} */
679
+ const preferHairlineToken = {
680
+ meta: {
681
+ type: 'suggestion',
682
+ docs: {
683
+ description:
684
+ 'Suggest the --hairline token over StyleSheet.hairlineWidth, which never updates',
685
+ url: `${DOCS}#prefer-hairline-token`,
686
+ },
687
+ messages: {
688
+ stale:
689
+ "StyleSheet.hairlineWidth is worked out once, at startup, so it keeps the first screen's " +
690
+ 'after a window moves to one of another density. Use var(--hairline) in a stylesheet, ' +
691
+ 'which watchConditions() keeps current.',
692
+ },
693
+ schema: [],
694
+ },
695
+ create(context) {
696
+ return {
697
+ // ponytail: read by name, as React Native's `StyleSheet` is usually imported under it; one
698
+ // renamed on import is not followed.
699
+ 'MemberExpression[computed=false][object.name="StyleSheet"][property.name="hairlineWidth"]'(
700
+ node,
701
+ ) {
702
+ context.report({ node, messageId: 'stale' });
703
+ },
704
+ };
705
+ },
706
+ };
707
+
477
708
  /** Report `window.document`, `globalThis.localStorage`, `window.addEventListener` and the like. */
478
709
  function checkWindowMember(context, identifier) {
479
710
  const member = identifier.parent;
@@ -525,10 +756,13 @@ const plugin = {
525
756
  meta: { name: '@ng-native/eslint-plugin' },
526
757
  rules: {
527
758
  'no-dom-events': noDomEvents,
759
+ 'desktop-only-events': desktopOnlyEvents,
528
760
  'no-html-controls': noHtmlControls,
529
761
  'no-browser-apis': noBrowserApis,
530
762
  'no-dom-node-access': noDomNodeAccess,
531
763
  'lowercase-elements': lowercaseElements,
764
+ 'no-uncalled-available': noUncalledAvailable,
765
+ 'prefer-hairline-token': preferHairlineToken,
532
766
  },
533
767
  };
534
768
 
@@ -548,7 +782,10 @@ const recommended = [
548
782
  rules: {
549
783
  '@ng-native/no-browser-apis': 'error',
550
784
  '@ng-native/no-dom-events': 'error',
785
+ '@ng-native/desktop-only-events': 'warn',
551
786
  '@ng-native/no-dom-node-access': 'error',
787
+ '@ng-native/no-uncalled-available': 'error',
788
+ '@ng-native/prefer-hairline-token': 'warn',
552
789
  },
553
790
  },
554
791
  {
@@ -558,6 +795,7 @@ const recommended = [
558
795
  plugins: { '@ng-native': plugin },
559
796
  rules: {
560
797
  '@ng-native/no-dom-events': 'error',
798
+ '@ng-native/desktop-only-events': 'warn',
561
799
  '@ng-native/no-html-controls': 'error',
562
800
  '@ng-native/lowercase-elements': 'error',
563
801
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ng-native/eslint-plugin",
3
- "version": "0.22.2",
3
+ "version": "0.23.0",
4
4
  "description": "ESLint rules for Angular Native: the DOM events, HTML controls and browser APIs that compile but do nothing on a device.",
5
5
  "keywords": [
6
6
  "angular",
@@ -16,6 +16,9 @@
16
16
  ".": "./index.mjs",
17
17
  "./package.json": "./package.json"
18
18
  },
19
+ "dependencies": {
20
+ "@ng-native/metro": "0.23.0"
21
+ },
19
22
  "peerDependencies": {
20
23
  "angular-eslint": "^22.0.0",
21
24
  "eslint": "^9.0.0 || ^10.0.0",