Skip to content

Commit

Permalink
feat: support third party libraries (#628)
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat authored Jun 17, 2022
1 parent 389cb6a commit fc5e6b9
Show file tree
Hide file tree
Showing 54 changed files with 1,187 additions and 293 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"private": true,
"name": "qwik-monorepo",
"version": "0.0.26",
"version": "0.0.27",
"scripts": {
"build": "yarn node scripts --tsc --build --api --platform-binding-wasm-copy",
"build.full": "yarn node scripts --tsc --build --api --eslint --qwikcity --platform-binding --wasm",
Expand Down
19 changes: 17 additions & 2 deletions packages/create-qwik/api/generate-starter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ function generateUserStarter(

if (starterServer) {
const serverPkgJson = readPackageJson(starterServer.dir);
const vite = serverPkgJson.qwik?.vite;
const vite = serverPkgJson.__qwik__?.vite;
replacements.push([/\/\* VITE_IMPORTS \*\//g, vite?.VITE_IMPORTS ?? '']);
replacements.push([/\/\* VITE_CONFIG \*\//g, vite?.VITE_CONFIG ?? '']);
replacements.push([/\/\* VITE_QWIK \*\//g, vite?.VITE_QWIK ?? '']);
Expand All @@ -76,6 +76,21 @@ function generateUserStarter(
const pkgJson = readPackageJson(baseApp.dir);
const starterPkgJson = readPackageJson(starterApp.dir);
mergePackageJSONs(pkgJson, starterPkgJson);
const replaceProps = [
'version',
'private',
'main',
'module',
'qwik',
'types',
'exports',
'files',
];
for (const prop of replaceProps) {
if (starterPkgJson[prop] !== undefined) {
pkgJson[prop] = starterPkgJson[prop];
}
}

let readmeContent = baseApp.readme!.trim() + '\n\n';

Expand Down Expand Up @@ -164,7 +179,7 @@ function cleanPackageJson(srcPkg: PackageJSON) {
Object.keys(cleanedPkg).forEach((prop) => {
delete (srcPkg as any)[prop];
});
delete srcPkg.qwik;
delete srcPkg.__qwik__;

const sortedKeys = Object.keys(srcPkg).sort();
for (const key of sortedKeys) {
Expand Down
5 changes: 3 additions & 2 deletions packages/create-qwik/api/get-starters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ function loadStarterData(startersDir: string, dirName: string) {
description: pkgJson.description ?? '',
readme,
dir: dataDir,
priority: pkgJson?.qwik?.priority ?? 0,
featureOptions: pkgJson?.qwik?.featureOptions ?? [],
selectServer: pkgJson?.__qwik__?.selectServer ?? true,
priority: pkgJson?.__qwik__?.priority ?? 0,
featureOptions: pkgJson?.__qwik__?.featureOptions ?? [],
};
return data;
})
Expand Down
8 changes: 6 additions & 2 deletions packages/create-qwik/interface/interactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export async function runInteractive() {
},
},
{
type: 'select',
type: () => {
const selected = starters.apps.find((a) => a.id === opts.appId);
return selected?.selectServer ? 'select' : null;
},
name: 'serverId',
message: 'Select a server',
choices: () => {
Expand Down Expand Up @@ -83,7 +86,8 @@ export async function runInteractive() {
const featureOptions = [...starter!.featureOptions];
return featureOptions.map((featureId) => {
const f = starters.features.find((f) => f.id === featureId)!;
return { title: f.name, value: f.id, description: f.description, selected: true };
const selected = f.id !== 'tailwindcss';
return { title: f.name, value: f.id, description: f.description, selected };
});
},
format: (featureIds: string[]) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/create-qwik/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-qwik",
"version": "0.0.26",
"version": "0.0.27",
"description": "Interactive CLI and API for generating Qwik projects.",
"bin": "create-qwik",
"main": "index.js",
Expand Down
1 change: 1 addition & 0 deletions packages/create-qwik/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface StarterData {
description: string;
readme: string | null;
dir: string;
selectServer: boolean;
priority: number;
featureOptions: string[];
}
2 changes: 1 addition & 1 deletion packages/eslint-plugin-qwik/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "eslint-plugin-qwik",
"version": "0.0.26",
"version": "0.0.27",
"description": "An Open-Source sub-framework designed with a focus on server-side-rendering, lazy-loading, and styling/animation.",
"main": "index.js",
"author": "Builder Team",
Expand Down
1 change: 1 addition & 0 deletions packages/qwik-city/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "Static Site Generator for Qwik",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"qwik": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"scripts": {
"test": "uvu -r tsm src/vite/tests"
Expand Down
2 changes: 1 addition & 1 deletion packages/qwik/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@builder.io/qwik",
"version": "0.0.26",
"version": "0.0.27",
"description": "An Open-Source sub-framework designed with a focus on server-side-rendering, lazy-loading, and styling/animation.",
"main": "./dist/core.cjs",
"module": "./dist/core.mjs",
Expand Down
2 changes: 1 addition & 1 deletion packages/qwik/src/core/render/cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -640,7 +640,7 @@ const PROP_HANDLER_MAP: Record<string, PropHandler> = {

const ALLOWS_PROPS = ['class', 'className', 'style', 'id', 'q:slot'];
const HOST_PREFIX = 'host:';
const SCOPE_PREFIX = /^(host|window|document):/;
const SCOPE_PREFIX = /^(host|window|document|prevent(d|D)efault):/;

export const updateProperties = (
rctx: RenderContext,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface QwikProps {
'q:version'?: string;
'q:container'?: '';
[key: `preventDefault:${string}`]: boolean;
[key: `preventdefault:${string}`]: boolean;
}

/**
Expand Down Expand Up @@ -206,6 +207,9 @@ export interface ComponentBaseProps {
[key: `window:on${string}$`]: EventHandler | undefined;
[key: `window:on${string}Qrl`]: QrlEvent | QrlEvent[] | undefined;

[key: `preventDefault:${string}`]: boolean;
[key: `preventdefault:${string}`]: boolean;

children?: JSXChildren;
}
export interface QwikAttributes extends QwikProps, QwikEvents {}
Expand Down
10 changes: 6 additions & 4 deletions packages/qwik/src/core/render/render.unit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ describe('render', () => {
});

it('should render attributes', async () => {
await render(fixture.host, <div id="abc" title="bar" preventDefault:click></div>);
await expectRendered(<div title="bar" id="abc"></div>);
await render(fixture.host, <div id="abc" title="bar" preventdefault:click></div>);
await expectRendered(<div title="bar" id="abc" preventdefault:click></div>);
});

it('should render style only for defined attributes', async () => {
Expand Down Expand Up @@ -149,9 +149,9 @@ describe('render', () => {

describe('component', () => {
it('should render a component', async () => {
await render(fixture.host, <HelloWorld name="World" />);
await render(fixture.host, <HelloWorld name="World" preventdefault:click />);
await expectRendered(
<hello-world>
<hello-world preventdefault:click>
<span>
{'Hello'} {'World'}
</span>
Expand All @@ -175,6 +175,7 @@ describe('render', () => {
host:on-ClicK$={() => {}}
document:onLoad$={() => {}}
window:onScroll$={() => {}}
preventDefault:click
/>
);
await expectRendered(
Expand All @@ -191,6 +192,7 @@ describe('render', () => {
on:-clic-k="/runtimeQRL#*"
on-document:load="/runtimeQRL#*"
on-window:scroll="/runtimeQRL#*"
preventdefault:click
>
<span>{'{"thing":"World"}'}</span>
</render-props>
Expand Down
5 changes: 3 additions & 2 deletions packages/qwik/src/optimizer/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,11 @@ fn optimize(
optimizer_input: OptimizerInput,
) -> Result<qwik_core::TransformOutput, Box<dyn std::error::Error>> {
let current_dir = std::env::current_dir()?;
let root_dir = current_dir.join(optimizer_input.src).canonicalize()?;
let src_dir = current_dir.join(optimizer_input.src).canonicalize()?;

let result = transform_fs(TransformFsOptions {
root_dir: root_dir.to_string_lossy().to_string(),
src_dir: src_dir.to_string_lossy().to_string(),
vendor_roots: vec![],
glob: optimizer_input.glob,
source_maps: optimizer_input.sourcemaps,
minify: optimizer_input.minify,
Expand Down
2 changes: 1 addition & 1 deletion packages/qwik/src/optimizer/core/benches/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ fn transform_todo_app(b: &mut Bencher) {
});
"#;
transform_modules(TransformModulesOptions {
root_dir: "/user/qwik/src/".into(),
src_dir: "/user/qwik/src/".into(),
input: vec![TransformModuleInput {
code: code.into(),
path: "file.tsx".into(),
Expand Down
46 changes: 19 additions & 27 deletions packages/qwik/src/optimizer/core/src/code_move.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::words::*;
use std::collections::BTreeMap;
use std::path::Path;

use anyhow::{format_err, Context, Error};
use anyhow::{Context, Error};
use path_slash::PathExt;
use swc_atoms::JsWord;
use swc_common::comments::{SingleThreadedComments, SingleThreadedCommentsMap};
Expand All @@ -27,12 +27,12 @@ pub struct NewModuleCtx<'a> {
pub expr: Box<ast::Expr>,
pub path: &'a PathData,
pub name: &'a str,
pub origin: &'a str,
pub local_idents: &'a [Id],
pub scoped_idents: &'a [Id],
pub global: &'a GlobalCollect,
pub is_entry: bool,
pub need_handle_watch: bool,
pub need_transform: bool,
pub leading_comments: SingleThreadedCommentsMap,
pub trailing_comments: SingleThreadedCommentsMap,
}
Expand All @@ -49,7 +49,8 @@ pub fn new_module(ctx: NewModuleCtx) -> Result<(ast::Module, SingleThreadedComme
shebang: None,
};

let use_lexical_scope = if !ctx.scoped_idents.is_empty() {
let has_scoped_idents = ctx.need_transform && !ctx.scoped_idents.is_empty();
let use_lexical_scope = if has_scoped_idents {
let new_local = id!(private_ident!(&USE_LEXICAL_SCOPE.clone()));
module
.body
Expand Down Expand Up @@ -93,7 +94,11 @@ pub fn new_module(ctx: NewModuleCtx) -> Result<(ast::Module, SingleThreadedComme
asserts: None,
src: ast::Str {
span: DUMMY_SP,
value: fix_path(ctx.origin, "a", import.source.as_ref())?,
value: fix_path(
&ctx.path.abs_dir,
&ctx.path.base_dir,
import.source.as_ref(),
)?,
raw: None,
},
specifiers: vec![specifier],
Expand All @@ -112,7 +117,11 @@ pub fn new_module(ctx: NewModuleCtx) -> Result<(ast::Module, SingleThreadedComme
asserts: None,
src: ast::Str {
span: DUMMY_SP,
value: fix_path(ctx.origin, "a", &format!("./{}", ctx.path.file_stem))?,
value: fix_path(
&ctx.path.abs_dir,
&ctx.path.base_dir,
&format!("./{}", ctx.path.file_stem),
)?,
raw: None,
},
specifiers: vec![ast::ImportSpecifier::Named(ast::ImportNamedSpecifier {
Expand Down Expand Up @@ -151,24 +160,8 @@ pub fn fix_path<S: AsRef<Path>, D: AsRef<Path>>(
) -> Result<JsWord, Error> {
let src = src.as_ref();
let dest = dest.as_ref();
let src_str = src.to_slash_lossy();
let dest_str = dest.to_slash_lossy();

if src_str.starts_with('/') {
return Err(format_err!(
"`fix_path`: `src` doesn't start with a slash: {}",
src_str
));
}

if ident.starts_with('.') {
let diff = pathdiff::diff_paths(
src.parent()
.with_context(|| format!("`fix_path`: `src` doesn't have a parent: {}", src_str))?,
dest.parent().with_context(|| {
format!("`fix_path`: `dest` doesn't have a parent: {}", dest_str)
})?,
);
let diff = pathdiff::diff_paths(src, dest);

if let Some(diff) = diff {
let normalize = diff.to_slash_lossy();
Expand Down Expand Up @@ -209,24 +202,23 @@ fn create_named_export(expr: Box<ast::Expr>, name: &str) -> ast::ModuleItem {
#[test]
fn test_fix_path() {
assert_eq!(
fix_path("src/components.tsx", "a", "./state").unwrap(),
fix_path("src", "", "./state").unwrap(),
JsWord::from("./src/state")
);

assert_eq!(
fix_path("src/path/components.tsx", "a", "./state").unwrap(),
fix_path("src/path", "", "./state").unwrap(),
JsWord::from("./src/path/state")
);

assert_eq!(
fix_path("src/components.tsx", "a", "../state").unwrap(),
fix_path("src", "", "../state").unwrap(),
JsWord::from("./state")
);
assert_eq!(
fix_path("components.tsx", "a", "./state").unwrap(),
fix_path("a", "a", "./state").unwrap(),
JsWord::from("./state")
);
assert!(fix_path("/components", "a", "./state").is_err())
}

pub fn generate_entries(
Expand Down
Loading

0 comments on commit fc5e6b9

Please sign in to comment.