Skip to content

Commit

Permalink
feat: support :host conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
LastLeaf committed Jul 4, 2024
1 parent d1a945f commit fcb831c
Show file tree
Hide file tree
Showing 16 changed files with 549 additions and 157 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
{
"component": true,
"styleIsolation": "shared"
"component": true
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
image {
:host {
display: block;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
{
"component": true,
"styleIsolation": "shared"
"component": true
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
view {
:host {
display: block;
}
82 changes: 64 additions & 18 deletions glass-easel-miniprogram-webpack-plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import { NormalModule, type Compiler, type WebpackPluginInstance } from 'webpack
import { TmplGroup } from 'glass-easel-template-compiler'
import { escapeJsString } from './helpers'

type VirtualModulePluginType = {
apply: (compiler: Compiler) => void
writeModule: (p: string, c: string) => void
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const chokidar = require('chokidar')
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
Expand All @@ -18,6 +23,7 @@ export const GlassEaselMiniprogramWxssLoader = path.join(__dirname, 'wxss_loader

const PLUGIN_NAME = 'GlassEaselMiniprogramWebpackPlugin'
const CACHE_ETAG = 1
const HOST_STYLES_MODULE = '__glass_easel_host_styles__.wxss'

type PluginConfig = {
path: string
Expand Down Expand Up @@ -66,13 +72,24 @@ const writeCache = <T>(compiler: Compiler, key: string, value: T): Promise<void>
})

class StyleSheetManager {
map = Object.create(null) as { [path: string]: { scopeName: string; srcPath: string } }
map = Object.create(null) as {
[path: string]: { scopeName: string; srcPath: string; lowPriority: string }
}
enableStyleScope = Object.create(null) as { [path: string]: boolean }
scopeNameInc = 0
disableClassPrefix: boolean

constructor(disableClassPrefix: boolean) {
codeRoot: string
virtualModules: VirtualModulePluginType
hostStylesReady = false

constructor(
disableClassPrefix: boolean,
codeRoot: string,
virtualModules: VirtualModulePluginType,
) {
this.disableClassPrefix = disableClassPrefix
this.codeRoot = codeRoot
this.virtualModules = virtualModules
}

add(compPath: string, srcPath: string) {
Expand All @@ -93,6 +110,7 @@ class StyleSheetManager {
this.map[compPath] = {
srcPath,
scopeName,
lowPriority: '',
}
}

Expand All @@ -111,16 +129,33 @@ class StyleSheetManager {
return undefined
}

setLowPriorityStyles(compPath: string, source: string, _map: string) {
const meta = this.map[compPath]
if (meta && meta.lowPriority !== source) {
meta.lowPriority = source
}
}

prepareHostStyles() {
const lowPriorityContent = Object.values(this.map)
.map(({ lowPriority }) => lowPriority)
.join('\n')
const fullPath = path.join(this.codeRoot, HOST_STYLES_MODULE)
this.virtualModules.writeModule(fullPath, lowPriorityContent)
this.hostStylesReady = true
}

toCodeString() {
const arr = Object.entries(this.map).map(([compPath, { srcPath }]) => {
const s = `backend.registerStyleSheetContent('${escapeJsString(
compPath,
)}', require('${escapeJsString(srcPath)}'));`
)}', (require('${escapeJsString(srcPath)}').default||''));`
return s
})
const req = this.hostStylesReady ? `(require('./${HOST_STYLES_MODULE}').default||'')` : "''"
return `
function (backend) {
backend.registerStyleSheetContent('app', require('./app.wxss'))
backend.registerStyleSheetContent('app', ${req} + (require('./app.wxss').default||''))
${arr.join('')}
}
`
Expand All @@ -134,10 +169,7 @@ export class GlassEaselMiniprogramWebpackPlugin implements WebpackPluginInstance
customBootstrap: boolean
disableClassPrefix: boolean
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
virtualModules = new VirtualModulesPlugin() as {
apply: (compiler: Compiler) => void
writeModule: (p: string, c: string) => void
}
virtualModules = new VirtualModulesPlugin() as VirtualModulePluginType

constructor(options: Partial<PluginConfig>) {
this.path = options.path || './src'
Expand All @@ -157,7 +189,15 @@ export class GlassEaselMiniprogramWebpackPlugin implements WebpackPluginInstance
let globalStaticConfig = {} as GlobalStaticConfig
let appEntry: 'app.js' | 'app.ts' | null = null
const depsTmplGroup = new TmplGroup()
const styleSheetManager = new StyleSheetManager(this.disableClassPrefix)

// init style sheet manager
const virtualModules = this.virtualModules
virtualModules.apply(compiler)
const styleSheetManager = new StyleSheetManager(
this.disableClassPrefix,
codeRoot,
this.virtualModules,
)

// cleanup wasm modules
compiler.hooks.shutdown.tap(PLUGIN_NAME, () => {
Expand Down Expand Up @@ -351,8 +391,6 @@ export class GlassEaselMiniprogramWebpackPlugin implements WebpackPluginInstance
})

// collect virtual files
const virtualModules = this.virtualModules
virtualModules.apply(compiler)
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
// add loaders
NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(
Expand All @@ -364,11 +402,18 @@ export class GlassEaselMiniprogramWebpackPlugin implements WebpackPluginInstance
const relPath = path.relative(codeRoot, absPath).split(path.sep).join('/')
const compPath = relPath.slice(0, -extName.length)
if (extName === '.wxss') {
loaders.forEach((x) => {
loaders.forEach((x, i) => {
if (x.loader === GlassEaselMiniprogramWxssLoader) {
x.options = {
classPrefix: styleSheetManager.getScopeName(compPath),
relPath,
if (relPath === HOST_STYLES_MODULE) {
loaders.splice(i, loaders.length - i)
} else {
x.options = {
classPrefix: styleSheetManager.getScopeName(compPath),
compPath,
setLowPriorityStyles: (s: string, map: string) => {
styleSheetManager.setLowPriorityStyles(compPath, s, map)
},
}
}
}
})
Expand Down Expand Up @@ -446,6 +491,7 @@ export class GlassEaselMiniprogramWebpackPlugin implements WebpackPluginInstance
// write index module
await Promise.all(tasks)
await new Promise<void>((resolve) => {
styleSheetManager.prepareHostStyles()
updateVirtualIndexFile(tmplGroup)
tmplGroup.free()
compilation.rebuildModule(indexModule!, () => resolve())
Expand Down Expand Up @@ -515,14 +561,14 @@ export class GlassEaselMiniprogramWebpackPlugin implements WebpackPluginInstance
if (typeof global !== 'undefined') { return global }
throw new Error('The global object cannot be recognized')
})()
`
const entryFooter = `
var initWithBackend = function (backend) {
var ab = env.associateBackend(backend)
;(${styleSheetManager.toCodeString()})(ab)
return ab
}
exports.initWithBackend = initWithBackend
`
const entryFooter = `
var registerGlobalEventListener = function (backend) {
backend.onEvent((target, type, detail, options) => {
glassEasel.triggerEvent(target, type, detail, options)
Expand Down
8 changes: 5 additions & 3 deletions glass-easel-miniprogram-webpack-plugin/wxss_loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ const { StyleSheetTransformer } = require('glass-easel-stylesheet-compiler')

module.exports = function (src, prevMap, meta) {
const callback = this.async()
const { classPrefix } = this.query
const sst = new StyleSheetTransformer(this.resourcePath, src, classPrefix, 750)
const { classPrefix, compPath, setLowPriorityStyles } = this.query
const sst = new StyleSheetTransformer(this.resourcePath, src, classPrefix, 750, compPath)
setLowPriorityStyles(sst.getLowPriorityContent(), sst.getLowPrioritySourceMap())
const ss = sst.getContent()
let map
if (this.sourceMap) {
const ssSourceMap = JSON.parse(sst.toSourceMap())
const ssSourceMap = JSON.parse(sst.getSourceMap())
sst.free()
if (prevMap) {
const destConsumer = new SourceMapConsumer(ssSourceMap)
const srcConsumer = new SourceMapConsumer(prevMap)
Expand Down
3 changes: 3 additions & 0 deletions glass-easel-stylesheet-compiler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ js_bindings = []
[dependencies]
cssparser = "0.34"
sourcemap = "6"
serde = "1"
serde_json = "1"
serde-wasm-bindgen = "0.6"
wasm-bindgen = "0.2"
js-sys = "0.3"
log = "0.4"
Expand Down
7 changes: 6 additions & 1 deletion glass-easel-stylesheet-compiler/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::ops::Range;

use serde::{Deserialize, Serialize};

/// A location in source code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Position {
Expand Down Expand Up @@ -60,20 +62,23 @@ impl ParseError {
pub enum ParseErrorKind {
UnexpectedCharacter = 0x10001,
IllegalImportPosition,
HostSelectorCombination,
}

impl ParseErrorKind {
fn static_message(&self) -> &'static str {
match self {
Self::UnexpectedCharacter => "unexpected character",
Self::IllegalImportPosition => "`@import` should be placed at the start of the stylesheet (according to CSS standard)",
Self::HostSelectorCombination => "`:host` selector combined with other selectors are not supported",
}
}

pub fn level(&self) -> ParseErrorLevel {
match self {
Self::UnexpectedCharacter => ParseErrorLevel::Fatal,
Self::IllegalImportPosition => ParseErrorLevel::Note,
Self::HostSelectorCombination => ParseErrorLevel::Warn,
}
}
}
Expand All @@ -91,7 +96,7 @@ impl std::fmt::Display for ParseErrorKind {
}

#[repr(u8)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum ParseErrorLevel {
/// Likely to be an mistake and should be noticed.
///
Expand Down
Loading

0 comments on commit fcb831c

Please sign in to comment.