Move nuxt-primevue to showcase and change plugin names

This commit is contained in:
mertsincan 2023-10-24 11:09:12 +01:00
parent 466ff52431
commit 5440d3d6ea
14 changed files with 583 additions and 303 deletions

View file

@ -0,0 +1,103 @@
import { addPlugin, addPluginTemplate, addTemplate, createResolver, defineNuxtModule } from '@nuxt/kit';
import { register } from './register';
export default defineNuxtModule({
meta: {
name: 'nuxt-primevue',
configKey: 'primevue',
compatibility: {
nuxt: '^3.0.0'
}
},
defaults: {
usePrimeVue: true,
resolvePath: undefined,
layerOrder: 'tailwind-base, primevue, tailwind-utilities',
importPT: undefined,
options: {},
components: {
prefix: '',
name: undefined,
include: undefined,
exclude: undefined
},
directives: {
prefix: '',
name: undefined,
include: undefined,
exclude: undefined
},
composables: {
prefix: '',
name: undefined,
include: undefined,
exclude: undefined
}
},
hooks: {},
setup(moduleOptions, nuxt) {
const resolver = createResolver(import.meta.url);
const registered = register(moduleOptions);
const { importPT } = moduleOptions;
nuxt.options.runtimeConfig.public.primevue = {
...moduleOptions,
...registered
};
//nuxt.options.build.transpile.push('nuxt');
nuxt.options.build.transpile.push('primevue');
const styleContent = () => `
${registered.styles.map((style) => `import ${style.as} from '${style.from}';`).join('\n')}
const styles = [
${registered.injectStylesAsString.join('')},
${registered.styles.map((item) => `${item.as} && ${item.as}.getStyleSheet ? ${item.as}.getStyleSheet() : ''`).join(',')}
].join('');
export { styles };
`;
nuxt.options.alias['#primevue-style'] = addTemplate({
filename: 'primevue-style.mjs',
getContents: styleContent
}).dst;
addPlugin(resolver.resolve('./runtime/plugin.client'));
addPluginTemplate({
filename: 'primevue-plugin.mjs',
getContents() {
return `
import { defineNuxtPlugin, useRuntimeConfig } from '#imports';
${registered.config.map((config) => `import ${config.as} from '${config.from}';`).join('\n')}
${registered.services.map((service) => `import ${service.as} from '${service.from}';`).join('\n')}
${registered.directives.map((directive) => `import ${directive.as} from '${directive.from}';`).join('\n')}
${importPT ? `import ${importPT.as} from '${importPT.from}';\n` : ''}
export default defineNuxtPlugin(({ vueApp }) => {
const runtimeConfig = useRuntimeConfig();
const config = runtimeConfig?.public?.primevue ?? {};
const { usePrimeVue = true, options = {} } = config;
const pt = ${importPT ? `{ pt: ${importPT.as} }` : `{}`};
usePrimeVue && vueApp.use(PrimeVue, { ...options, ...pt });
${registered.services.map((service) => `vueApp.use(${service.as});`).join('\n')}
${registered.directives.map((directive) => `vueApp.directive('${directive.name}', ${directive.as});`).join('\n')}
});
`;
}
});
nuxt.hook('nitro:config', async (config) => {
config.externals = config.externals || {};
config.externals.inline = config.externals.inline || [];
config.externals.inline.push(resolver.resolve('./runtime/plugin.server'));
config.virtual = config.virtual || {};
config.virtual['#primevue-style'] = styleContent;
config.plugins = config.plugins || [];
config.plugins.push(resolver.resolve('./runtime/plugin.server'));
});
}
});

View file

@ -0,0 +1,157 @@
import { addComponent, addImports } from '@nuxt/kit';
import { components } from './runtime/core/components';
import { composables } from './runtime/core/composables';
import { directives } from './runtime/core/directives';
import { Utils } from './utils';
function registerItems(items = [], options = {}, params) {
const included = Utils.object.getValue(options.include, params);
const excluded = Utils.object.getValue(options.exclude, params);
return items.filter((item) => {
const name = item?.name;
const matchedIn = included === '*' || included === undefined ? true : Utils.object.isNotEmpty(included) ? included.some((inc) => name?.toLowerCase() === inc.toLowerCase()) : false;
const matchedEx = excluded === '*' ? true : Utils.object.isNotEmpty(excluded) ? excluded.some((exc) => name?.toLowerCase() === exc.toLowerCase()) : false;
return matchedIn && !matchedEx;
});
}
function registerConfig(resolvePath) {
return [
{
name: 'PrimeVue',
as: 'PrimeVue',
from: resolvePath({ name: 'PrimeVue', as: 'PrimeVue', from: `primevue/config`, type: 'config' })
}
];
}
function registerComponents(resolvePath, options = {}) {
const items = registerItems(components, options, { components });
return items.map((item) => {
const _item = { ...item, name: item.name, as: item.name, from: `primevue/${item.name.toLowerCase()}` };
const name = Utils.object.getName(_item, options);
const from = resolvePath({ name, as: _item.as, from: _item.from, type: 'component' });
const opt = {
export: 'default',
name,
filePath: from,
global: true
};
addComponent(opt);
return {
..._item,
...opt
};
});
}
function registerDirectives(resolvePath, options = {}) {
const items = registerItems(directives, options, { directives });
return items.map((item) => {
const name = Utils.object.getName(item, options);
const opt = {
...item,
name,
from: resolvePath({ name, as: item.as, from: item.from, type: 'directive' })
};
return opt;
});
}
function registerComposables(resolvePath, options = {}) {
const items = registerItems(composables, options, { composables });
return items.map((item) => {
const name = Utils.object.getName(item, options);
const opt = {
...item,
name,
from: resolvePath({ name, as: item.as, from: item.from, type: 'composable' })
};
addImports(opt);
return opt;
});
}
function registerServices(resolvePath, registered) {
const services = new Set();
registered?.components?.forEach((component) => component?.use && services.add(component.use.as));
return [...services].map((service) => ({
name: service,
as: service,
from: resolvePath({ name: service, as: service, from: `primevue/${service.toLowerCase()}`, type: 'service' })
}));
}
function registerStyles(resolvePath, registered, options) {
const styles = [
{
name: 'BaseStyle',
as: 'BaseStyle',
from: resolvePath({ name: 'BaseStyle', as: 'BaseStyle', from: 'primevue/base/style', type: 'style' })
}
];
if (!options?.unstyled) {
if (Utils.object.isNotEmpty(registered?.components)) {
styles.push({
name: 'BaseComponentStyle',
as: 'BaseComponentStyle',
from: resolvePath({ name: 'BaseComponentStyle', as: 'BaseComponentStyle', from: 'primevue/basecomponent/style', type: 'style' })
});
}
[registered.components, registered.directives]
.flat()
.reduce((acc, citem) => (acc.some((item) => item.as.toLowerCase() === citem.as.toLowerCase()) ? acc : [...acc, citem]), [])
.forEach((item) =>
styles.push({
name: `${item.as}Style`,
as: `${item.as}Style`,
from: resolvePath({ name: `${item.as}Style`, as: `${item.as}Style`, from: `primevue/${item.as.toLowerCase()}/style`, type: 'style' })
})
);
}
return styles;
}
function registerInjectStylesAsString(options) {
return [Utils.object.createStyleAsString(options.layerOrder ? `@layer ${options.layerOrder}` : undefined, { name: 'layer-order' })];
}
export function register(moduleOptions) {
const resolvePath = (resolveOptions) => Utils.object.getPath(moduleOptions.resolvePath, resolveOptions);
const config = registerConfig(resolvePath);
const components = registerComponents(resolvePath, moduleOptions.components);
const directives = registerDirectives(resolvePath, moduleOptions.directives);
const composables = registerComposables(resolvePath, moduleOptions.composables);
const registered = {
components,
directives,
composables
};
const services = registerServices(resolvePath, registered);
const styles = registerStyles(resolvePath, registered, moduleOptions.options);
const injectStylesAsString = registerInjectStylesAsString(moduleOptions);
return {
config,
...registered,
services,
styles,
injectStylesAsString
};
}

View file

@ -0,0 +1,48 @@
const form = [
'AutoComplete',
'Calendar',
'CascadeSelect',
'Checkbox',
'Chips',
'ColorPicker',
'Dropdown',
'Editor',
'InputMask',
'InputNumber',
'InputSwitch',
'InputText',
'Knob',
'Listbox',
'MultiSelect',
'Password',
'RadioButton',
'Rating',
'SelectButton',
'Slider',
'Textarea',
'ToggleButton',
'TreeSelect',
'TriStateCheckbox'
];
const button = ['Button', 'SpeedDial', 'SplitButton'];
const data = ['Column', 'Row', 'ColumnGroup', 'DataTable', 'DataView', 'DataViewLayoutOptions', 'OrderList', 'OrganizationChart', 'Paginator', 'PickList', 'Tree', 'TreeTable', 'Timeline', 'VirtualScroller'];
const panel = ['Accordion', 'AccordionTab', 'Card', 'DeferredContent', 'Divider', 'Fieldset', 'Panel', 'ScrollPanel', 'Splitter', 'SplitterPanel', 'TabView', 'TabPanel', 'Toolbar'];
const overlay = [{ name: 'ConfirmDialog', use: { as: 'ConfirmationService' } }, { name: 'ConfirmPopup', use: { as: 'ConfirmationService' } }, 'Dialog', { name: 'DynamicDialog', use: { as: 'DialogService' } }, 'OverlayPanel', 'Sidebar'];
const file = ['FileUpload'];
const menu = ['Breadcrumb', 'ContextMenu', 'Dock', 'Menu', 'Menubar', 'MegaMenu', 'PanelMenu', 'Steps', 'TabMenu', 'TieredMenu'];
const chart = ['Chart'];
const messages = ['Message', 'InlineMessage', { name: 'Toast', use: { as: 'ToastService' } }];
const media = ['Carousel', 'Galleria', 'Image'];
const misc = ['Avatar', 'AvatarGroup', 'Badge', 'BlockUI', 'Chip', 'Inplace', 'ScrollTop', 'Skeleton', 'ProgressBar', 'ProgressSpinner', 'Tag', 'Terminal'];
export const components = [...form, ...button, ...data, ...panel, ...overlay, ...file, ...menu, ...chart, ...messages, ...media, ...misc].map((c) => (typeof c === 'string' ? { name: c } : c));

View file

@ -0,0 +1 @@
export const composables = [{ name: 'useStyle', as: 'useStyle', from: 'primevue/usestyle' }];

View file

@ -0,0 +1,8 @@
export const directives = [
{ name: 'badge', as: 'BadgeDirective', from: 'primevue/badgedirective' },
{ name: 'tooltip', as: 'Tooltip', from: 'primevue/tooltip' },
{ name: 'ripple', as: 'Ripple', from: 'primevue/ripple' },
{ name: 'styleclass', as: 'StyleClass', from: 'primevue/styleclass' },
{ name: 'focustrap', as: 'FocusTrap', from: 'primevue/focustrap' },
{ name: 'animate', as: 'Animate', from: 'primevue/animate' }
];

View file

@ -0,0 +1,3 @@
import { defineNuxtPlugin } from 'nuxt/app';
export default defineNuxtPlugin(({ vueApp }) => {});

View file

@ -0,0 +1,11 @@
// @ts-expect-error
import { styles } from '#primevue-style';
//import { useRuntimeConfig } from '#imports';
const defineNitroPlugin = (def) => def;
export default defineNitroPlugin(async (nitroApp) => {
nitroApp.hooks.hook('render:html', (html) => {
html.head.push(styles);
});
});

View file

@ -0,0 +1,34 @@
export const Utils = {
object: {
isEmpty(value) {
return value === null || value === undefined || value === '' || (Array.isArray(value) && value.length === 0) || (!(value instanceof Date) && typeof value === 'object' && Object.keys(value).length === 0);
},
isNotEmpty(value) {
return !this.isEmpty(value);
},
isFunction(value) {
return !!(value && value.constructor && value.call && value.apply);
},
isString(value, empty = true) {
return typeof value === 'string' && (empty || value !== '');
},
getValue(obj, ...params) {
return this.isFunction(obj) ? obj(...params) : obj;
},
getName(item, options) {
return this.isFunction(options?.name) ? options.name(item) : `${options.prefix}${item.name}`;
},
getPath(fn, options) {
return this.isFunction(fn) ? fn(options) : options.from;
},
createStyleAsString(css, options = { name: '' }) {
if (css) {
const { name, ...rest } = options;
return `'<style type="text/css" data-primevue-style-id="${name}"${Object.entries(rest).reduce((s, [k, v]) => s + `${k}="${v}"`, ' ')}>${css}</style>'`;
}
return '';
}
}
};