Theming API: Add new helper methods and remove useColorScheme

pull/5507/head
mertsincan 2024-03-22 13:02:01 +00:00
parent 064f7f9b02
commit 7bd88de07b
13 changed files with 155 additions and 113 deletions

16
app.vue
View File

@ -6,7 +6,6 @@
<script>
import EventBus from '@/layouts/AppEventBus';
import { useColorScheme } from 'primevue/themes';
export default {
beforeMount() {
@ -14,7 +13,8 @@ export default {
if (isDark) document.documentElement.classList.add('p-dark');
else document.documentElement.classList.remove('p-dark');
//@todo - set initial colorScheme
this.$appState.darkTheme = isDark;
},
mounted() {
EventBus.on('theme-change', this.themeChangeListener);
@ -33,15 +33,13 @@ export default {
document.startViewTransition(() => this.applyTheme(event));
},
applyTheme(event) {
const { toggleColorScheme } = useColorScheme();
const newColorScheme = toggleColorScheme();
const isDark = event.dark;
localStorage['primevue-theme'] = newColorScheme;
if (isDark) document.documentElement.classList.add('p-dark');
else document.documentElement.classList.remove('p-dark');
/*this.$appState.darkTheme = event.dark;
if (event.dark) document.documentElement.classList.add('p-dark');
else document.documentElement.classList.remove('p-dark');*/
localStorage['primevue-theme'] = isDark ? 'dark' : 'light';
this.$appState.darkTheme = isDark;
}
}
};

View File

@ -1,5 +1,5 @@
import { FilterMatchMode } from 'primevue/api';
import Theme from 'primevue/themes';
import Theme, { ThemeService } from 'primevue/themes';
import PrimeOne from 'primevue/themes/primeone';
import Aura from 'primevue/themes/primeone/aura';
import { inject, reactive, watch } from 'vue';
@ -144,7 +144,7 @@ export const defaultOptions = {
darkModeSelector: '.p-dark',
cssLayer: false
/*
darkModeSelector: '.p-dark | [data-p-dark="true"] | system',
darkModeSelector: '.p-dark | [data-p-dark="true"] | system(default)',
cssLayer: {
// cssLayer: true | false | undefined | object // default: undefined
name: '', // ({component_name, type=variable|style}) => layer_name // default: primevue
@ -216,5 +216,11 @@ export default {
app.config.globalProperties.$primevue = PrimeVue;
app.provide(PrimeVueSymbol, PrimeVue);
ThemeService.on('theme:change', (newTheme) => {
app.config.globalProperties.$primevue.config.theme = newTheme;
}).on('preset:change', (newPreset) => {
app.config.globalProperties.$primevue.config.theme.preset = newPreset;
});
}
};

View File

@ -1,27 +1,30 @@
import { ThemeUtils } from 'primevue/themes';
import { ThemeService, ThemeUtils } from 'primevue/themes';
export default {
defaults: {
variable: {
prefix: '',
prefix: 'p',
selector: ':root',
excludedKeyRegex: /^(primitive|semantic|variables|colorscheme|light|dark|common|colors|root|states|components|directives)$/gi
excludedKeyRegex: /^(primitive|semantic|components|directives|variables|colorscheme|light|dark|common|root|states)$/gi
},
darkModeSelector: '.p-dark',
options: {
prefix: 'p',
darkModeSelector: 'system',
cssLayer: {
name: 'primevue',
order: 'primevue'
}
}
},
_pConfig: undefined,
_theme: undefined,
_initialized: false,
_currentColorScheme: 'light',
_layerNames: new Set(),
_tokens: {},
init() {
if (!this._initialized) {
this._tokens = ThemeUtils.createTokens(this.preset, this.getCurrentColorScheme(), this.defaults);
this._tokens = ThemeUtils.createTokens(this.preset, this.defaults);
ThemeService.emit('theme:init', this.theme);
}
this._initialized = true;
@ -50,15 +53,29 @@ export default {
getTokenValue(tokenPath) {
return ThemeUtils.getTokenValue(this.tokens, tokenPath, this.defaults);
},
getTheme() {
return this.theme;
},
setTheme(newValue) {
this._theme = newValue;
this._theme = {
...newValue,
options: {
...this.defaults.options,
...newValue.options
}
};
this._tokens = ThemeUtils.createTokens(newValue?.preset, this.defaults);
ThemeService.emit('theme:change', newValue);
},
getPreset() {
return this.preset;
},
setPreset(newValue) {
this._theme = { ...this.theme, preset: newValue };
this._tokens = ThemeUtils.createTokens(newValue, this.defaults);
},
getCurrentColorScheme() {
return this._currentColorScheme;
},
setCurrentColorScheme(newValue) {
this._currentColorScheme = newValue;
ThemeService.emit('preset:change', newValue);
},
getLayerNames() {
return [...this._layerNames];
@ -66,13 +83,6 @@ export default {
setLayerNames(layerName) {
this._layerNames?.add(layerName);
},
toggleColorScheme() {
const newColorScheme = ThemeUtils.toggleColorScheme(this.options, this.getCurrentColorScheme(), this.defaults);
this.setCurrentColorScheme(newColorScheme);
return newColorScheme;
},
getCommonCSS(name = '', theme, params) {
return ThemeUtils.getCommon({ name, theme: theme || this.theme, params, defaults: this.defaults, set: { layerNames: this.setLayerNames.bind(this) } });
},

View File

@ -0,0 +1,15 @@
import Theme from 'primevue/themes';
export default (preset1, preset2) => {
const [{ primitive: p1, semantic: s1, components: c1, directives: d1 }, { primitive: p2, semantic: s2, components: c2, directives: d2 }] = [preset1, preset2];
const newPreset = {
primitive: { ...p1, ...p2 },
semantic: { ...s1, ...s2 },
components: { ...c1, ...c2 },
directives: { ...d1, ...d2 }
};
Theme.setPreset(newPreset);
return newPreset;
};

View File

@ -1,7 +1,9 @@
export * from './color';
export * from './dt';
export { default as extendPreset } from './extendPreset';
export { default as ThemeService } from './service';
export { default as SharedUtils } from './sharedUtils';
export { default as ThemeUtils } from './themeUtils';
export { default as toVariables } from './toVariables';
export { default as useColorScheme } from './useColorScheme';
export { default as updatePreset } from './updatePreset';
export { default as updateTheme } from './updateTheme';

View File

@ -9,6 +9,8 @@ function createService() {
else handlers.push(handler);
allHandlers.set(type, handlers);
return this;
},
off(type, handler) {
@ -17,6 +19,8 @@ function createService() {
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
return this;
},
emit(type, evt) {

View File

@ -44,6 +44,23 @@ export default {
Object.assign(value1, value2);
}
},
mergeKeysByRegex(target = {}, source = {}, regex) {
const mergedObj = { ...target };
Object.keys(source).forEach((key) => {
if (this.test(regex, key)) {
if (this.isObject(source[key]) && key in target && this.isObject(target[key])) {
mergedObj[key] = this.mergeKeysByRegex(target[key], source[key], regex);
} else {
mergedObj[key] = source[key];
}
} else {
mergedObj[key] = source[key];
}
});
return mergedObj;
},
getItemValue(obj, ...params) {
return this.isFunction(obj) ? obj(...params) : obj;
},

View File

@ -6,30 +6,30 @@ export default {
class: {
pattern: /^\.([a-zA-Z][\w-]*)$/,
resolve(value) {
return { type: 'class', selector: value, value: value.trim().match(this.pattern)?.[1] };
return { type: 'class', selector: value, matched: this.pattern.test(value.trim()) };
}
},
attr: {
pattern: /^\[(.*)\]$/,
resolve(value) {
return { type: 'attr', selector: `:root${value}`, value: value.trim().match(this.pattern)?.[1]?.split('=') };
return { type: 'attr', selector: `:root${value}`, matched: this.pattern.test(value.trim()) };
}
},
media: {
pattern: /^@media (.*)$/,
resolve(value) {
return { type: 'media', selector: `${value}{:root{[CSS]}}`, value: value.trim().match(this.pattern)?.[1] };
return { type: 'media', selector: `${value}{:root{[CSS]}}`, matched: this.pattern.test(value.trim()) };
}
},
system: {
pattern: /^system$/,
resolve(value) {
return { type: 'system', selector: '@media (prefers-color-scheme: dark){:root{[CSS]}}', value: this.pattern.test(value) ? 'system' : undefined };
return { type: 'system', selector: '@media (prefers-color-scheme: dark){:root{[CSS]}}', matched: this.pattern.test(value.trim()) };
}
},
custom: {
resolve(value) {
return { type: 'custom', selector: value, value: undefined };
return { type: 'custom', selector: value, matched: true };
}
}
},
@ -38,7 +38,7 @@ export default {
.filter((k) => k !== 'custom')
.map((r) => this.rules[r]);
return [value].flat().map((v) => rules.map((r) => r.resolve(v)).find((rr) => !!rr.value) ?? this.rules.custom.resolve(v));
return [value].flat().map((v) => rules.map((r) => r.resolve(v)).find((rr) => rr.matched) ?? this.rules.custom.resolve(v));
}
},
getCommon({ name = '', theme = {}, params, set, defaults }) {
@ -46,17 +46,14 @@ export default {
let primitive_css, semantic_css, global_css;
if (SharedUtils.object.isNotEmpty(preset)) {
const { options, extend } = theme;
const { options } = theme;
const { primitive, semantic } = preset;
const { colorScheme, ...sRest } = semantic || {};
const { dark, ...csRest } = colorScheme || {};
const { primitive: primitiveExt, semantic: semanticExt } = extend || {};
const { colorScheme: colorSchemeExt, ...sRestExt } = semanticExt || {};
const { dark: darkExt, ...csRestExt } = colorSchemeExt || {};
const prim_css = SharedUtils.object.isNotEmpty(primitive) ? this._toVariables({ primitive: { ...primitive, ...primitiveExt } }, options).declarations : '';
const sRest_css = SharedUtils.object.isNotEmpty(sRest) ? this._toVariables({ semantic: { ...sRest, ...sRestExt } }, options).declarations : '';
const csRest_css = SharedUtils.object.isNotEmpty(csRest) ? this._toVariables({ light: { ...csRest, ...csRestExt } }, options).declarations : '';
const dark_css = SharedUtils.object.isNotEmpty(dark) ? this._toVariables({ dark: { ...dark, ...darkExt } }, options).declarations : '';
const prim_css = SharedUtils.object.isNotEmpty(primitive) ? this._toVariables({ primitive }, options).declarations : '';
const sRest_css = SharedUtils.object.isNotEmpty(sRest) ? this._toVariables({ semantic: sRest }, options).declarations : '';
const csRest_css = SharedUtils.object.isNotEmpty(csRest) ? this._toVariables({ light: csRest }, options).declarations : '';
const dark_css = SharedUtils.object.isNotEmpty(dark) ? this._toVariables({ dark }, options).declarations : '';
primitive_css = this._transformCSS(name, prim_css, 'light', 'variable', options, set, defaults);
semantic_css = `${this._transformCSS(name, `${sRest_css}${csRest_css}color-scheme:light`, 'light', 'variable', options, set, defaults)}${this._transformCSS(
@ -79,14 +76,12 @@ export default {
};
},
getPresetC({ name = '', theme = {}, params, set, defaults }) {
const { preset, options, extend } = theme;
const { preset, options } = theme;
const { colorScheme, ...vRest } = preset?.components?.[name] || {};
const { dark, ...csRest } = colorScheme || {};
const { colorScheme: colorSchemeExt, ...vRestExt } = extend?.components?.[name] || {};
const { dark: darkExt, ...csRestExt } = colorSchemeExt || {};
const vRest_css = SharedUtils.object.isNotEmpty(vRest) ? this._toVariables({ [name]: { ...vRest, ...vRestExt } }, options).declarations : '';
const csRest_css = SharedUtils.object.isNotEmpty(csRest) ? this._toVariables({ [name]: { ...csRest, ...csRestExt } }, options).declarations : '';
const dark_css = SharedUtils.object.isNotEmpty(dark) ? this._toVariables({ [name]: { ...dark, ...darkExt } }, options).declarations : '';
const vRest_css = SharedUtils.object.isNotEmpty(vRest) ? this._toVariables({ [name]: vRest }, options).declarations : '';
const csRest_css = SharedUtils.object.isNotEmpty(csRest) ? this._toVariables({ [name]: csRest }, options).declarations : '';
const dark_css = SharedUtils.object.isNotEmpty(dark) ? this._toVariables({ [name]: dark }, options).declarations : '';
return `${this._transformCSS(name, `${vRest_css}${csRest_css}`, 'light', 'variable', options, set, defaults)}${this._transformCSS(name, dark_css, 'dark', 'variable', options, set, defaults)}`;
},
@ -98,14 +93,12 @@ export default {
return this._transformCSS(name, computed_css, undefined, 'style', options, set, defaults);
},
getPresetD({ name = '', theme = {}, params, set, defaults }) {
const { preset, options, extend } = theme;
const { preset, options } = theme;
const { colorScheme, ...vRest } = preset?.directives?.[name] || {};
const { dark, ...csRest } = colorScheme || {};
const { colorScheme: colorSchemeExt, ...vRestExt } = extend?.directives?.[name] || {};
const { dark: darkExt, ...csRestExt } = colorSchemeExt || {};
const vRest_css = SharedUtils.object.isNotEmpty(vRest) ? this._toVariables({ [name]: { ...vRest, ...vRestExt } }, options).declarations : '';
const csRest_css = SharedUtils.object.isNotEmpty(csRest) ? this._toVariables({ [name]: { ...csRest, ...csRestExt } }, options).declarations : '';
const dark_css = SharedUtils.object.isNotEmpty(dark) ? this._toVariables({ [name]: { ...dark, ...darkExt } }, options).declarations : '';
const vRest_css = SharedUtils.object.isNotEmpty(vRest) ? this._toVariables({ [name]: vRest }, options).declarations : '';
const csRest_css = SharedUtils.object.isNotEmpty(csRest) ? this._toVariables({ [name]: csRest }, options).declarations : '';
const dark_css = SharedUtils.object.isNotEmpty(dark) ? this._toVariables({ [name]: dark }, options).declarations : '';
return `${this._transformCSS(name, `${vRest_css}${csRest_css}`, 'light', 'variable', options, set, defaults)}${this._transformCSS(name, dark_css, 'dark', 'variable', options, set, defaults)}`;
},
@ -117,39 +110,13 @@ export default {
return this._transformCSS(name, computed_css, undefined, 'style', options, set, defaults);
},
getColorSchemeOption(options, defaults) {
return this.regex.resolve(options.darkModeSelector ?? defaults.darkModeSelector);
},
toggleColorScheme(options = {}, currentColorScheme, defaults) {
const newColorScheme = currentColorScheme === 'dark' ? 'light' : 'dark';
const defaultDocumentEl = SharedUtils.dom.isClient() ? window.document?.documentElement : undefined;
if (defaultDocumentEl) {
const colorSchemeOption = this.getColorSchemeOption(options, defaults);
colorSchemeOption.forEach(({ type, value }) => {
switch (type) {
case 'class':
SharedUtils.dom[newColorScheme === 'dark' ? 'addClass' : 'removeClass'](defaultDocumentEl, value);
break;
case 'attr':
newColorScheme === 'dark' ? defaultDocumentEl.setAttribute(value[0], value[1].replace(/['"]/g, '')) : defaultDocumentEl.removeAttribute(value[0]);
break;
default:
console.warn(`The 'toggleColorScheme' method cannot be used with the specified 'darkModeSelector' options.`);
break;
}
});
}
return newColorScheme;
return this.regex.resolve(options.darkModeSelector ?? defaults.options.darkModeSelector);
},
getLayerOrder(name, options = {}, params, defaults) {
const { cssLayer } = options;
if (cssLayer) {
const order = SharedUtils.object.getItemValue(cssLayer.order || defaults.cssLayer.order, params);
const order = SharedUtils.object.getItemValue(cssLayer.order || defaults.options.cssLayer.order, params);
return `@layer ${order}`;
}
@ -188,18 +155,19 @@ export default {
return css.join('');
},
createTokens(obj = {}, currentColorScheme, defaults, parentKey = '', parentPath = '', tokens = {}) {
createTokens(obj = {}, defaults, parentKey = '', parentPath = '', tokens = {}) {
Object.entries(obj).forEach(([key, value]) => {
const currentKey = SharedUtils.object.test(defaults.variable.excludedKeyRegex, key) ? parentKey : parentKey ? `${parentKey}.${SharedUtils.object.toTokenKey(key)}` : SharedUtils.object.toTokenKey(key);
const currentPath = parentPath ? `${parentPath}.${key}` : key;
if (SharedUtils.object.isObject(value)) {
this.createTokens(value, currentColorScheme, defaults, currentKey, currentPath, tokens);
this.createTokens(value, defaults, currentKey, currentPath, tokens);
} else {
tokens[currentKey] ||= {
paths: [],
computed(colorScheme) {
const scheme = colorScheme || currentColorScheme;
// @todo
const scheme = colorScheme;
return this.paths.find((p) => p.scheme === scheme || p.scheme === 'none')?.computed();
}
@ -268,7 +236,7 @@ export default {
}
if (cssLayer) {
let layerOptions = { ...defaults.cssLayer };
let layerOptions = { ...defaults.options.cssLayer };
SharedUtils.object.isObject(cssLayer) && (layerOptions.name = SharedUtils.object.getItemValue(cssLayer.name, { name, type }));

View File

@ -0,0 +1,11 @@
import Theme, { SharedUtils } from 'primevue/themes';
const VARIABLE = Theme.defaults.variable;
export default (preset) => {
const newPreset = SharedUtils.object.mergeKeysByRegex(Theme.getPreset(), preset, VARIABLE.excludedKeyRegex);
Theme.setPreset(newPreset);
return newPreset;
};

View File

@ -0,0 +1,13 @@
import Theme from 'primevue/themes';
export default (theme) => {
const [{ options: o1 }, { options: o2 }] = [Theme.getTheme(), theme];
const newTheme = {
...theme,
options: { ...o1, ...o2 }
};
Theme.setTheme(newTheme);
return newTheme;
};

View File

@ -1,17 +0,0 @@
import Theme from 'primevue/themes';
export default (initial = 'light') => {
// @todo
//Theme.setCurrentColorScheme(initial);
return {
colorScheme: Theme.getCurrentColorScheme(),
toggleColorScheme() {
const newColorScheme = Theme.toggleColorScheme();
Theme.setCurrentColorScheme(newColorScheme);
return newColorScheme;
}
};
};

View File

@ -38,6 +38,8 @@
</template>
<script>
import { palette, $dt, updatePreset, updateTheme } from 'primevue/themes';
export default {
data() {
return {
@ -99,9 +101,22 @@ export default {
document.startViewTransition(() => this.applyTheme(type, color));
},
applyTheme(type, color) {
for (const shade in color.palette) {
document.documentElement.style.setProperty(`--p-${type}-${shade}`, `${color.palette[shade]}`);
updatePreset({
semantic:
type === 'surface'
? {
colorScheme: {
dark: {
surface: color.palette
}
}
}
: { [type]: color.palette }
});
/*for (const shade in color.palette) {
document.documentElement.style.setProperty(`--p-${type}-${shade}`, `${color.palette[shade]}`);
}*/
},
onRippleChange(value) {
this.$appState.ripple = value;

View File

@ -1,7 +1,7 @@
const $appState = {
install: (Vue, options) => {
Vue.config.globalProperties.$appState = reactive({
theme: 'aura-light-green',
//theme: 'aura-light-green',
darkTheme: false,
codeSandbox: false,
sourceType: 'options-api',