@markuplint/rules 4.6.1 → 4.8.0-alpha.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 (40) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/lib/index.d.ts +13 -11
  3. package/lib/index.js +4 -0
  4. package/lib/no-ambiguous-navigable-target-names/index.d.ts +2 -0
  5. package/lib/no-ambiguous-navigable-target-names/index.js +44 -0
  6. package/lib/no-ambiguous-navigable-target-names/meta.d.ts +4 -0
  7. package/lib/no-ambiguous-navigable-target-names/meta.js +3 -0
  8. package/lib/permitted-contents/choice.d.ts +1 -1
  9. package/lib/permitted-contents/choice.js +2 -2
  10. package/lib/permitted-contents/complex-branch.d.ts +2 -2
  11. package/lib/permitted-contents/complex-branch.js +5 -5
  12. package/lib/permitted-contents/count-pattern.d.ts +2 -2
  13. package/lib/permitted-contents/count-pattern.js +3 -3
  14. package/lib/permitted-contents/index.js +9 -3
  15. package/lib/permitted-contents/matches-selector.d.ts +1 -1
  16. package/lib/permitted-contents/matches-selector.js +21 -21
  17. package/lib/permitted-contents/order.d.ts +2 -2
  18. package/lib/permitted-contents/order.js +3 -3
  19. package/lib/permitted-contents/recursive-branch.d.ts +1 -1
  20. package/lib/permitted-contents/recursive-branch.js +4 -4
  21. package/lib/permitted-contents/represent-transparent-nodes.d.ts +3 -1
  22. package/lib/permitted-contents/represent-transparent-nodes.js +73 -52
  23. package/lib/permitted-contents/start.js +49 -43
  24. package/lib/permitted-contents/transparent.d.ts +1 -1
  25. package/lib/permitted-contents/transparent.js +6 -6
  26. package/lib/permitted-contents/types.d.ts +4 -0
  27. package/lib/permitted-contents/utils.d.ts +2 -3
  28. package/lib/permitted-contents/utils.js +0 -14
  29. package/lib/table-row-column-alignment/find-children.d.ts +2 -0
  30. package/lib/table-row-column-alignment/find-children.js +13 -0
  31. package/lib/table-row-column-alignment/grid.d.ts +22 -0
  32. package/lib/table-row-column-alignment/grid.js +186 -0
  33. package/lib/table-row-column-alignment/index.d.ts +2 -0
  34. package/lib/table-row-column-alignment/index.js +73 -0
  35. package/lib/table-row-column-alignment/meta.d.ts +4 -0
  36. package/lib/table-row-column-alignment/meta.js +3 -0
  37. package/lib/table-row-column-alignment/types.d.ts +2 -0
  38. package/lib/table-row-column-alignment/types.js +1 -0
  39. package/package.json +9 -9
  40. package/schema.json +6 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # [4.8.0-alpha.0](https://github.com/markuplint/markuplint/compare/@markuplint/rules@4.7.0...@markuplint/rules@4.8.0-alpha.0) (2024-05-04)
7
+
8
+ ### Features
9
+
10
+ - **rules:** add `no-ambiguous-navigable-target-names` rule ([742db4e](https://github.com/markuplint/markuplint/commit/742db4eb98b8f27e8a1f6a82d3b6541871e02a5c))
11
+ - **rules:** add `table-row-column-alignment` rule ([4b071f8](https://github.com/markuplint/markuplint/commit/4b071f8d7dae0f1500e1a77046b289489eb5a598))
12
+ - **rules:** apply `no-ambiguous-navigable-target-names` to build-in rules ([93d34f0](https://github.com/markuplint/markuplint/commit/93d34f0ead2624107a5b6f315af0c8bbd4f1e1ec))
13
+ - **rules:** apply `table-row-column-alignment` to build-in rules ([85de609](https://github.com/markuplint/markuplint/commit/85de6098813cd7c3167099f9e7e6250ca8324539))
package/lib/index.d.ts CHANGED
@@ -16,13 +16,7 @@ declare const rules: {
16
16
  readonly 'id-duplication': Readonly<import("@markuplint/ml-core").RuleSeed<import("@markuplint/ml-core").RuleConfigValue, undefined>>;
17
17
  readonly 'ineffective-attr': Readonly<import("@markuplint/ml-core").RuleSeed<import("@markuplint/ml-core").RuleConfigValue, undefined>>;
18
18
  readonly 'invalid-attr': Readonly<import("@markuplint/ml-core").RuleSeed<boolean, {
19
- allowAttrs?: Record<string, {
20
- enum: [string, ...string[]];
21
- } | {
22
- pattern: string;
23
- } | {
24
- type: import("packages/@markuplint/ml-spec/lib/index.js").AttributeType;
25
- }> | (string | {
19
+ allowAttrs?: (string | {
26
20
  name: string;
27
21
  value: import("packages/@markuplint/ml-spec/lib/index.js").AttributeType | ({
28
22
  enum: [string, ...string[]];
@@ -31,14 +25,14 @@ declare const rules: {
31
25
  } | {
32
26
  type: import("packages/@markuplint/ml-spec/lib/index.js").AttributeType;
33
27
  });
34
- })[] | undefined;
35
- disallowAttrs?: Record<string, {
28
+ })[] | Record<string, {
36
29
  enum: [string, ...string[]];
37
30
  } | {
38
31
  pattern: string;
39
32
  } | {
40
33
  type: import("packages/@markuplint/ml-spec/lib/index.js").AttributeType;
41
- }> | (string | {
34
+ }> | undefined;
35
+ disallowAttrs?: (string | {
42
36
  name: string;
43
37
  value: import("packages/@markuplint/ml-spec/lib/index.js").AttributeType | ({
44
38
  enum: [string, ...string[]];
@@ -47,7 +41,13 @@ declare const rules: {
47
41
  } | {
48
42
  type: import("packages/@markuplint/ml-spec/lib/index.js").AttributeType;
49
43
  });
50
- })[] | undefined;
44
+ })[] | Record<string, {
45
+ enum: [string, ...string[]];
46
+ } | {
47
+ pattern: string;
48
+ } | {
49
+ type: import("packages/@markuplint/ml-spec/lib/index.js").AttributeType;
50
+ }> | undefined;
51
51
  ignoreAttrNamePrefix?: string | string[] | undefined;
52
52
  allowToAddPropertiesForPretender?: boolean | undefined;
53
53
  attrs?: Record<string, ({
@@ -66,6 +66,7 @@ declare const rules: {
66
66
  labelEachArea: boolean;
67
67
  }>>;
68
68
  readonly 'neighbor-popovers': Readonly<import("@markuplint/ml-core").RuleSeed<import("@markuplint/ml-core").RuleConfigValue, undefined>>;
69
+ readonly 'no-ambiguous-navigable-target-names': Readonly<import("@markuplint/ml-core").RuleSeed<boolean, undefined>>;
69
70
  readonly 'no-boolean-attr-value': Readonly<import("@markuplint/ml-core").RuleSeed<import("@markuplint/ml-core").RuleConfigValue, undefined>>;
70
71
  readonly 'no-consecutive-br': Readonly<import("@markuplint/ml-core").RuleSeed<import("@markuplint/ml-core").RuleConfigValue, undefined>>;
71
72
  readonly 'no-default-value': Readonly<import("@markuplint/ml-core").RuleSeed<import("@markuplint/ml-core").RuleConfigValue, undefined>>;
@@ -99,6 +100,7 @@ declare const rules: {
99
100
  ignoreHasMutableContents: boolean;
100
101
  }>>;
101
102
  readonly 'required-h1': Readonly<import("@markuplint/ml-core").RuleSeed<boolean, import("./required-h1/index.js").Options>>;
103
+ readonly 'table-row-column-alignment': Readonly<import("@markuplint/ml-core").RuleSeed<boolean, undefined>>;
102
104
  readonly 'use-list': Readonly<import("@markuplint/ml-core").RuleSeed<readonly string[], {
103
105
  spaceNeededBullets?: string[] | undefined;
104
106
  noPrev?: boolean | undefined;
package/lib/index.js CHANGED
@@ -16,6 +16,7 @@ import InvalidAttr from './invalid-attr/index.js';
16
16
  import LabelHasControl from './label-has-control/index.js';
17
17
  import LandmarkRoles from './landmark-roles/index.js';
18
18
  import NeighborPopovers from './neighbor-popovers/index.js';
19
+ import NoAmbiguousNavigableTargetNames from './no-ambiguous-navigable-target-names/index.js';
19
20
  import NoBooleanAttrValue from './no-boolean-attr-value/index.js';
20
21
  import NoConsecutiveBr from './no-consecutive-br/index.js';
21
22
  import NoDefaultValue from './no-default-value/index.js';
@@ -32,6 +33,7 @@ import RequireDatetime from './require-datetime/index.js';
32
33
  import RequiredAttr from './required-attr/index.js';
33
34
  import RequiredElement from './required-element/index.js';
34
35
  import RequiredH1 from './required-h1/index.js';
36
+ import TableRowColumnAlignment from './table-row-column-alignment/index.js';
35
37
  import UseList from './use-list/index.js';
36
38
  import WaiAria from './wai-aria/index.js';
37
39
  const rules = {
@@ -53,6 +55,7 @@ const rules = {
53
55
  'label-has-control': LabelHasControl,
54
56
  'landmark-roles': LandmarkRoles,
55
57
  'neighbor-popovers': NeighborPopovers,
58
+ 'no-ambiguous-navigable-target-names': NoAmbiguousNavigableTargetNames,
56
59
  'no-boolean-attr-value': NoBooleanAttrValue,
57
60
  'no-consecutive-br': NoConsecutiveBr,
58
61
  'no-default-value': NoDefaultValue,
@@ -69,6 +72,7 @@ const rules = {
69
72
  'required-attr': RequiredAttr,
70
73
  'required-element': RequiredElement,
71
74
  'required-h1': RequiredH1,
75
+ 'table-row-column-alignment': TableRowColumnAlignment,
72
76
  'use-list': UseList,
73
77
  'wai-aria': WaiAria,
74
78
  };
@@ -0,0 +1,2 @@
1
+ declare const _default: Readonly<import("@markuplint/ml-core").RuleSeed<boolean, undefined>>;
2
+ export default _default;
@@ -0,0 +1,44 @@
1
+ import { createRule, getAttrSpecs } from '@markuplint/ml-core';
2
+ import { valueCheck } from '../attr-check.js';
3
+ import meta from './meta.js';
4
+ export default createRule({
5
+ meta: meta,
6
+ defaultSeverity: 'warning',
7
+ async verify({ document, report, t }) {
8
+ await document.walkOn('Attr', attr => {
9
+ if (!attr.valueNode) {
10
+ return;
11
+ }
12
+ const attrSpecs = getAttrSpecs(attr.ownerElement, document.specs);
13
+ if (!attrSpecs) {
14
+ return;
15
+ }
16
+ const attrSpec = attrSpecs.find(spec => spec.name === attr.name);
17
+ if (attrSpec?.type !== 'NavigableTargetNameOrKeyword' && attrSpec?.type !== 'NavigableTargetName') {
18
+ return;
19
+ }
20
+ const value = attr.value.trim();
21
+ if (value.startsWith('_')) {
22
+ // This is a keyword
23
+ return;
24
+ }
25
+ const valueWithUnderscore = `_${value}`;
26
+ const invalid = valueCheck(t, attr.name, valueWithUnderscore, 'NavigableTargetNameOrKeyword');
27
+ if (invalid !== false) {
28
+ return;
29
+ }
30
+ report({
31
+ scope: attr,
32
+ line: attr.valueNode.startLine,
33
+ col: attr.valueNode.startCol,
34
+ raw: attr.valueNode.raw,
35
+ message:
36
+ //
37
+ t("don't use {0}", t('a {0}', t('ambiguous {0}', 'navigable target name'))) +
38
+ (attrSpec.type === 'NavigableTargetNameOrKeyword'
39
+ ? t('. ') + t('Did you mean "{0}"?', valueWithUnderscore)
40
+ : ''),
41
+ });
42
+ });
43
+ },
44
+ });
@@ -0,0 +1,4 @@
1
+ declare const _default: {
2
+ readonly category: "a11y";
3
+ };
4
+ export default _default;
@@ -0,0 +1,3 @@
1
+ export default {
2
+ category: 'a11y',
3
+ };
@@ -1,4 +1,4 @@
1
1
  import type { ChildNode, Options, Result, Specs } from './types.js';
2
2
  import type { PermittedContentChoice } from '@markuplint/ml-spec';
3
3
  import type { ReadonlyDeep } from 'type-fest';
4
- export declare function choice(pattern: ReadonlyDeep<PermittedContentChoice>, elements: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
4
+ export declare function choice(pattern: ReadonlyDeep<PermittedContentChoice>, childNodes: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
@@ -4,9 +4,9 @@ import { Collection, modelLog } from './utils.js';
4
4
  const indexes = new WeakMap();
5
5
  export function choice(pattern,
6
6
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
7
- elements, specs, options, depth) {
7
+ childNodes, specs, options, depth) {
8
8
  const choiceLog = cmLog.extend(`choice#${depth}`);
9
- const collection = new Collection(elements);
9
+ const collection = new Collection(childNodes);
10
10
  const unmatchedResults = [];
11
11
  let i = 0;
12
12
  for (const some of pattern.choice) {
@@ -5,10 +5,10 @@ import type { ReadonlyDeep } from 'type-fest';
5
5
  * Check content condition
6
6
  *
7
7
  * @param pattern
8
- * @param elements
8
+ * @param childNodes
9
9
  * @param specs
10
10
  * @param options
11
11
  * @param depth
12
12
  * @returns
13
13
  */
14
- export declare function complexBranch(pattern: ReadonlyDeep<PermittedContentPattern>, elements: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
14
+ export declare function complexBranch(pattern: ReadonlyDeep<PermittedContentPattern>, childNodes: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
@@ -6,7 +6,7 @@ import { isChoice, isTransparent } from './utils.js';
6
6
  * Check content condition
7
7
  *
8
8
  * @param pattern
9
- * @param elements
9
+ * @param childNodes
10
10
  * @param specs
11
11
  * @param options
12
12
  * @param depth
@@ -14,12 +14,12 @@ import { isChoice, isTransparent } from './utils.js';
14
14
  */
15
15
  export function complexBranch(pattern,
16
16
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
17
- elements, specs, options, depth) {
17
+ childNodes, specs, options, depth) {
18
18
  if (isChoice(pattern)) {
19
- return choice(pattern, elements, specs, options, depth);
19
+ return choice(pattern, childNodes, specs, options, depth);
20
20
  }
21
21
  if (isTransparent(pattern)) {
22
- return transparent(elements);
22
+ return transparent(childNodes);
23
23
  }
24
- return countPattern(pattern, elements, specs, options, depth);
24
+ return countPattern(pattern, childNodes, specs, options, depth);
25
25
  }
@@ -5,10 +5,10 @@ import type { ReadonlyDeep } from 'type-fest';
5
5
  * Check count
6
6
  *
7
7
  * @param pattern
8
- * @param elements
8
+ * @param childNodes
9
9
  * @param specs
10
10
  * @param options
11
11
  * @param depth
12
12
  * @returns
13
13
  */
14
- export declare function countPattern(pattern: ReadonlyDeep<PermittedContentOneOrMore> | ReadonlyDeep<PermittedContentOptional> | ReadonlyDeep<PermittedContentRequire> | ReadonlyDeep<PermittedContentZeroOrMore>, elements: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
14
+ export declare function countPattern(pattern: ReadonlyDeep<PermittedContentOneOrMore> | ReadonlyDeep<PermittedContentOptional> | ReadonlyDeep<PermittedContentRequire> | ReadonlyDeep<PermittedContentZeroOrMore>, childNodes: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
@@ -6,7 +6,7 @@ const cLog = cmLog.extend('countCompereResult');
6
6
  * Check count
7
7
  *
8
8
  * @param pattern
9
- * @param elements
9
+ * @param childNodes
10
10
  * @param specs
11
11
  * @param options
12
12
  * @param depth
@@ -14,9 +14,9 @@ const cLog = cmLog.extend('countCompereResult');
14
14
  */
15
15
  export function countPattern(pattern,
16
16
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
17
- elements, specs, options, depth) {
17
+ childNodes, specs, options, depth) {
18
18
  const ptLog = cmLog.extend(`countPattern#${depth}`);
19
- const collection = new Collection(elements);
19
+ const collection = new Collection(childNodes);
20
20
  const { model, min, max, repeat, missingType } = normalizeModel(pattern);
21
21
  ptLog('Model:\n RegEx: %s\n Schema: %o', modelLog(model, repeat), pattern);
22
22
  let prevResult = null;
@@ -7,12 +7,10 @@ export default createRule({
7
7
  defaultValue: [],
8
8
  defaultOptions: {
9
9
  ignoreHasMutableChildren: true,
10
+ evaluateConditionalChildNodes: false,
10
11
  },
11
12
  async verify({ document, report, t }) {
12
13
  await document.walkOn('Element', el => {
13
- if (el.rule.options.ignoreHasMutableChildren && el.hasMutableChildren()) {
14
- return;
15
- }
16
14
  const results = contentModel(el, el.rule.value, el.rule.options);
17
15
  for (const { type, scope, query, hint } of results) {
18
16
  let message = '';
@@ -28,6 +26,10 @@ export default createRule({
28
26
  break;
29
27
  }
30
28
  case 'MISSING_NODE_ONE_OR_MORE': {
29
+ if (scope.rule.options.ignoreHasMutableChildren &&
30
+ (!scope.is(scope.ELEMENT_NODE) || scope.hasMutableChildren())) {
31
+ break;
32
+ }
31
33
  message =
32
34
  message ||
33
35
  t('Require {0}', t('one or more elements')) + t('. ') + '(' + t('Need "{0*}"', query) + ')';
@@ -38,6 +40,10 @@ export default createRule({
38
40
  break;
39
41
  }
40
42
  case 'MISSING_NODE_REQUIRED': {
43
+ if (scope.rule.options.ignoreHasMutableChildren &&
44
+ (!scope.is(scope.ELEMENT_NODE) || scope.hasMutableChildren())) {
45
+ break;
46
+ }
41
47
  message =
42
48
  message ||
43
49
  t('Require {0}', t('an {0}', 'element')) + t('. ') + '(' + t('Need "{0*}"', query) + ')';
@@ -1,3 +1,3 @@
1
1
  import type { ChildNode, Result, Specs } from './types.js';
2
2
  export type SelectorResult = Result<'UNMATCHED_SELECTOR_BUT_MAY_EMPTY' | 'MISSING_NODE' | 'UNMATCHED_SELECTORS'>;
3
- export declare function matchesSelector(query: string, node: ChildNode | undefined, specs: Specs, depth: number): SelectorResult;
3
+ export declare function matchesSelector(query: string, childNode: ChildNode | undefined, specs: Specs, depth: number): SelectorResult;
@@ -3,10 +3,10 @@ import { cmLog } from './debug.js';
3
3
  import { cleanObject, matches } from './utils.js';
4
4
  export function matchesSelector(query,
5
5
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
6
- node, specs, depth) {
6
+ childNode, specs, depth) {
7
7
  const nodeLog = cmLog.extend(`node#${depth}`);
8
8
  const { selector, hasText, hasCustom } = optCondition(query, specs);
9
- if (node == null) {
9
+ if (childNode == null) {
10
10
  if (hasText) {
11
11
  nodeLog('<#text>.matches(%s) => ""', query);
12
12
  return {
@@ -27,23 +27,23 @@ node, specs, depth) {
27
27
  hint: {},
28
28
  };
29
29
  }
30
- if (node.is(node.TEXT_NODE)) {
30
+ if (childNode.is(childNode.TEXT_NODE)) {
31
31
  if (hasText) {
32
- nodeLog('<#text>.matches(%s) => "%s"', query, node.raw.trim());
32
+ nodeLog('<#text>.matches(%s) => "%s"', query, childNode.raw.trim());
33
33
  return {
34
34
  type: 'MATCHED',
35
- matched: [node],
35
+ matched: [childNode],
36
36
  unmatched: [],
37
37
  zeroMatch: true,
38
38
  query,
39
39
  hint: {},
40
40
  };
41
41
  }
42
- if (node.isWhitespace()) {
42
+ if (childNode.isWhitespace()) {
43
43
  nodeLog('<#text>.matches(%s) => WHITESPACE', query);
44
44
  return {
45
45
  type: 'MATCHED',
46
- matched: [node],
46
+ matched: [childNode],
47
47
  unmatched: [],
48
48
  zeroMatch: true,
49
49
  query,
@@ -54,41 +54,41 @@ node, specs, depth) {
54
54
  return {
55
55
  type: 'UNEXPECTED_EXTRA_NODE',
56
56
  matched: [],
57
- unmatched: [node],
57
+ unmatched: [childNode],
58
58
  zeroMatch: false,
59
59
  query,
60
60
  hint: {},
61
61
  };
62
62
  }
63
- if (node.is(node.MARKUPLINT_PREPROCESSOR_BLOCK)) {
64
- nodeLog('%s.matches(%s) => PBlock', node.raw, query);
63
+ if (childNode.is(childNode.MARKUPLINT_PREPROCESSOR_BLOCK)) {
64
+ nodeLog('%s.matches(%s) => PBlock', childNode.raw, query);
65
65
  return {
66
66
  type: 'MATCHED',
67
- matched: [node],
67
+ matched: [childNode],
68
68
  unmatched: [],
69
69
  zeroMatch: !!hasText,
70
70
  query,
71
71
  hint: {},
72
72
  };
73
73
  }
74
- if (node.is(node.ELEMENT_NODE)) {
75
- if (node.elementType !== 'html' && hasCustom) {
76
- nodeLog('%s.matches(%s) => CustomElement', node.raw, query);
74
+ if (childNode.is(childNode.ELEMENT_NODE)) {
75
+ if (childNode.elementType !== 'html' && hasCustom) {
76
+ nodeLog('%s.matches(%s) => CustomElement', childNode.raw, query);
77
77
  return {
78
78
  type: 'MATCHED',
79
- matched: [node],
79
+ matched: [childNode],
80
80
  unmatched: [],
81
81
  zeroMatch: !!hasText,
82
82
  query,
83
83
  hint: {},
84
84
  };
85
85
  }
86
- const result = matches(selector, node, specs);
87
- nodeLog('%s.matches(%s) => %s', node.raw, query, result.matched);
86
+ const result = matches(selector, childNode, specs);
87
+ nodeLog('%s.matches(%s) => %s', childNode.raw, query, result.matched);
88
88
  if (result.matched) {
89
89
  return {
90
90
  type: 'MATCHED',
91
- matched: [node],
91
+ matched: [childNode],
92
92
  unmatched: [],
93
93
  zeroMatch: !!hasText,
94
94
  query,
@@ -99,7 +99,7 @@ node, specs, depth) {
99
99
  return {
100
100
  type: 'UNMATCHED_SELECTOR_BUT_MAY_EMPTY',
101
101
  matched: [],
102
- unmatched: [node],
102
+ unmatched: [childNode],
103
103
  zeroMatch: true,
104
104
  query,
105
105
  hint: cleanObject({
@@ -110,7 +110,7 @@ node, specs, depth) {
110
110
  return {
111
111
  type: 'UNMATCHED_SELECTORS',
112
112
  matched: [],
113
- unmatched: [node],
113
+ unmatched: [childNode],
114
114
  zeroMatch: false,
115
115
  query,
116
116
  hint: cleanObject({
@@ -120,7 +120,7 @@ node, specs, depth) {
120
120
  }
121
121
  return {
122
122
  type: 'MATCHED',
123
- matched: [node],
123
+ matched: [childNode],
124
124
  unmatched: [],
125
125
  zeroMatch: !!hasText,
126
126
  query,
@@ -5,10 +5,10 @@ import type { ReadonlyDeep } from 'type-fest';
5
5
  * Check ordered array
6
6
  *
7
7
  * @param contents
8
- * @param nodes
8
+ * @param childNodes
9
9
  * @param specs
10
10
  * @param options
11
11
  * @param depth
12
12
  * @returns
13
13
  */
14
- export declare function order(contents: ReadonlyDeep<PermittedContentPattern[]>, nodes: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
14
+ export declare function order(contents: ReadonlyDeep<PermittedContentPattern[]>, childNodes: readonly ChildNode[], specs: Specs, options: Options, depth: number): Result;
@@ -6,7 +6,7 @@ import { Collection, mergeHints, modelLog } from './utils.js';
6
6
  * Check ordered array
7
7
  *
8
8
  * @param contents
9
- * @param nodes
9
+ * @param childNodes
10
10
  * @param specs
11
11
  * @param options
12
12
  * @param depth
@@ -14,11 +14,11 @@ import { Collection, mergeHints, modelLog } from './utils.js';
14
14
  */
15
15
  export function order(contents,
16
16
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
17
- nodes, specs, options, depth) {
17
+ childNodes, specs, options, depth) {
18
18
  const orderLog = cmLog.extend(`order#${depth}`);
19
19
  const btLog = cmLog.extend(`backtrack#${depth}`);
20
20
  const patterns = deepCopy(contents);
21
- const collection = new Collection(nodes);
21
+ const collection = new Collection(childNodes);
22
22
  orderLog('Model:\n RegEx: %s\n Schema: %o', modelLog(patterns, ''), patterns);
23
23
  orderLog('Starts: %s', collection);
24
24
  let result = undefined;
@@ -2,4 +2,4 @@ import type { SelectorResult } from './matches-selector.js';
2
2
  import type { ChildNode, Options, Specs } from './types.js';
3
3
  import type { PermittedContentPattern, Model } from '@markuplint/ml-spec';
4
4
  import type { ReadonlyDeep } from 'type-fest';
5
- export declare function recursiveBranch(model: ReadonlyDeep<Model | PermittedContentPattern[]>, nodes: readonly ChildNode[], specs: Specs, options: Options, depth: number): SelectorResult;
5
+ export declare function recursiveBranch(model: ReadonlyDeep<Model | PermittedContentPattern[]>, childNodes: readonly ChildNode[], specs: Specs, options: Options, depth: number): SelectorResult;
@@ -3,14 +3,14 @@ import { order } from './order.js';
3
3
  import { Collection, isModel } from './utils.js';
4
4
  export function recursiveBranch(model,
5
5
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
6
- nodes, specs, options, depth) {
6
+ childNodes, specs, options, depth) {
7
7
  if (!isModel(model)) {
8
- return order(model, nodes, specs, options, depth + 1);
8
+ return order(model, childNodes, specs, options, depth + 1);
9
9
  }
10
10
  if (typeof model === 'string') {
11
- return matchesSelector(model, nodes[0], specs, depth);
11
+ return matchesSelector(model, childNodes[0], specs, depth);
12
12
  }
13
- const collection = new Collection(nodes);
13
+ const collection = new Collection(childNodes);
14
14
  let lastUnmatched = null;
15
15
  for (const query of model) {
16
16
  const result = matchesSelector(query, collection.unmatched[0], specs, depth);
@@ -1,6 +1,8 @@
1
1
  import type { ChildNode, Options, Result, Specs } from './types.js';
2
2
  export declare const transparentMode: Map<ChildNode, true>;
3
- export declare function representTransparentNodes(nodes: ChildNode[], specs: Specs, options: Options): {
3
+ type TransparentNode = {
4
4
  nodes: ChildNode[];
5
5
  errors: Result[];
6
6
  };
7
+ export declare function representTransparentNodes(childNodes: readonly ChildNode[], specs: Specs, options: Options): TransparentNode[];
8
+ export {};
@@ -1,73 +1,94 @@
1
1
  import { getContentModel } from '@markuplint/ml-spec';
2
+ import { branchesToPatterns } from '@markuplint/shared';
2
3
  import { order } from './order.js';
3
- import { Collection, getChildNodesWithoutWhitespaces, isTransparent, matches } from './utils.js';
4
+ import { Collection, isTransparent, matches } from './utils.js';
4
5
  export const transparentMode = new Map();
5
6
  export function representTransparentNodes(
6
7
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
7
- nodes, specs, options) {
8
- const result = [];
9
- const errors = [];
10
- const parent = nodes[0]?.parentElement;
11
- if (parent) {
12
- const { errors: parentErrors } = representTransparentNodes([parent], specs, options);
13
- errors.push(...parentErrors);
14
- }
15
- for (const node of nodes) {
16
- if (!node.is(node.ELEMENT_NODE)) {
17
- result.push(node);
8
+ childNodes, specs, options) {
9
+ const parentElement = childNodes[0]?.parentElement;
10
+ const parentResults = parentElement
11
+ ? representTransparentNodes([parentElement], specs, options)
12
+ : [{ nodes: [], errors: [] }];
13
+ const branches = [];
14
+ for (const childNode of childNodes) {
15
+ if (!childNode.is(childNode.ELEMENT_NODE)) {
16
+ branches.push(childNode);
18
17
  continue;
19
18
  }
20
- const models = getContentModel(node, specs.specs);
19
+ const models = getContentModel(childNode, specs.specs);
21
20
  if (models == null || typeof models === 'boolean') {
22
- result.push(node);
21
+ branches.push(childNode);
23
22
  continue;
24
23
  }
25
24
  const noTransparentModels = models.filter(m => !isTransparent(m));
26
25
  if (noTransparentModels.length === models.length) {
27
- result.push(node);
26
+ branches.push(childNode);
28
27
  continue;
29
28
  }
30
- const collection = new Collection(getChildNodesWithoutWhitespaces(node));
31
- let unmatched;
32
- if (noTransparentModels.length > 0) {
33
- const result = order(noTransparentModels, collection.unmatched, specs, options, Number.POSITIVE_INFINITY);
34
- unmatched = result.unmatched;
35
- }
36
- else {
37
- unmatched = collection.unmatched;
38
- }
39
- const transparent = models.find(m => isTransparent(m));
40
- if (!transparent || !isTransparent(transparent)) {
41
- throw new Error('Unreachable code');
42
- }
43
- for (const _child of unmatched) {
44
- const child = _child;
45
- if (transparentMode.has(child)) {
46
- continue;
29
+ const childNodesPatterns = options.evaluateConditionalChildNodes
30
+ ? childNode.conditionalChildNodes().map(childNodes => [...childNodes])
31
+ : [[...childNode.childNodes].filter(child => !(child.is(child.TEXT_NODE) && child.isWhitespace()))];
32
+ const representPattern = [];
33
+ for (const childNodes of childNodesPatterns) {
34
+ const collection = new Collection([...childNodes]);
35
+ let unmatched;
36
+ if (noTransparentModels.length > 0) {
37
+ const result = order(noTransparentModels, collection.unmatched, specs, options, Number.POSITIVE_INFINITY);
38
+ unmatched = result.unmatched;
47
39
  }
48
- transparentMode.set(child, true);
49
- if (child.is(child.ELEMENT_NODE)) {
50
- const transparentCondMatched = matches(transparent.transparent, child, specs);
51
- if (!transparentCondMatched.matched) {
52
- errors.push({
53
- type: 'TRANSPARENT_MODEL_DISALLOWS',
54
- matched: [],
55
- unmatched: [node],
56
- zeroMatch: false,
57
- query: transparent.transparent,
58
- hint: {
59
- not: transparentCondMatched.not,
60
- transparent: node,
61
- },
62
- });
40
+ else {
41
+ unmatched = collection.unmatched;
42
+ }
43
+ const transparent = models.find(m => isTransparent(m));
44
+ if (!transparent || !isTransparent(transparent)) {
45
+ throw new Error('Unreachable code');
46
+ }
47
+ for (const _child of unmatched) {
48
+ const child = _child;
49
+ if (transparentMode.has(child)) {
63
50
  continue;
64
51
  }
52
+ transparentMode.set(child, true);
53
+ if (child.is(child.ELEMENT_NODE)) {
54
+ const transparentCondMatched = matches(transparent.transparent, child, specs);
55
+ if (!transparentCondMatched.matched) {
56
+ representPattern.push({
57
+ type: 'TRANSPARENT_MODEL_DISALLOWS',
58
+ matched: [],
59
+ unmatched: [childNode],
60
+ zeroMatch: false,
61
+ query: transparent.transparent,
62
+ hint: {
63
+ not: transparentCondMatched.not,
64
+ transparent: childNode,
65
+ },
66
+ });
67
+ continue;
68
+ }
69
+ }
70
+ representPattern.push(child);
65
71
  }
66
- result.push(child);
67
72
  }
73
+ branches.push(representPattern);
68
74
  }
69
- return {
70
- nodes: result,
71
- errors,
72
- };
75
+ const patterns = branchesToPatterns(branches);
76
+ const result = parentResults.flatMap(parentResult => {
77
+ const patternResults = patterns.map(pattern => {
78
+ const nodes = pattern.filter((node) => 'nodeName' in node);
79
+ const errors = pattern.filter((node) => 'type' in node);
80
+ return {
81
+ nodes,
82
+ errors: [...parentResult.errors, ...errors],
83
+ };
84
+ });
85
+ if (patternResults.length === 0) {
86
+ return {
87
+ nodes: [],
88
+ errors: parentResult.errors,
89
+ };
90
+ }
91
+ return patternResults;
92
+ });
93
+ return result;
73
94
  }
@@ -1,6 +1,5 @@
1
1
  import { order } from './order.js';
2
2
  import { representTransparentNodes } from './represent-transparent-nodes.js';
3
- import { getChildNodesWithoutWhitespaces } from './utils.js';
4
3
  /**
5
4
  * Check start
6
5
  *
@@ -13,53 +12,60 @@ import { getChildNodesWithoutWhitespaces } from './utils.js';
13
12
  export function start(contents,
14
13
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
15
14
  el, specs, options) {
16
- if (contents === false) {
17
- if (el.childNodes.length > 0) {
15
+ const childNodesPatterns = options.evaluateConditionalChildNodes
16
+ ? el.conditionalChildNodes().map(childNodes => [...childNodes])
17
+ : [[...el.childNodes].filter(child => !(child.is(child.TEXT_NODE) && child.isWhitespace()))];
18
+ return childNodesPatterns.flatMap(childNodes => {
19
+ if (contents === false) {
20
+ if (childNodes.length > 0) {
21
+ return [
22
+ {
23
+ type: 'NOTHING',
24
+ scope: el,
25
+ query: ':not(*)',
26
+ hint: {},
27
+ },
28
+ ];
29
+ }
18
30
  return [
19
31
  {
20
- type: 'NOTHING',
32
+ type: 'MATCHED',
21
33
  scope: el,
22
- query: ':not(*)',
34
+ query: '*',
23
35
  hint: {},
24
36
  },
25
37
  ];
26
38
  }
27
- return [
28
- {
29
- type: 'MATCHED',
30
- scope: el,
31
- query: '*',
32
- hint: {},
33
- },
34
- ];
35
- }
36
- if (contents === true) {
37
- // Allows all elements
38
- return [
39
- {
40
- type: 'MATCHED',
41
- scope: el,
42
- query: '*',
43
- hint: {},
44
- },
45
- ];
46
- }
47
- const { nodes, errors } = representTransparentNodes(getChildNodesWithoutWhitespaces(el), specs, options);
48
- const result = order(contents, nodes, specs, options, 0);
49
- return [
50
- {
51
- type: result.type,
52
- scope: result.type === 'MISSING_NODE_REQUIRED' || result.type === 'MISSING_NODE_ONE_OR_MORE'
53
- ? el
54
- : result.unmatched[0] ?? el,
55
- query: result.query,
56
- hint: result.hint,
57
- },
58
- ...errors.map(error => ({
59
- type: error.type,
60
- scope: error.unmatched[0] ?? el,
61
- query: error.query,
62
- hint: error.hint,
63
- })),
64
- ];
39
+ if (contents === true) {
40
+ // Allows all elements
41
+ return [
42
+ {
43
+ type: 'MATCHED',
44
+ scope: el,
45
+ query: '*',
46
+ hint: {},
47
+ },
48
+ ];
49
+ }
50
+ const patterns = representTransparentNodes(childNodes, specs, options);
51
+ return patterns.flatMap(({ nodes, errors }) => {
52
+ const result = order(contents, nodes, specs, options, 0);
53
+ return [
54
+ {
55
+ type: result.type,
56
+ scope: result.type === 'MISSING_NODE_REQUIRED' || result.type === 'MISSING_NODE_ONE_OR_MORE'
57
+ ? el
58
+ : result.unmatched[0] ?? el,
59
+ query: result.query,
60
+ hint: result.hint,
61
+ },
62
+ ...errors.map(error => ({
63
+ type: error.type,
64
+ scope: error.unmatched[0] ?? el,
65
+ query: error.query,
66
+ hint: error.hint,
67
+ })),
68
+ ];
69
+ });
70
+ });
65
71
  }
@@ -1,2 +1,2 @@
1
1
  import type { ChildNode, Result } from './types.js';
2
- export declare function transparent(nodes: readonly ChildNode[]): Result;
2
+ export declare function transparent(childNodes: readonly ChildNode[]): Result;
@@ -2,14 +2,14 @@ import { cmLog } from './debug.js';
2
2
  const transparentLog = cmLog.extend('transparent');
3
3
  export function transparent(
4
4
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
5
- nodes) {
6
- if (nodes.length === 0 || nodes[0]?.parentElement?.parentElement) {
5
+ childNodes) {
6
+ if (childNodes.length === 0 || childNodes[0]?.parentElement?.parentElement) {
7
7
  transparentLog('Skipped');
8
8
  return {
9
- type: nodes.length === 0 ? 'MATCHED_ZERO' : 'MATCHED',
10
- matched: [...nodes],
9
+ type: childNodes.length === 0 ? 'MATCHED_ZERO' : 'MATCHED',
10
+ matched: [...childNodes],
11
11
  unmatched: [],
12
- zeroMatch: nodes.length === 0,
12
+ zeroMatch: childNodes.length === 0,
13
13
  query: 'transparent',
14
14
  hint: {},
15
15
  };
@@ -17,7 +17,7 @@ nodes) {
17
17
  transparentLog('Transparent model element is component root');
18
18
  return {
19
19
  type: 'MATCHED',
20
- matched: [...nodes],
20
+ matched: [...childNodes],
21
21
  unmatched: [],
22
22
  zeroMatch: false,
23
23
  query: 'transparent',
@@ -49,4 +49,8 @@ export type TagRule = {
49
49
  } & ReadonlyDeep<ContentModel>;
50
50
  export type Options = {
51
51
  readonly ignoreHasMutableChildren: boolean;
52
+ /**
53
+ * @experimental
54
+ */
55
+ readonly evaluateConditionalChildNodes: boolean;
52
56
  };
@@ -1,7 +1,6 @@
1
- import type { ChildNode, Element, Hints, MissingNodeReason, RepeatSign, Specs } from './types.js';
1
+ import type { ChildNode, Hints, MissingNodeReason, RepeatSign, Specs } from './types.js';
2
2
  import type { PermittedContentPattern, PermittedContentChoice, PermittedContentOneOrMore, PermittedContentOptional, PermittedContentRequire, PermittedContentTransparent, PermittedContentZeroOrMore, Model } from '@markuplint/ml-spec';
3
3
  import type { ReadonlyDeep } from 'type-fest';
4
- export declare function getChildNodesWithoutWhitespaces(el: Element): ChildNode[];
5
4
  export declare function isModel(model: ReadonlyDeep<Model | PermittedContentPattern[]>): model is ReadonlyDeep<Model>;
6
5
  export declare function matches(selector: string, node: ChildNode, specs: Specs): {
7
6
  matched: boolean;
@@ -30,7 +29,7 @@ export declare function mergeHints(a: Readonly<Hints>, b: Readonly<Hints>): Part
30
29
  }> | undefined;
31
30
  max?: number | undefined;
32
31
  not?: ChildNode | undefined;
33
- transparent?: Element | undefined;
32
+ transparent?: import("./types.js").Element | undefined;
34
33
  }>;
35
34
  export declare function cleanObject<T extends Object>(object: T): Partial<T>;
36
35
  export declare class Collection {
@@ -13,20 +13,6 @@ var _Collection_locked, _Collection_matched, _Collection_nodes, _Collection_orig
13
13
  import { createSelector } from '@markuplint/selector';
14
14
  import { bgGreen, green, bgRed, bgBlue, blue, bgMagenta, cyan } from './debug.js';
15
15
  import { transparentMode } from './represent-transparent-nodes.js';
16
- const getChildNodesWithoutWhitespacesCaches = new Map();
17
- export function getChildNodesWithoutWhitespaces(
18
- // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
19
- el) {
20
- let nodes = getChildNodesWithoutWhitespacesCaches.get(el);
21
- if (nodes) {
22
- return nodes;
23
- }
24
- nodes = [...el.childNodes].filter(node => {
25
- return !(node.is(node.TEXT_NODE) && node.isWhitespace());
26
- });
27
- getChildNodesWithoutWhitespacesCaches.set(el, nodes);
28
- return nodes;
29
- }
30
16
  export function isModel(model) {
31
17
  if (typeof model === 'string') {
32
18
  return true;
@@ -0,0 +1,2 @@
1
+ import type { Element } from '@markuplint/ml-core';
2
+ export declare function findChildren(el: Element<boolean>, selector: string): Element<boolean, undefined>[];
@@ -0,0 +1,13 @@
1
+ const findCache = {};
2
+ export function findChildren(
3
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
4
+ el, selector) {
5
+ const key = `${el.uuid}:${selector}`;
6
+ const cached = findCache[key];
7
+ if (cached) {
8
+ return cached;
9
+ }
10
+ const children = [...el.children].filter(child => child.matches(selector));
11
+ findCache[key] = children;
12
+ return children;
13
+ }
@@ -0,0 +1,22 @@
1
+ import type { CellType } from './types.js';
2
+ import type { Element } from '@markuplint/ml-core';
3
+ export declare class Grid {
4
+ #private;
5
+ readonly tbodyGrid: ReadonlyArray<ReadonlyArray<CellType>>;
6
+ readonly tfootGrid: ReadonlyArray<ReadonlyArray<CellType>>;
7
+ readonly theadGrid: ReadonlyArray<ReadonlyArray<CellType>>;
8
+ constructor(table: Element<boolean>);
9
+ getAllRowElements(): Element<boolean, undefined>[];
10
+ getAllRows(): (readonly CellType[])[];
11
+ getBaseColLength(): number;
12
+ getSections(): {
13
+ section: readonly (readonly CellType[])[];
14
+ elements: readonly Element<boolean, undefined>[];
15
+ }[];
16
+ hasOverlapped(): boolean;
17
+ log(): void;
18
+ }
19
+ export declare function getOverflowRowSpan(rows: ReadonlyArray<ReadonlyArray<CellType>>, rowElements: ReadonlyArray<Element<boolean>>): {
20
+ rowSpan: import("@markuplint/ml-core").Attr<boolean, undefined>;
21
+ } | null;
22
+ export declare function getIndexes(row: readonly CellType[]): (number | null)[];
@@ -0,0 +1,186 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _Grid_tbodyRowElements, _Grid_tfootRowElements, _Grid_theadRowElements;
13
+ import { findChildren } from './find-children.js';
14
+ export class Grid {
15
+ constructor(
16
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
17
+ table) {
18
+ _Grid_tbodyRowElements.set(this, void 0);
19
+ _Grid_tfootRowElements.set(this, void 0);
20
+ _Grid_theadRowElements.set(this, void 0);
21
+ const thead = findChildren(table, 'thead')[0];
22
+ const tbody = findChildren(table, 'tbody')[0];
23
+ const tfoot = findChildren(table, 'tfoot')[0];
24
+ __classPrivateFieldSet(this, _Grid_theadRowElements, thead ? findChildren(thead, 'tr') : [], "f");
25
+ __classPrivateFieldSet(this, _Grid_tbodyRowElements, tbody ? findChildren(tbody, 'tr') : [], "f");
26
+ __classPrivateFieldSet(this, _Grid_tfootRowElements, tfoot ? findChildren(tfoot, 'tr') : [], "f");
27
+ this.theadGrid = createGrid(__classPrivateFieldGet(this, _Grid_theadRowElements, "f"));
28
+ this.tbodyGrid = createGrid(__classPrivateFieldGet(this, _Grid_tbodyRowElements, "f"));
29
+ this.tfootGrid = createGrid(__classPrivateFieldGet(this, _Grid_tfootRowElements, "f"));
30
+ }
31
+ getAllRowElements() {
32
+ return [...__classPrivateFieldGet(this, _Grid_theadRowElements, "f"), ...__classPrivateFieldGet(this, _Grid_tbodyRowElements, "f"), ...__classPrivateFieldGet(this, _Grid_tfootRowElements, "f")];
33
+ }
34
+ getAllRows() {
35
+ return [
36
+ ...this.theadGrid.filter(hasElementFilter),
37
+ ...this.tbodyGrid.filter(hasElementFilter),
38
+ ...this.tfootGrid.filter(hasElementFilter),
39
+ ];
40
+ }
41
+ getBaseColLength() {
42
+ if (this.theadGrid.length > 0) {
43
+ return getBaseColLength(this.theadGrid);
44
+ }
45
+ if (this.tfootGrid.length > 0) {
46
+ return getBaseColLength(this.tfootGrid);
47
+ }
48
+ return getBaseColLength(this.tbodyGrid);
49
+ }
50
+ getSections() {
51
+ return [
52
+ {
53
+ section: this.theadGrid,
54
+ elements: __classPrivateFieldGet(this, _Grid_theadRowElements, "f"),
55
+ },
56
+ {
57
+ section: this.tbodyGrid,
58
+ elements: __classPrivateFieldGet(this, _Grid_tbodyRowElements, "f"),
59
+ },
60
+ {
61
+ section: this.tfootGrid,
62
+ elements: __classPrivateFieldGet(this, _Grid_tfootRowElements, "f"),
63
+ },
64
+ ];
65
+ }
66
+ hasOverlapped() {
67
+ return (this.tbodyGrid.some(row => row.includes('x')) ||
68
+ this.tfootGrid.some(row => row.includes('x')) ||
69
+ this.theadGrid.some(row => row.includes('x')));
70
+ }
71
+ log() {
72
+ // eslint-disable-next-line no-console
73
+ console.table(this.theadGrid);
74
+ // eslint-disable-next-line no-console
75
+ console.table(this.tbodyGrid);
76
+ // eslint-disable-next-line no-console
77
+ console.table(this.tfootGrid);
78
+ }
79
+ }
80
+ _Grid_tbodyRowElements = new WeakMap(), _Grid_tfootRowElements = new WeakMap(), _Grid_theadRowElements = new WeakMap();
81
+ export function getOverflowRowSpan(rows,
82
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
83
+ rowElements) {
84
+ for (const [rowNum] of rows.entries()) {
85
+ const rowEl = rowElements[rowNum];
86
+ if (!rowEl) {
87
+ const prevRow = rows[rowNum - 1];
88
+ const prevRowEl = rowElements[rowNum - 1];
89
+ if (!prevRow || !prevRowEl) {
90
+ continue;
91
+ }
92
+ const spanStart = prevRow.indexOf('◎');
93
+ if (spanStart === -1) {
94
+ continue;
95
+ }
96
+ const indexes = getIndexes(prevRow);
97
+ const index = indexes[spanStart];
98
+ if (index == null) {
99
+ continue;
100
+ }
101
+ const cells = findChildren(prevRowEl, 'th, td');
102
+ const spanStartCell = cells[index];
103
+ if (!spanStartCell) {
104
+ continue;
105
+ }
106
+ const rowSpan = spanStartCell.getAttributeNode('rowspan');
107
+ if (!rowSpan) {
108
+ continue;
109
+ }
110
+ return {
111
+ rowSpan,
112
+ };
113
+ }
114
+ }
115
+ return null;
116
+ }
117
+ export function getIndexes(row) {
118
+ let indexCounter = 0;
119
+ return row.map(col => (col === '●' || col === '◎' ? indexCounter++ : null));
120
+ }
121
+ function getBaseColLength(grid) {
122
+ let baseColLength;
123
+ if (grid.length >= 3) {
124
+ const totalCols = grid.reduce((acc, row) => {
125
+ return acc + row.length;
126
+ }, 0);
127
+ const average = Math.round(totalCols / grid.length);
128
+ baseColLength = grid
129
+ // eslint-disable-next-line unicorn/no-array-reduce
130
+ .reduce((closest, row) => {
131
+ return Math.abs(row.length - average) < Math.abs(closest - average) ? row.length : closest;
132
+ }, grid[0]?.length ?? 0);
133
+ }
134
+ else {
135
+ baseColLength = grid[0]?.length ?? 0;
136
+ }
137
+ return baseColLength;
138
+ }
139
+ function createGrid(
140
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
141
+ rows) {
142
+ const rowSpans = new Set();
143
+ const matrix = [];
144
+ for (const [rowNum, row] of rows.entries()) {
145
+ const cols = findChildren(row, 'th, td');
146
+ let colNum = 0;
147
+ matrix[rowNum] = matrix[rowNum] ?? [];
148
+ for (const col of cols) {
149
+ const colSpan = Number.parseInt(col.getAttribute('colspan') ?? '1');
150
+ const rowSpan = Number.parseInt(col.getAttribute('rowspan') ?? '1');
151
+ for (let i = 0; i < colSpan; i++) {
152
+ const key = `${rowNum}:${colNum}`;
153
+ let spanStart = false;
154
+ if (colSpan > 1 && i === 0) {
155
+ spanStart = true;
156
+ }
157
+ if (rowSpan > 1) {
158
+ if (i === 0) {
159
+ spanStart = true;
160
+ }
161
+ for (let i = 1; i <= rowSpan - 1; i++) {
162
+ matrix[rowNum + i] = matrix[rowNum + i] ?? [];
163
+ matrix[rowNum + i][colNum] = '↓';
164
+ rowSpans.add(`${rowNum + i}:${colNum}`);
165
+ }
166
+ }
167
+ const addCol = rowSpans.has(key) ? 1 : 0;
168
+ if (matrix[rowNum]?.[colNum] === '↓' && !spanStart && colSpan > 1) {
169
+ // Overlap
170
+ matrix[rowNum][colNum] = 'x';
171
+ }
172
+ else {
173
+ matrix[rowNum][colNum] = spanStart ? '◎' : addCol > 0 ? '↓' : colSpan > 1 ? '→' : '●';
174
+ }
175
+ if (addCol === 1) {
176
+ matrix[rowNum].push('●');
177
+ }
178
+ colNum += 1;
179
+ }
180
+ }
181
+ }
182
+ return matrix;
183
+ }
184
+ function hasElementFilter(row) {
185
+ return row.some(cell => cell === '●' || cell === '◎');
186
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: Readonly<import("@markuplint/ml-core").RuleSeed<boolean, undefined>>;
2
+ export default _default;
@@ -0,0 +1,73 @@
1
+ import { createRule } from '@markuplint/ml-core';
2
+ import { findChildren } from './find-children.js';
3
+ import { Grid, getIndexes, getOverflowRowSpan } from './grid.js';
4
+ import meta from './meta.js';
5
+ export default createRule({
6
+ meta,
7
+ defaultSeverity: 'warning',
8
+ verify({ document, report, t }) {
9
+ const tables = document.querySelectorAll('table');
10
+ for (const table of tables) {
11
+ const grid = new Grid(table);
12
+ const baseColLength = grid.getBaseColLength();
13
+ // grid.log();
14
+ if (grid.hasOverlapped()) {
15
+ report({
16
+ scope: table,
17
+ message: t(
18
+ //
19
+ '{0} are causing {1}', t(['rowspan', 'colspan'], true), 'cell overlap'),
20
+ });
21
+ break;
22
+ }
23
+ for (const { section, elements } of grid.getSections()) {
24
+ const overflow = getOverflowRowSpan(section, elements);
25
+ if (overflow) {
26
+ report({
27
+ scope: overflow.rowSpan,
28
+ message: t('Exceeds the number of available {0}', 'rows'),
29
+ });
30
+ }
31
+ }
32
+ const rows = grid.getAllRows();
33
+ const rowElements = grid.getAllRowElements();
34
+ for (const [rowNum, row] of rows.entries()) {
35
+ const colLength = row.length;
36
+ const rowEl = rowElements[rowNum];
37
+ if (!rowEl) {
38
+ continue;
39
+ }
40
+ const indexes = getIndexes(row);
41
+ if (colLength > baseColLength) {
42
+ const index = indexes.slice(baseColLength)[0];
43
+ const cells = findChildren(rowEl, 'th, td');
44
+ const unexpected = typeof index === 'number' ? cells[index] : null;
45
+ if (!unexpected) {
46
+ const spanStart = cells.findLast(cell => Number.parseInt(cell.getAttribute('colspan') ?? '1') > 1);
47
+ const colSpan = spanStart?.getAttributeNode('colspan');
48
+ if (!colSpan) {
49
+ continue;
50
+ }
51
+ report({
52
+ scope: colSpan,
53
+ message: t('Exceeds the number of available {0}', 'columns'),
54
+ });
55
+ continue;
56
+ }
57
+ const diff = colLength - baseColLength;
58
+ report({
59
+ scope: unexpected,
60
+ message: t('{0} extra {1} in {2}', t(`${diff}`), t(diff === 1 ? 'column' : 'columns'), t('a {0}', t('row'))),
61
+ });
62
+ }
63
+ if (colLength < baseColLength) {
64
+ const diff = baseColLength - colLength;
65
+ report({
66
+ scope: rowEl,
67
+ message: t('{0} missing {1} in {2}', t(`${diff}`), t(diff === 1 ? 'column' : 'columns'), t('a {0}', t('row'))),
68
+ });
69
+ }
70
+ }
71
+ }
72
+ },
73
+ });
@@ -0,0 +1,4 @@
1
+ declare const _default: {
2
+ readonly category: "a11y";
3
+ };
4
+ export default _default;
@@ -0,0 +1,3 @@
1
+ export default {
2
+ category: 'a11y',
3
+ };
@@ -0,0 +1,2 @@
1
+ export type Key = `${number}:${number}`;
2
+ export type CellType = '●' | '◎' | '↓' | '→' | 'x';
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markuplint/rules",
3
- "version": "4.6.1",
3
+ "version": "4.8.0-alpha.0",
4
4
  "description": "Built-in rules of markuplint",
5
5
  "repository": "git@github.com:markuplint/markuplint.git",
6
6
  "author": "Yusuke Hirao <yusukehirao@me.com>",
@@ -25,18 +25,18 @@
25
25
  "./lib/permitted-contents/debug.js": "./lib/permitted-contents/debug.browser.js"
26
26
  },
27
27
  "dependencies": {
28
- "@markuplint/html-spec": "4.6.1",
29
- "@markuplint/ml-core": "4.6.1",
30
- "@markuplint/ml-spec": "4.4.1",
31
- "@markuplint/selector": "4.5.1",
32
- "@markuplint/shared": "4.2.0",
33
- "@markuplint/types": "4.3.0",
28
+ "@markuplint/html-spec": "4.7.1-alpha.0",
29
+ "@markuplint/ml-core": "4.7.1-alpha.0",
30
+ "@markuplint/ml-spec": "4.5.1-alpha.0",
31
+ "@markuplint/selector": "4.6.1-alpha.0",
32
+ "@markuplint/shared": "4.3.1-alpha.0",
33
+ "@markuplint/types": "4.4.1-alpha.0",
34
34
  "@types/debug": "4.1.12",
35
35
  "@ungap/structured-clone": "1.2.0",
36
36
  "ansi-colors": "4.1.3",
37
37
  "chrono-node": "2.7.5",
38
38
  "debug": "4.3.4",
39
- "type-fest": "4.15.0"
39
+ "type-fest": "4.18.1"
40
40
  },
41
- "gitHead": "b029c86a6b3a9ea8189d2e5535e3023aaea753fd"
41
+ "gitHead": "d091e2199e3dc6757c2c8edbf01fd19e8b072015"
42
42
  }
package/schema.json CHANGED
@@ -60,6 +60,9 @@
60
60
  "neighbor-popovers": {
61
61
  "$ref": "https://raw.githubusercontent.com/markuplint/markuplint/main/packages/%40markuplint/rules/src/neighbor-popovers/schema.json"
62
62
  },
63
+ "no-ambiguous-navigable-target-names": {
64
+ "$ref": "https://raw.githubusercontent.com/markuplint/markuplint/main/packages/%40markuplint/rules/src/no-ambiguous-navigable-target-names/schema.json"
65
+ },
63
66
  "no-boolean-attr-value": {
64
67
  "$ref": "https://raw.githubusercontent.com/markuplint/markuplint/main/packages/%40markuplint/rules/src/no-boolean-attr-value/schema.json"
65
68
  },
@@ -108,6 +111,9 @@
108
111
  "required-h1": {
109
112
  "$ref": "https://raw.githubusercontent.com/markuplint/markuplint/main/packages/%40markuplint/rules/src/required-h1/schema.json"
110
113
  },
114
+ "table-row-column-alignment": {
115
+ "$ref": "https://raw.githubusercontent.com/markuplint/markuplint/main/packages/%40markuplint/rules/src/table-row-column-alignment/schema.json"
116
+ },
111
117
  "use-list": {
112
118
  "$ref": "https://raw.githubusercontent.com/markuplint/markuplint/main/packages/%40markuplint/rules/src/use-list/schema.json"
113
119
  },