mainPackageStyles.test.mjs 9.53 KB
import assert from 'node:assert/strict'
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
import { formatResponsiveFontSize } from '../../utils/responsiveFontSize.js'

const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const STYLE_REFERENCE_EXTENSIONS = new Set([
  '.css',
  '.js',
  '.json',
  '.sass',
  '.scss',
  '.wxml',
  '.wxs',
  '.wxss'
])
const SCAN_ROOTS = [
  'app.sass',
  'components',
  'integration',
  'packageCrowdFunding',
  'packageDynamicForm',
  'packageEquity',
  'packageEquityAI',
  'packageStudyCenter',
  'packageUsedCar',
  'pages',
  'styles',
  'subvehicleConversion',
  'tabDate',
  'tabIndex',
  'tabMine',
  'tabOperating',
  'tabRepairOrder',
  'tabWorkOrder'
]

/**
 * Recursively lists runtime source files in deterministic order.
 * Test, documentation, generated-authority and dependency folders are excluded
 * because they are not compiled as mini-program runtime consumers.
 * @param {string} entryPath Absolute file or directory path.
 * @returns {string[]} Absolute runtime source paths.
 */
function listRuntimeSourceFiles(entryPath) {
  if (!existsSync(entryPath)) return []
  const stats = statSync(entryPath)
  if (stats.isFile()) return STYLE_REFERENCE_EXTENSIONS.has(path.extname(entryPath))
    ? [entryPath]
    : []

  return readdirSync(entryPath, { withFileTypes: true })
    .filter(entry => !['docs', 'test', 'tests'].includes(entry.name))
    .sort((left, right) => left.name.localeCompare(right.name))
    .flatMap(entry => listRuntimeSourceFiles(path.join(entryPath, entry.name)))
}

/**
 * Removes source comments so dormant examples do not force runtime variables.
 * @param {string} source Runtime source text.
 * @returns {string} Comment-free source used by the dependency assertion.
 */
function stripComments(source) {
  return source
    .replace(/<!--[\s\S]*?-->/g, '')
    .replace(/\/\*[\s\S]*?\*\//g, '')
    .replace(/^\s*\/\/.*$/gm, '')
}

/**
 * Reads a parenthesized numeric Sass list.
 * @param {string} source app.sass source.
 * @param {string} variableName Sass variable name without the dollar sign.
 * @returns {number[]} Sorted numeric values.
 */
function readSassNumberList(source, variableName) {
  const match = new RegExp(`\\$${variableName}:\\s*\\(([\\s\\S]*?)\\);`).exec(source)
  assert.ok(match, `$${variableName} must be a parenthesized Sass list`)
  return [...match[1].matchAll(/\d+(?:\.\d+)?/g)]
    .map(item => Number(item[0]))
    .sort((left, right) => left - right)
}

/**
 * Resolves every WXSS import declared by a stylesheet.
 * @param {string} relativePath Project-relative stylesheet path.
 * @returns {string[]} Absolute imported stylesheet paths.
 */
function resolveStyleImports(relativePath) {
  const sourcePath = path.join(projectRoot, relativePath)
  const source = readFileSync(sourcePath, 'utf8')

  return [...source.matchAll(/@import\s+['"]([^'"]+)['"]\s*;/g)]
    .map(match => path.resolve(path.dirname(sourcePath), match[1]))
}

/**
 * Asserts that a group of stylesheets delegates duplicated rules to one file.
 * @param {string[]} consumerPaths Project-relative consumer paths.
 * @param {string} sharedPath Project-relative shared stylesheet path.
 * @param {string[]} movedSelectors Selectors that must live only in the shared file.
 * @returns {void}
 */
function assertSharedStyle(consumerPaths, sharedPath, movedSelectors) {
  const absoluteSharedPath = path.join(projectRoot, sharedPath)
  assert.ok(existsSync(absoluteSharedPath), `${sharedPath} must exist`)

  const sharedSource = stripComments(readFileSync(absoluteSharedPath, 'utf8'))
  for (const relativePath of consumerPaths) {
    const imports = resolveStyleImports(relativePath)
    assert.ok(
      imports.includes(absoluteSharedPath),
      `${relativePath} must import ${sharedPath}`
    )

    const consumerSource = stripComments(readFileSync(path.join(projectRoot, relativePath), 'utf8'))
    for (const selector of movedSelectors) {
      const selectorPattern = new RegExp(`${selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\{`)
      assert.match(sharedSource, selectorPattern, `${selector} must be declared by ${sharedPath}`)
      assert.doesNotMatch(
        consumerSource,
        selectorPattern,
        `${selector} must not be duplicated in ${relativePath}`
      )
    }
  }
}

/**
 * Asserts that selectors with identical declarations use one grouped rule.
 * @param {string} relativePath Project-relative stylesheet path.
 * @param {string[][]} selectorGroups Ordered selector groups.
 * @returns {void}
 */
function assertGroupedSelectors(relativePath, selectorGroups) {
  const source = stripComments(readFileSync(path.join(projectRoot, relativePath), 'utf8'))

  for (const selectors of selectorGroups) {
    const escapedSelectors = selectors.map(selector =>
      selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
    const groupedRulePattern = new RegExp(`${escapedSelectors.join('\\s*,\\s*')}\\s*\\{`)
    assert.match(
      source,
      groupedRulePattern,
      `${relativePath} must group ${selectors.join(', ')}`
    )
  }
}

/**
 * Collects numeric custom-property references from runtime source.
 * @returns {{ base: number[], content: number[], dynamicPaths: string[] }} References.
 */
function collectFontSizeReferences() {
  const base = new Set()
  const content = new Set()
  const dynamicPaths = []

  for (const file of SCAN_ROOTS.flatMap(root =>
    listRuntimeSourceFiles(path.join(projectRoot, root)))) {
    const source = stripComments(readFileSync(file, 'utf8'))
    for (const match of source.matchAll(/var\(--fontSize(Content)?(\d+)\)/g)) {
      ;(match[1] ? content : base).add(Number(match[2]))
    }
    if (source.includes('--fontSize${')) {
      dynamicPaths.push(path.relative(projectRoot, file).replaceAll('\\', '/'))
    }
  }

  return {
    base: [...base].sort((left, right) => left - right),
    content: [...content].sort((left, right) => left - right),
    dynamicPaths
  }
}

test('responsive font-size formatter preserves phone and large-screen scaling', () => {
  assert.equal(formatResponsiveFontSize(28, 767), 'calc(28vmin / 7.5)')
  assert.equal(formatResponsiveFontSize(28, 768), 'calc(28vmin / 8.5)')
  assert.equal(formatResponsiveFontSize(1114, 375), 'calc(1114vmin / 7.5)')
  assert.throws(() => formatResponsiveFontSize(Number.NaN, 375), /finite number/)
  assert.throws(() => formatResponsiveFontSize(28, Number.POSITIVE_INFINITY), /finite number/)
})

test('app Sass emits exactly the statically referenced font-size variables', () => {
  const appSass = readFileSync(path.join(projectRoot, 'app.sass'), 'utf8')
  const references = collectFontSizeReferences()
  const declaredBase = readSassNumberList(appSass, 'font-size-values')
  const declaredContent = readSassNumberList(appSass, 'font-size-content-values')

  assert.deepEqual(declaredBase, references.base)
  assert.deepEqual(declaredContent, references.content)
  assert.deepEqual(
    references.dynamicPaths,
    [],
    `runtime CSS variable names must not be assembled dynamically:\n${references.dynamicPaths.join('\n')}`
  )
  assert.ok(declaredBase.length < 400, 'font-size declarations must stay usage-driven')
  assert.ok(declaredContent.length < 50, 'content font-size declarations must stay usage-driven')
})

test('main-package page clones share scoped WXSS rules', () => {
  assertSharedStyle(
    [
      'pages/tabWorkOrder/pages/index/index.sass',
      'pages/tabDateIndex/pages/tabDateIndex.sass'
    ],
    'styles/main-list-common.wxss',
    ['page', '.to-box', '.search-box', '.search-box .search-input', '.input-placeholder']
  )

  assertSharedStyle(
    ['pages/sceneIndex/sceneIndex.wxss', 'pages/changeScene/changeScene.wxss'],
    'styles/scene-selection-common.wxss',
    ['page', '.user-box', '.scene-item .left', '.change-btn', '.logout']
  )
})

test('main-package component clones share scoped WXSS rules', () => {
  assertSharedStyle(
    [
      'pages/tabWorkOrder/components/OrderScreen/OrderScreen.wxss',
      'pages/tabDateIndex/components/DateScreen/DateScreen.wxss'
    ],
    'styles/screen-panel-common.wxss',
    ['.confirm-box', '.box .title', '.box .list-box .item', '.btn-box', '.text-hide']
  )

  assertSharedStyle(
    ['components/DatePicker/DatePicker.wxss', 'components/RemarkPopup/RemarkPopup.wxss'],
    'styles/fixed-picker-common.wxss',
    ['.fixed-box', '.fixed-content', '.fixed-content .fixed-footer', '.text-center']
  )

  assertSharedStyle(
    ['pages/components/authSetting/authSetting.wxss', 'pages/components/authNoLogin/authNoLogin.wxss'],
    'styles/auth-tips-common.wxss',
    ['.tips .icon', '.tips .icon .check-img', '.tips .choose-box']
  )
})

test('identical declarations in main-package styles use grouped selectors', () => {
  assertGroupedSelectors('components/navigationBar/navigationBar.wxss', [
    ['.back-box', '.menu-box']
  ])
  assertGroupedSelectors('pages/tabDateIndex/pages/tabDateIndex.sass', [
    ['.date-icon', '.phone-icon']
  ])
  assertGroupedSelectors('pages/accountItems/accountItems.wxss', [
    ['.items .right .midle_4', '.items .right .midle_5']
  ])
  assertGroupedSelectors('pages/merchantList/merchantList.wxss', [
    [
      '.custom_items .text_box .status_text_0',
      '.custom_items .text_box .status_text_3'
    ]
  ])
  assertGroupedSelectors('components/SideSelectPopup/SideSelectPopup.wxss', [
    [
      '.search-box .select_box .option_box::after',
      '.search-box .select_box .option_box::before'
    ],
    [
      '.wrapper .custom_element .text_box .status_text_0',
      '.wrapper .custom_element .text_box .status_text_3'
    ]
  ])
})