Skip to content

Commit

Permalink
fix(injectPosition): resolve file paths to determine position
Browse files Browse the repository at this point in the history
  • Loading branch information
ineshbose committed Jan 13, 2025
1 parent 078772c commit 71be9ac
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
9 changes: 1 addition & 8 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,7 @@ export default defineNuxtModule<ModuleOptions>({

// inject only if this file isn't listed already by user
if (resolvedCss && !resolvedNuxtCss.includes(resolvedCss)) {
let injectPosition: number
try {
injectPosition = resolvers.resolveInjectPosition(nuxt.options.css, cssPathConfig?.injectPosition)
}
catch (e: any) {
throw new Error('failed to resolve Tailwind CSS injection position: ' + e.message)
}

const injectPosition = await resolvers.resolveInjectPosition(resolvedNuxtCss, cssPathConfig?.injectPosition)
nuxt.options.css.splice(injectPosition, 0, resolvedCss)
}

Expand Down
21 changes: 13 additions & 8 deletions src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const resolveEditorSupportConfig = (config: ModuleOptions['editorSupport'
*
* @returns index in the css array
*/
export function resolveInjectPosition(css: string[], position: InjectPosition = 'first') {
export async function resolveInjectPosition(css: string[], position: InjectPosition = 'first') {
if (typeof (position) === 'number') {
return ~~Math.min(position, css.length + 1)
}
Expand All @@ -56,18 +56,23 @@ export function resolveInjectPosition(css: string[], position: InjectPosition =
switch (position) {
case 'first': return 0
case 'last': return css.length
default: throw new Error('invalid literal: ' + position)
}
}

if (position.after !== undefined) {
const index = css.indexOf(position.after)
if (index === -1) {
throw new Error('`after` position specifies a file which does not exists on CSS stack: ' + position.after)
if (typeof (position) === 'object') {
const minIndex = 'after' in position ? css.indexOf(await resolvePath(position.after)) + 1 : 0
const maxIndex = 'before' in position ? css.indexOf(await resolvePath(position.before as string)) : css.length

if ([minIndex, maxIndex].includes(-1) || ('after' in position && minIndex === 0)) {
throw new Error(`\`injectPosition\` specifies a file which does not exists on CSS stack: ` + JSON.stringify(position))
}

if (minIndex > maxIndex) {
throw new Error(`\`injectPosition\` specifies a relative location \`${minIndex}\` that cannot be resolved (i.e., \`after\` orders \`before\` may be reversed): ` + JSON.stringify(position))
}

return index + 1
return 'after' in position ? minIndex : maxIndex
}

throw new Error('invalid position: ' + JSON.stringify(position))
throw new Error('invalid `injectPosition`: ' + JSON.stringify(position))
}

0 comments on commit 71be9ac

Please sign in to comment.