Skip to content

perf: format - #7949

Closed
shaohuzhang1 wants to merge 1 commit into
v3from
pr@v3@feat_format
Closed

shaohuzhang1 wants to merge 1 commit into
v3from
pr@v3@feat_format

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

perf: format

},
}
},
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Findings

Potential Issues / Bugs

  1. replaceAll('\\', '/') compatibility — String.prototype.replaceAll requires Node ≥ 15 / modern runtimes. If this ESLint plugin targets older environments, use .split('\\').join('/') or a global regex. Depends on your engine range.

  2. Duplicate import merging semantics — When splitting a mixed type/value declaration into two, the reported fix replaces only the import block range. But if two original declarations for the same source existed (e.g., one value + one type), you emit two separate import statements that remain adjacent but not merged. That's fine for correctness, but be aware duplicate specifiers across type/value imports of the same module are preserved, which no-duplicate-imports (or its includeExports) may flag elsewhere.

  3. Length estimate in renderImport is approximate.

    const length = prefix.length + [...bindings, singleLine].join(', ').length + code.getText(node.source).length + 6

    The + 6 magic number assumes from (6 chars) plus spaces; and the node.source text uses original quote style. This can misdecide multiline vs single-line near the boundary. Consider computing the actual rendered string first, then deciding:

    const candidate = `${prefix}${[...bindings, singleLine].join(', ')} from ${code.getText(node.source)}`
    bindings.push(candidate.length > 150 ? `{\n...\n}` : singleLine)

    Also the 150 threshold hardcodes Prettier's printWidth rather than reading config; acceptable if documented, but brittle if .prettierrc changes.

  4. types.includes(specifier) — O(n²) but harmless for small specifier lists; using a Set would be marginally cleaner.

  5. node.importKind === 'type' || specifier.importKind === 'type' — Correct, but note groupOf's isType handling: for a mixed declaration you split into two entries where groupOf(..., true, ...) always returns group 1. Meaning all type-only imports go to group 1 regardless of source category. Likely intentional (types grouped separately) — confirm it matches your ordering rules.

  6. inlineTypesOnly detection is incomplete. A declaration like import { type A, B } where B is a value has every(... importKind === 'type') false — correct, untouched. But a declaration with zero specifiers (side-effect import, e.g. import './styles.css') is excluded by the !node.specifiers.length guard — good (comment mentions styles). OK.

  7. gap.trim() used as "don't cross boundaries" check — Comments attached between imports via blank lines break blocks; also any whitespace-only gap clears the block, so imports separated by blank lines are never reordered relative to each other. That may be stricter than desired; if users expect sorting across blank-line-separated groups, this silently disables it. Document this behavior or make it configurable.

  8. previous recomputed within loop — block.at(-1) is read before possibly resetting block; fine since gap uses the pre-reset previous. But logic flow is subtle: after check(block); block = [], the same node is then pushed at the end if valid. Verify that when leadingComment is true, node is correctly excluded from all blocks (it is, since push is guarded by !leadingComment).

  9. No context.filename fallback — context.filename was added in ESLint 8.40 (replacing context.getFilename()). Fine if that's your minimum ESLint, otherwise add fallback.

  10. Report location nodes[0] — Reports on the first import, but fixes whole block. Acceptable; consider reporting at the mismatched entry for clearer UX, or loc: { start: nodes[0].range[0], end: ... }.

  11. Missing meta.docs / meta.hasSuggestions — Meta lacks docs (url/description/recommended) — optional but conventional.

  12. Chinese message / English everything else — Minor consistency nit.

Optimization Suggestions

  • Replace chained regex tests in groupOf with URL-prefix checks where possible; regexes like /(?:@\/|\/src\/)api\/enums(?:\/|\.|$)/ will also match @/api/enums-old? No — the (?:\/|\.|$) guards prevent that. Good. But they're evaluated per import; caching by source could help on large files.
  • path.resolve + replaceAll per external-looking source is only invoked for non-. sources — actually resolved computes for all sources including bare packages, calling path.resolve needlessly. Since resolved is only used in the two api regexes meant for project paths, you can skip resolution for bare module specifiers (not starting with . or @/). Minor perf win.
  • entries.sort comparator covers groups 0 and 4 specially; note group 4 also falls through to compare(source) after the @/ rank, correct. For group 0 (frameworks), after rank comparison, non-framework packages sort alphabetically — verify you don't want framework sub-path imports (e.g. vue/dist/..., unlikely) grouped with their package; online includes exact match means vue-router ranks in the array while vue-something goes to alphabetical fallback. Fine but worth noting.

Summary

Logic is generally sound and carefully guards comment/side-effect cases. Main actionable items: (a) make the width decision based on actual rendered string instead of the +6 heuristic, (b) confirm context.filename/replaceAll match your supported runtime, (c) consider surfacing the blank-line boundary behavior in docs, (d) minor cleanups (Set, docs, locale consistency).

import { createPortalConversation } from './index'

const applicationSelectorRef = ref<InstanceType<typeof SelectApplicationDrawer>>()
const bundle = createPortalConversation({ openApplicationSelector: () => applicationSelectorRef.value?.open() })

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the diff

Overall this change is purely cosmetic — it reorganizes imports (alphabetical ordering within groups, grouping symbols from the same module). No functional behavior changes are introduced. Below are observations and minor concerns.

1. Risk in reordering imports (side effects)

  • import { createPortalConversation } from './index' was moved to the bottom, together with the other local ../ imports. If ./index performs side-effectful module initialization (e.g., registering components/globals) and previously ran earlier, the relative order among value imports could matter. Verify ./index has no top-level side effects that depend on prior imports.
  • The Vue import was alphabetized (computed, onBeforeUnmount, onMounted, provide, ref, watch). Harmless, but note that some linters/formatters expect specific member ordering (Vue's own style guide doesn't enforce this, so it's fine — just confirm your ESLint config agrees, otherwise it will be reverted on the next lint run).

2. Inconsistent toggling of "alphabetical" rule

  • @/api/enums is now before @/api/chat/file. A pure alphabetical sort would put @/api/chat/file first. This suggests mixed sorting rules (path-length vs. lexical). Pick one convention to avoid churn between contributors/linters.

3. Import grouping breaks logical cohesion

  • Primitives (ref) are now removed from the first line's leading position, but more importantly: matching the KEY injection tokens next to their corresponding component imports would improve readability:
    import ConversationList, { CONVERSATION_LIST_KEY } from '...'
    Consider combining named + default imports from the same module into a single statement where possible, e.g.:
    import PortalConversationList, { PORTAL_CONVERSATION_LIST_KEY } from '../../left-sidebar/portal-conversation-list/index.vue'
    (Only valid if the .vue file actually re-exports the key; if the key comes from a sibling .ts, keep them separate — but then at least place them adjacently.)

4. Unused / verify usage

  • Confirm all newly grouped imports are still referenced downstream. In particular, SHARE_LINK_KEY, PROFILE_KEY, RIGHT_SIDEBAR_KEY etc. must each be passed into a provide(...) call below this snippet — nothing here shows usage, so double-check you didn't accidentally drop a reference when reshuffling.

5. Extension inconsistency

  • ../index.ts still carries an explicit .ts extension while other local imports omit it ('./index'). This inconsistency existed before but is worth normalizing since the diff touches this block.

6. Optimization / maintainability suggestions

  • Reduce token proliferation: Six+ injected KEY constants imported at page level hint at a large provide/inject surface. Consider consolidating into a single typed injection container object to reduce import noise and coupling.
  • Barrel/strict path aliases: Paths like ../../components/message-list/share/index are deep and brittle. Prefer alias-based imports (e.g. @/views/...) or index barrels to shorten and stabilize them.
  • Type-only imports: Use import type { AxiosProgressEvent } already done — good. Ensure any other type-only symbols use import type too for tree-shaking clarity.

7. Minor

  • const applicationSelectorRef = ref<InstanceType<typeof SelectApplicationDrawer>>() — prefer ref<SelectApplicationDrawer | null>(null) (or VueInstance) patterns; current form works but is verbose and implicitly starts as undefined. Not introduced by this diff, just noting.

Verdict

No functional bugs introduced by this diff. Main actionable items: (a) confirm import-order has no side-effect dependency, (b) align sorting convention with your lint config to prevent future churn, and (c) consider consolidating the many injection-key imports for long-term maintainability.

import { isSystemResource } from '@/utils/resource-context'

/**
* debug 模式:装配各组件 store。adapter 走 admin(带 applicationId)。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here are my observations on the diff:

1. Missing type modifier on a type-only import

The original had import { computed, type Ref } from 'vue'. The new version splits this into:

  • import { computed } from 'vue'
  • import type { Ref } from 'vue'

That's fine functionally, but two points:

  • Ref is not used in the visible part of the file. If it is used further down (unchanged context), then importing it as import type { Ref } from 'vue' is correct and actually an improvement via verbatimModuleSyntax/tree-shaking. Otherwise, it's an unused import — remove it.
  • Similarly, verify computed is actually used; it was kept, so presumably yes.

2. Import reordering changes side-effect ordering

The imports were reordered visually (grouped/alphabetized by different rules). This matters only if any imported module has side effects at import time (e.g., registering Vue plugins, mutating globals, polyfills). Specifically:

  • SystemResourceConversationApi / WorkspaceConversationApi — API modules, usually side-effect-free, fine.
  • useStore (@/stores), isSystemResource — typically pure, fine.
  • createConversationListStore, createMessageListStore, etc. — factory modules; confirm they don't register anything at module-eval time.

If nothing has side effects, reordering is purely cosmetic. If ESLint simple-import-sort / import/order is configured, ensure the new order matches the lint rules, otherwise you'll get lint errors.

3. Type-only imports scattered among value imports

You now have import type { ... } interleaved with value imports (import type { ConversationBundle }, import type { ApplicationDetail }, import type { Ref } sitting between value imports). This is legal but stylistically inconsistent. Most projects prefer either:

  • all type imports grouped together (separate block), or
  • inline import { type X, value } form.

Pick one convention to match the codebase/lint config.

4. import type { ConversationBundle } moved position

Was near the bottom, now near the top. No issue, just note consistency with #3.

5. Duplicate-ish imports from same package

@/api/types is imported once (ApplicationDetail) — fine. But watch for other files combining import type { ApplicationDetail } and likely other types from @/api/types elsewhere; consider consolidating per-file.

6. Unchanged surrounding hunks

The diff header (@@ -1,19 +1,20 @@) shows line count changed 19→20 (one extra line due to splitting the Vue import). No logical change shown beyond imports — the docstring is intact.

7. Recommendation summary

  • Confirm Ref and computed are both used; remove Ref if not.
  • Verify no module has import-time side effects before reordering.
  • Align import ordering with your ESLint import/order / simple-import-sort config.
  • Adopt a consistent policy for where import type lines live (grouped vs. inline).
  • Consider enabling verbatimModuleSyntax and @typescript-eslint/consistent-type-imports to auto-enforce this pattern.

No functional bugs are introduced by this diff as-is, assuming the imports are all used and side-effect-free.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants