Repository navigation
perf: format - #7949
perf: format#7949shaohuzhang1 wants to merge 1 commit into
Conversation
| }, | ||
| } | ||
| }, | ||
| } |
There was a problem hiding this comment.
Review Findings
Potential Issues / Bugs
-
replaceAll('\\', '/')compatibility —String.prototype.replaceAllrequires Node ≥ 15 / modern runtimes. If this ESLint plugin targets older environments, use.split('\\').join('/')or a global regex. Depends on your engine range. -
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 itsincludeExports) may flag elsewhere. -
Length estimate in
renderImportis approximate.const length = prefix.length + [...bindings, singleLine].join(', ').length + code.getText(node.source).length + 6
The
+ 6magic number assumesfrom(6 chars) plus spaces; and thenode.sourcetext 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
150threshold hardcodes Prettier'sprintWidthrather than reading config; acceptable if documented, but brittle if.prettierrcchanges. -
types.includes(specifier)— O(n²) but harmless for small specifier lists; using aSetwould be marginally cleaner. -
node.importKind === 'type' || specifier.importKind === 'type'— Correct, but note groupOf'sisTypehandling: for a mixed declaration you split into two entries wheregroupOf(..., 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. -
inlineTypesOnlydetection is incomplete. A declaration likeimport { type A, B }whereBis a value hasevery(... 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.lengthguard — good (comment mentions styles). OK. -
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. -
previousrecomputed within loop —block.at(-1)is read before possibly resettingblock; fine sincegapuses the pre-resetprevious. But logic flow is subtle: aftercheck(block); block = [], the same node is then pushed at the end if valid. Verify that whenleadingCommentis true, node is correctly excluded from all blocks (it is, since push is guarded by!leadingComment). -
No
context.filenamefallback —context.filenamewas added in ESLint 8.40 (replacingcontext.getFilename()). Fine if that's your minimum ESLint, otherwise add fallback. -
Report location
nodes[0]— Reports on the first import, but fixes whole block. Acceptable; consider reporting at the mismatched entry for clearer UX, orloc: { start: nodes[0].range[0], end: ... }. -
Missing
meta.docs/meta.hasSuggestions— Meta lacksdocs(url/description/recommended) — optional but conventional. -
Chinese message / English everything else — Minor consistency nit.
Optimization Suggestions
- Replace chained regex tests in
groupOfwith 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 bysourcecould help on large files. path.resolve+replaceAllper external-looking source is only invoked for non-.sources — actuallyresolvedcomputes for all sources including bare packages, callingpath.resolveneedlessly. Sinceresolvedis only used in the twoapiregexes meant for project paths, you can skip resolution for bare module specifiers (not starting with.or@/). Minor perf win.entries.sortcomparator covers groups 0 and 4 specially; note group 4 also falls through tocompare(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; onlineincludesexact match meansvue-routerranks in the array whilevue-somethinggoes 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() }) |
There was a problem hiding this comment.
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./indexperforms side-effectful module initialization (e.g., registering components/globals) and previously ran earlier, the relative order among value imports could matter. Verify./indexhas 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/enumsis now before@/api/chat/file. A pure alphabetical sort would put@/api/chat/filefirst. 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 theKEYinjection tokens next to their corresponding component imports would improve readability:Consider combining named + default imports from the same module into a single statement where possible, e.g.:import ConversationList, { CONVERSATION_LIST_KEY } from '...'
(Only valid if theimport PortalConversationList, { PORTAL_CONVERSATION_LIST_KEY } from '../../left-sidebar/portal-conversation-list/index.vue'
.vuefile 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_KEYetc. must each be passed into aprovide(...)call below this snippet — nothing here shows usage, so double-check you didn't accidentally drop a reference when reshuffling.
5. Extension inconsistency
../index.tsstill carries an explicit.tsextension 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
KEYconstants 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/indexare 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 useimport typetoo for tree-shaking clarity.
7. Minor
const applicationSelectorRef = ref<InstanceType<typeof SelectApplicationDrawer>>()— preferref<SelectApplicationDrawer | null>(null)(orVueInstance) patterns; current form works but is verbose and implicitly starts asundefined. 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)。 |
There was a problem hiding this comment.
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:
Refis not used in the visible part of the file. If it is used further down (unchanged context), then importing it asimport type { Ref } from 'vue'is correct and actually an improvement viaverbatimModuleSyntax/tree-shaking. Otherwise, it's an unused import — remove it.- Similarly, verify
computedis 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
Refandcomputedare both used; removeRefif not. - Verify no module has import-time side effects before reordering.
- Align import ordering with your ESLint
import/order/simple-import-sortconfig. - Adopt a consistent policy for where
import typelines live (grouped vs. inline). - Consider enabling
verbatimModuleSyntaxand@typescript-eslint/consistent-type-importsto auto-enforce this pattern.
No functional bugs are introduced by this diff as-is, assuming the imports are all used and side-effect-free.
perf: format