Giter Site home page Giter Site logo

kitajs / html Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nicojs/typed-html

500.0 500.0 28.0 1.71 MB

๐Ÿ›๏ธ Super fast JSX runtime to generate HTML strings that works everywhere. If it supports string we got you covered.

Home Page: http://kita.js.org/discord

License: Apache License 2.0

TypeScript 10.23% JavaScript 2.09% Shell 0.02% HTML 87.67%
generator html jsx safe tsx type typesafe typescript

html's Introduction

Using this package? Please consider donating to support my open source work โค๏ธ
Help kitajs grow! Star and share this amazing repository with your friends and co-workers!


Kita JS logo


Discord License Codecov Last commit Stars


๐ŸŒท KitaJS

KitaJS is a routing meta framework.


๐ŸŽ‰ Kita is officially Stable! Try it out today!


Star History

Star History Chart

All Thanks To Our Contributors:

html's People

Contributors

adicco avatar aralroca avatar arkahnx avatar arthurfiorette avatar b-r-p avatar bebraw avatar danielo515 avatar dependabot[bot] avatar derekhawker avatar deriegle avatar douglasduteil avatar eejit43 avatar ethanniser avatar florentulve avatar gabor-s avatar jacopopatroclo avatar jeaciaz avatar karurochori avatar keuller avatar mthmulders avatar nicojs avatar nsaunders avatar romainlanz avatar shakdoesgithub avatar tpguy825 avatar tqhoughton avatar wrapperup avatar yvvki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

html's Issues

hx-sync attribute type error

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

  • "@kitajs/html": "^3.0.10"
  • "typescript": "^5.0.0"

Description

When setting hx-sync to this:replace, which is a valid value according to htmx's docs, I encounter the following TypeScript error:

image

Is it because of the way the HxSync union is defined?

Steps to Reproduce

<textarea hx-sync="this:replace"></textarea>

Expected Behavior

No TypeScript error is raised when hx-sync is set to this:replace

Possibly incorrect detection for conditional elements

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Saw kitajs/ts-html-plugin#24, feels like this is still a problem

Versions

1.3.3

Description

No errors:

<Icon icon={icon} size={size} />

K601

{!hideIcon && <Icon icon={icon} size={size} />}

Steps to Reproduce

example above

Expected Behavior

Should have no errors

{!hideIcon && <Icon icon={icon} size={size} />}

Support `.` in attribute names

Problem

I am trying to use Alpine JS for a bit of client-side interactivity and it has directives that use syntax that are not supported. I was able to bypass some of them, but there is no way around some of them. For example,

<input @click="...">

could be updated to work as

<input x-on:click="...">

but something like:

<input x-on:keyup.enter="...">

is not possible to include because of the . and Alpine does not provide alternatives.

Suggestion

It would be great to provide support for this. Or maybe provide a way to escape illegal characters.

{false && <div>Render</div>} pattern is broken.

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

Issue noticed on 4.1.0, on 3.0.10 it worked fine.

Description

This could be an intentional change, but as the title says, {false && <div>Render</div>} renders the text false in the DOM. My expectation would be that nothing is rendered.

Steps to Reproduce

{false && <div>Render</div>}

Expected Behavior

Nothing is rendered to the DOM

Need a way to add scripts that doesn't get transpiled

"Hello,

I am using this (Kitajs) to transpile JSX into HTML on the server and send it to the client. The issue I face while doing that is that I can't add JavaScript (for the client-side). For example, if I just use <script>console.log("hi, mom")</script>, it just throws an error. So, to avoid this, I have to write JavaScript (for the client-side) as a string inside <script> tags.

This is how I'm doing it:

<script>
{`
  authModal.close()
  authModal.showModal()

  authModal.addEventListener("click", (e) => {
    const dialogDimensions = authModal.getBoundingClientRect();
    if (
      e.clientX < dialogDimensions.left ||
      e.clientX > dialogDimensions right ||
      e.clientY < dialogDimensions.top ||
      e.clientY > dialogDimensions.bottom
    ) {
      authModal.remove();
    }
  });

  document.getElementById('basic-details').childNodes.forEach((field) => {
    field.addEventListener("input", () => (document.querySelector('[value=""]').style.pointerEvents = document.getElementById('basic-details').checkValidity() ? "none" : "auto"));
  });

  function saveAsCookie(e) {
    e.preventDefault();

    const name = e.target.name.value;
    const phone = e.target.phone.value;
    const city = e.target.city.value;
    const college = e.target.college.value;

    const d = new Date();
    d.setTime(d.getTime() + 60 * 60 * 1000);
    let expires = "expires=" + d.toUTCString();
    document.cookie = \`formData=\${JSON.stringify({ name, phone, city, college })}; expires=\${expires}; path=/\`;
  }
`}
</script>

I'm doing this without syntax highlighting or IntelliSense. Is there a better way?

[question] Recommended strategies to pass context

Seeing as a library like this will be used as a (lightweight) templating engine, I wonder what strategies could be used to inject context into a template to prevent property drilling.

Example use cases:

  • Passing theme
  • Passing localization

I've searched for some packages that provide a similar feature for rendering JSX to HTML without React in the mix:

I would love to hear your thoughts on this @arthurfiorette

console.log(<div>{'<' + '/div>'}</div>); not erroring on codespaces

Prerequisites

  • I have searched existing issues to ensure the bug has not already been reported

  • I have written a descriptive issue title

Versions

Only tested on latest versions as of Dec 19, 2023

Description

It doesn't seem like the xss vsCode extension is working. Additionally I don't think the xss-scan command is working as it does not seem to catch very obvious xss vulnerabilities (see below)

image

Steps to Reproduce

  1. Open https://github.com/kitajs/minimal-example?tab=readme-ov-file in a codespace
  2. paste in console.log(<div>{'<' + '/div>'}</div>);

Expected Behavior

The above should error based on what I have read in the readme here but it does not seem to have any effect.

Expose JSX.HtmlTag.style type under html namespace

It would be nice if you exposed the JSX.HtmlTag.style type, which can then be easily used for components where you want styling to be able to be parsed down from the invocation.

Currently to implement a basic component with some lowering of attributes from caller ends up looking like this:

import type * as CSS from 'csstype';
import html from '@kitajs/html';

export function Link(props: html.PropsWithChildren<{
	to: string,
	class?: string,
	style?: string | CSS.Properties<0 | (string & {}), string & {}>,
	target?: string
}>) {
	return <a
		target={props.target || ""}
		class={props.class || ""}
		style={props.style || ""}
		href={props.to}
		hx-get={props.to}
		// Chrome doesn't support 'Vary' headers for effective caching
		hx-headers='{"Cache-Control": "no-cache"}'
	>{props.children}</a>
}

When the signature could be written more simply like below if the type was exposed by the library

export function Link(props: html.PropsWithChildren<{
	to: string,
	class?: string,
	style?: html.CSSProperty,
	target?: string
}>)

Avoid escaping hx-vals

Thank you for this great plugin, which I have been using successfully on a Bun/Elysia/HTMX stack. I have not managed yet to use HTMX's hx-vals as attributes are encoded and so this mangles the output hx-vals attribute:

<div 
hx-swap="outerHTML"
hx-target="closest div"
hx-post="/edit/current_request/del_item/y5ktrpj4euvzfy0kr8cob0ji"
hx-vals="{&quot;type&quot;:&quot;list&quot;}"></div>

Would there be a way to have some kind of "unsafe" mode for some attributes whereby their values could be raw? Thank you!

[question] Is there an elegant way to pass a script tag with a component?

I did some tests and tried to pass a script tag inside a component. It seems it strips out the curly brackets from within the tag:

<script>function click(){console.log('test')}</script> transformed to <script>function click()</script>

but this worked:

<script>{"function click(){console.log('test')}"}</script>

But in both cases there was no syntax highlighting... I'm just exploring the prospects of getting rid of React for my next project and this library seems to be very promising approach.

Add `onchange` and `oninput` events for the `select` tag

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

3.1.2

Description

There's no onchange and oninput event in the typings of HmtlSelectTag.

Steps to Reproduce

html/jsx.d.ts

Line 448 in 9ca8cdf

interface HtmlSelectTag extends HtmlTag {

Expected Behavior

No response

Improve `compile` declaration to avoid having to manually add `<typeof function>` as a generic parameters.

love the new compile api, super cool how thats able to be done with Proxy
its great to just be able to pass in a clean component, and get out a new compiled one that type wise is identical

however I ran into some strange type issues (errors in comment of gist)

This might be solved by explicitly passing a generic, but the dx is so much better when that isnt necessary

After messing around a bit I refactored the type for compile and ended up with this

type StringPropsOnly<P> = {
  [K in keyof P]: string;
};

declare function myCompiled<P extends StringPropsOnly<P>>(
  this: void,
  component: (props: P) => JSX.Element,
  strict?: boolean,
  separator?: string
): (props: P) => JSX.Element;

which resolved all of the issues I had


The existing type still supports passing a tuple or record of strings, which I am assuming is a remnant from the old API.

Curious to your thoughts on this, but I think we should drop support for that, and just rely on inference from the function


thanks!

esbuild fails to use proposed `html` namespace

When using the proposed tsconfig.json esbuild compiles in a way that attempts to use React.createElement to generate elements instead of the html.createElement namespace. This then results in an error because React is not defined anywhere.

I'm not sure of the exact issue, but changing the config to this fixes the issue:

{
	"compilerOptions": {
		"jsx": "react",
		"jsxFactory": "elements.createElement",
		"jsxFragmentFactory": "elements.Fragment",
	}
}

With just this commit I got my server from runtime erroring attempting to use React, to actually using the library properly.
This issue only occurs when a tsx file is compiled using esbuild instead of tsc
IDK if you want to just update the docs to mimic my config, or diagnose the issue root issue, but it's up ot you

Feature Request: Support arbitrary attribute mutations, possibly at compile-time

I have a use case where I want to automatically spread certain attributes, like so:

const onClick: Htmx.Attributes = {
    'hx-get': '/api',
};

return <div {...onClick}/>;

I would love to be able to instead write this as:

return <div htmx={onClick}/>

and then somehow have a parser translate the htmx attribute into spreading the props after the fact.

Right now the types are extendable, but is it possible to add a piece of functionality to an attribute? Pseudocode for what I'm looking for

registerAttributeBehavior(props => {
    if (!'htmx' in props) {
        return props;
    }

    const htmxProp = props.htmx;
    delete props['htmx'];
    props = {...props, ...htmxProps};
    return props;
});

but hopefully this sort of translation can be done at compile time rather than runtime.

Related to #132, as I want to be intentional with naming htmx attributes in my components, rather than use the spread operator.

Vitejs - ReferenceError: Html is not defined (Import Html on every file?)

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

"@kitajs/html": "^3.0.10",
"@kitajs/ts-html-plugin": "^1.3.3",

Description

Hi, first thanks to produce this lib, it's very usefull for the stack I want to use โค๏ธ

I'm actually using it with Vite js, all works fine on development.
I registred globally kita on entry-server.tsx, which is the main entry.
image

But when I build my project and start it, I got this error.
image

This is a part of the code I got /dist folder

image

The only way found to fix the problem is to: import { Html } from '@kitajs/html'; on every .tsx files.
Which not is not convenient.

There is a way to import this Html globally?

Steps to Reproduce

//tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": [
      "ES2020",
      "DOM",
      "DOM.Iterable"
    ],
    "skipLibCheck": true,
    /* Bundler mode */
    "moduleResolution": "Bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    /* Kita */
    "jsx": "react",
    "jsxFactory": "Html.createElement",
    "jsxFragmentFactory": "Html.Fragment",
    "plugins": [
      {
        "name": "@kitajs/ts-html-plugin"
      }
    ]
  },
  "include": [
    "src"
  ]
}

Expected Behavior

No response

`CleanProps` is not exported

What expected?

import { CleanProps } from "@kitajs/html"

function Clean(props: CleanProps<{ repeated: string }>) {
  return <div>{props.repeated}</div>
}

Issue

CleanProps type is not available.

getting VS Code to like JSX

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

"@kitajs/html": "^3.0.11",
"@kitajs/ts-html-plugin": "^1.3.3",

Description

VS Code doesn't like my use of JSX when I use this library. Here is a screenshot:

Screenshot 2024-01-19 at 9 30 14โ€ฏAM

Here is my tsconfig.json file:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "strict": true,
    "jsx": "react",
    "jsxFactory": "Html.createElement",
    "jsxFragmentFactory": "Html.Fragment",
    "plugins": [{"name": "@kitajs/ts-html-plugin"}]
  }
}

If I change tsconfig.json to the following, VS Code stops complaining about the JSX, but then I'm not using this library:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "strict": true,
    "jsx": "react-jsx",
    "jsxImportSource": "hono/jsx"
  }
}

Here is the complete source file, index.tsx:

import {Hono} from 'hono';
import type {Context} from 'hono';
import type {FC} from 'hono/jsx';
import {Html} from '@kitajs/html';

const app = new Hono();

const BaseHtml: FC = ({children}) => (
  <html>
    <head>
      <title>Endpoint Returning Script</title>
      <script src="https://unpkg.com/[email protected]"></script>
      <script>console.log('Hello, World!');</script>
    </head>
    <body>{children}</body>
  </html>
);

app.get('/', (c: Context) => {
  return c.html(
    <BaseHtml>
      <h1>Endpoint Returning Script</h1>
    </BaseHtml>
  );
});

export default app;

Steps to Reproduce

Open the source file above in VS Code.

Expected Behavior

VS Code should not complain about the JSX in this source file.

Types compilation errors

Hello, thanks for your effort in maintaining and improving this library.

If I m running tsc without "skipLibCheck": true I m getting some type errors coming from index.d.ts

node_modules/.pnpm/@[email protected]/node_modules/@kitajs/html/index.d.ts(17,10): error TS1038: A 'declare' modifier cannot be used in an already ambient context.
node_modules/.pnpm/@[email protected]/node_modules/@kitajs/html/index.d.ts(122,10): error TS1038: A 'declare' modifier cannot be used in an already ambient context.
node_modules/.pnpm/@[email protected]/node_modules/@kitajs/html/index.d.ts(122,28): error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.
node_modules/.pnpm/@[email protected]/node_modules/@kitajs/html/index.d.ts(124,10): error TS1038: A 'declare' modifier cannot be used in an already ambient context.
node_modules/.pnpm/@[email protected]/node_modules/@kitajs/html/index.d.ts(132,10): error TS1038: A 'declare' modifier cannot be used in an already ambient context.
node_modules/.pnpm/@[email protected]/node_modules/@kitajs/html/index.d.ts(134,10): error TS1038: A 'declare' modifier cannot be used in an already ambient context.

JSX.Element definition lacks some types that do compile.

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

@elysiajs/[email protected], I understand this is built using this package.

Description

The current JSX.Element definition causes errors to be thrown when including some types in JSX: number | boolean | null | undefined. However, JSX such as the following...

<div>
    {1}
    {undefined}
    { possiblyFalse() && "Hi mom" }
</div>

...runs as expected despite throwing IDE type errors.

Steps to Reproduce

See description

Expected Behavior

See description; expected no type errors to be thrown for given types.

Support for Context

Hi! Thanks for this library and the work you have put into it! Given your knowledge about this project it would be possible to create a "react like" context implementation?

I would love to make a PR.
I already kind of implemented something like that in this fastify plugin https://github.com/JacopoPatroclo/cose/blob/main/packages/fastify-jsx/src/lib/context.tsx but it's not convincing. It requires to handle children as a function to postpone their execution in order to give them access to the context. I'm sure there is a better way to do it. What are your thoughts @arthurfiorette ?

Include a typescript plugin to emit warnings on unsanitized user input.

Its easy to forget to add safe on user input, which easily allows XSS attacks to happen almost everywhere. We could help by creating a typescript plugin or maybe an eslint rule to help emit warnings.

function UserCard({ name, age, birth }) {
  const safeName = name;
  const shouldEscape = <h1>{name}</h1>

  return (
    <>
      // this line works as normal
      <h1 safe>{name}</h1>
      // this line emits a warning of unsanitized user input
      <h1>{name}</h1>
      // this line should not emit warnings because variable starts with safe keyword
      <h1>{safeName}</h1>
      // this line emits warnings because safe was used on a non pure string child
      <div safe><h1>{name}</h1></div>
      // this line should not emit warnings because inner html was extracted to another variable
      <h1 safe>{shouldEscape}</h1>
      // this line should not emit warnings because age isn't of type string
      <div>{age}</div>
      // this line should not emit warnings because its variable isnt of type string,
      // (even if there are methods called)
      <div>{birth.toISOString()}</div>
    </>
  )
}

This typescript doc page can clarify on how to build it:

https://www.typescriptlang.org/tsconfig#plugins

No "alpine" exported on npm

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

  • 3.1.2
  • all

Description

On the published package https://www.npmjs.com/package/@kitajs/html/v/3.1.2?activeTab=code
CleanShot 2024-03-19 at 22 04 40@2x
There's no exported alpine.d.ts and alpine.js files that appears in the github repo.

Steps to Reproduce

try to add "types": ["@kitajs/html/alpine.d.ts"], to tsconfig.json and linter throws.

Expected Behavior

No response

Cannot find module '@kitajs/html/jsx-runtime' or its corresponding type declarations with NodeJS and module package

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

kitajs/html: 4.1.0
typescript: 5.4.5
node: 22.0.0

Description

Cannot build a package with "type": "module" using tsc for NodeJS. Doing so seems to always result in the error Cannot find module '@kitajs/html/jsx-runtime' or its corresponding type declarations. I believe this is because the output is doing a deep import on a jsx-runtime without a file extension.

I do not believe this is a duplicate of #150 even though it looks very similar. In that case everyone commenting was using Bun as the runtime in this instance I'm using Node. Apologies if I'm doing something silly.

Steps to Reproduce

I've produced a repoduction at https://github.com/mattdean-digicatapult/kitajs-html-example. In short to reproduce checkout that repo and just do:

npm i
npm run build

build is just running tsc if you'd prefer

Expected Behavior

The build to succeed.

Attribute types are not checked if spread operator is used for passing props

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

Version being used: 3.0.10

Description

I want to create an object that satisfiesHtmx.Attributes, and pass that to a component using a spread operator. This functionally works, but if there is a misspelled attribute, the JSX parser does not show a parsing error.

Steps to Reproduce

The problem is that if I type this incorrectly like:

const childProps = {
    'hx-wrongspelling': '/myapi',
};

return <div {...childProps}/>

I don't receive a type error, whereas I correctly receive a type error in this case:

return <div hx-wrongspelling='/myapi'/>

Expected Behavior

A type error should show when an invalid HTML attribute is passed in via spread operator

Missing attribute formaction on button.

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

At the very least v3.1.2

Description

The valid attribute formaction for buttons is not defined in the interface of HtmlButtonTag
For reference.

Steps to Reproduce

<button  formaction={`something`}>Hello</button>

Expected Behavior

The field is properly handled.

`CSSProperties` type too permissive

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

v3.0.5

Description

The CSSProperties type currently accepts string, number, or boolean length values. (For reference: csstype's Properties interface)

However, it doesn't appear that the styleToString function actually handles numeric or boolean length values.

IMHO the easiest fix is probably just to change the TLength arg to simply string.

Steps to Reproduce

Try something like style={{ width: 100 }} and review the resulting HTML output.

Expected Behavior

The expected behavior for a numeric length value (judging by React's functionality, anyway) is for the resulting style attribute to be style="width: 100px". Since the px units aren't added implicitly here, a numeric length value shouldn't be allowed.

SVG viewBox broken

Using @kitajs/html, most of my SVG display incorrectly because of the viewBox attribute being transformed to view-box.

This route

app.get("/test", () => (
  <Layout>
    <button class="flex text-white bg-blue-600 rounded-full hover:bg-blue-500">
      <svg
        class="w-10 h-10"
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 20 20"
        fill="currentColor"
      >
        <path
          fillRule="evenodd"
          d="M10.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L12.586 11H5a1 1 0 110-2h7.586l-2.293-2.293a1 1 0 010-1.414z"
          clipRule="evenodd"
        />
      </svg>
    </button>
  </Layout>
));

Returns

...
<button class="flex text-white bg-blue-600 rounded-full hover:bg-blue-500">
  <svg class="w-10 h-10" xmlns="http://www.w3.org/2000/svg" view-box="0 0 20 20" fill="currentColor">
  <path fill-rule="evenodd" d="M10.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L12.586 11H5a1 1 0 110-2h7.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd"></path>
  </svg>
</button>
...

view-box is not recognized by Google chrome or Safari.

You can reproduce the behavior by replacing viewBox with view-box on play.tailwindcss.com

[Question] Is there a way to get a compilation manifest?

Greetings,

I recently started playing with this project and am super impressed!

Is there a way to obtain a compilation manifest of sorts?

For example, if I create a "layout" component that has many children components, I would love to be able to acquire a dependency tree (or a component tree rather).

-> Layout 
   -> Header
      -> Nav
   -> Footer
   -> Home
      -> Sidebar
         -> Nav
      -> Article

Is this possible at all?

Something like:

const manifest = Html.getManifest(<Layout />)

Thoughts?

Dialog tag definition is missing in JSX.IntrinsicElements

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

latest

Description

<dialog/> Tag is missing in jsx definition causing type errors.

ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog

Workaround

declare namespace JSX {
  interface IntrinsicElements {
    dialog: HtmlTag;
  }
}

Steps to Reproduce

Set a <dialog/> tag and linter will get angry.

Expected Behavior

no type errors

Htmx + safe attribute doesn't work

Have simple example of Elysia/html plugin, kita and htmx

Elysia endpoint

app.post('/clicked', ({ html }) => html(<script>alert("hacked!")</script>))

Component with htmx tags

const Component = () => (
	<button
		hx-post="/devtools/clicked"
		hx-trigger="click"
		hx-swap="innerHTML"
		safe
	>
		Click Me!
	</button>
)

results injecting and running js code...
maaaaaybe I need to sanitize it on server then?

Screenshot 2023-09-17 at 00 49 06

Can't execute bun build bundle

When running the bun bundler. I get this error :

$ bun run ./build/index.js
24813 | // node_modules/@kitajs/html/index.js
24814 | var require_html = __commonJS((exports, module) => {
24815 |   __export(exports, {
24816 |     toKebabCase: () => {
24817 |       {
24818 |         return $toKebabCase;
                   ^
ReferenceError: Can't find variable: $toKebabCase
      at toKebabCase (/Users/mohamed/Desktop/htmx/build/index.js:24818:15)
      at /Users/mohamed/Desktop/htmx/build/index.js:25160:20
      at /Users/mohamed/Desktop/htmx/build/index.js:36:71
      at /Users/mohamed/Desktop/htmx/build/index.js:27554:11

I don't know if it's a bun issue or a kitajs/html issue.

Here's the github repo : https://github.com/DrUse1/htmx

You can reproduce the error by cloning the repo and doing this command :

bun install | bun run build | bun run prod

Compilation issue with TypeScript in versions >= @kitajs/[email protected]

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

@kitajs/[email protected] and above

Description

I am experimenting @kitajs/html and @kitajs/ts-html-plugin in a NodeJS Express application serving HTMX, for using JSX in development.

The app is throwing the following TypeScript compilation error when I have installed version 3.0.4 or above

node_modules/@kitajs/html/suspense.d.ts:23:17 - error TS2304: Cannot find name 'WeakRef'.

23         stream: WeakRef<HtmlStream>;
                   ~~~~~~~

Found 1 error in node_modules/@kitajs/html/suspense.d.ts:23

I am not sure about the fix, but this seems to have started the issue - v3.0.3...v3.0.4#diff-7aa4473ede4abd9ec099e87fec67fd57afafaf39e05d493ab4533acc38547eb8R2

Steps to Reproduce

Initial Steps

  1. Clone the repo - https://github.com/haricane8133/htmx-jsx-express-stack
  2. npm ci

Build succeeds (@kitajs/[email protected] used)

  • npm run build

Build fails (@kitajs/[email protected] used)

Expected Behavior

No response

Cannot find module '@kitajs/html/jsx-runtime' or its corresponding type declarations.

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

{
	"dependencies": {
		"@kitajs/html": "3.1.2",
		"@kitajs/ts-html-plugin": "1.3.4",
	},
	"devDependencies": {
		"typescript": "5.4.2",
	}
}

Description

jsx-runtime is not installed/present in the html package.

image

Steps to Reproduce

  • Install dependencies.
  • Update tsconfig.json:
    {
      "extends": [
        "@tsconfig/strictest/tsconfig",
        "@tsconfig/node-lts/tsconfig",
      ],
      "compilerOptions": {
        "jsx": "react-jsx",
        "jsxImportSource": "@kitajs/html",
        "plugins": [
          {
            "name": "@kitajs/ts-html-plugin"
          }
        ]
      }
    }
  • Add code to test like in README:
    console.log(<div safe>{String.name}</div>);`
  • Hovering:
    Cannot find module '@kitajs/html/jsx-runtime' or its corresponding type declarations.ts(2307)
  • Compiling:
    Error: Cannot find module '@kitajs/html/jsx-runtime'

Expected Behavior

No response

Cannot set boolean value for 'selected' on 'option' html tag

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

"@kitajs/html": "^3.0.2"

Description

The selected property of option can only be set with a string:
<option selected={true}></option>
or
<option selected=true></option>
do give the following error:
Type 'boolean' is not assignable to type 'string'.ts(2322) jsx.d.ts(311, 5): The expected type comes from property 'selected' which is declared here on type 'HtmlOptionTag' (property) JSX.HtmlOptionTag.selected?: string | undefined

I've not found a way to disable it with just string values eg. "false", "".

If using the boolean value it works but raises the warning.

Steps to Reproduce

function Test() { return <option selected={true}>test</option>; }
returns correctly: test

But raises the typescript intellisense error

Expected Behavior

No response

Bun & Deno compatibility with `react-jsx` runtime

@arthurfiorette I feel that we should export both jsx and jsxDEV functions from the jsx-runtime file and also create a jsx-dev-runtime file. They should have the same signature, this should be an easy thing to do.

@7f8ddd you should open an issue to Bun about this. Bun should handle the difference between dev and prod when it bundles. For this library, the difference is zero but for something like React you should not use the dev mode in a prod build.

Originally posted by @JacopoPatroclo in #150 (comment)

Passing HtmlTag as a property to the JSX component?

Heyo!

Having great fun using this package in my project but I'm trying to use the HtmlTag types to pass as props, I would of assumed that ...rest would do the trick but it does not seem to, The types are happy from typescript end so I am unsure why its not appending the attributes.

type JSXKeys = keyof JSX.IntrinsicElements['div'];
type JSXValues = JSX.IntrinsicElements['div'][JSXKeys];

type ChatMessageItemProps = {
	message: string;
} & { [K in JSXKeys]?: JSXValues };

export const ChatMessageItem = html.compile(
	({ message, ...rest }: ChatMessageItemProps) => {
		console.log('went here');
		return (
			<div class="p-4" {...rest}>
				{message}
			</div>
		);
	}
);

And usage

ChatMessageItem({ message: 'token', 'sse-swap': 'token_data' })

Any help appriciated!

[question] How do I ignore XSS errors on custom JSX components?

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

"@kitajs/ts-html-plugin": "^1.3.4",

Description

Hi there,

first off, love the project. Has been absolutely flawless so far.

I read the following in your docs (https://kitajs.github.io/ts-html-plugin/#special-cases) :

Ternary and binary operations are evaluated in both sides separately and will throw errors if any of the sides is not safe, even their condition never gets hit at runtime.

I'm finding the XSS plugin exceedingly aggressive, finding errors where there shouldn't be. I'm hoping you can suggest some workarounds. Consider the following code:

<div class="body">
              {collection.website && (
                <Badge externalUrl={collection.website} symbol="website" />
              )}
              {collection.twitter && (
                <Badge externalUrl={collection.twitter} symbol="x" />
              )}
              {collection.discord && (
                <Badge externalUrl={collection.discord} symbol="discord" />
              )}
</div>

Each of these gets flagged as xss-prone content as in the screenshot (whether I use short-circuiting above or switch to ? : syntax makes no difference.) This doesn't feel like the intention behind the plugin at all.

I tried escaping the content like this:

              {collection.website && (
                <Badge
                  externalUrl={Html.escapeHtml(collection.website)}
                  symbol="website"
                />
              )}

But it's still flagged as xss prone.

I don't want to pass the safe attribute to the enclosing <div>, because <Badge /> is a custom component comprising more JSX.

a) Is there a way to mark a component as "safe", like a string primitive?
b) Wouldn't it be more sensible to skip XSS warnings for custom JSX components? Maybe I'm missing something but I only care about that warning on standard HTML tags like <div>, <span>, <p>, etc...

Thanks very much.

image

Steps to Reproduce

use above code snippet

Expected Behavior

No response

JSX type definitions in conlfict with react

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Versions

Tested with 3.0.10

Description

I have installed @kitajs/html as an inderect dependency of @elysiajs/html. Now I get Typescript errors in my project in random JSX properties, for example

<meta charSet="UTF-8" />
//    ^^^^^^^ 
//           Property 'charSet' does not exist on type 'HtmlMetaTag'. Did you mean 'charset'?ts(2322)

React's types defined this attribute to be written in camel case, ie. charSet while @kitajs/html overrides this with the all lowercase charset. Other examples are event handlers like onClick or onKeyPress

To me this is unexpected und unpractical because all my other projects use React's definitions as lingua franca

Steps to Reproduce

Setup a project with Next js and use this component

const Button = () => <button onClick={() => {}}>click</click>

You will see no type Errors. Install @kitajs/html and you will get type errors ot onClick

Expected Behavior

KitaJs matches, re-exports or expects React's TS Definitions as a peer dependency instead of providing divergent types

cannot assign functions to onclick + idk how to do this document.getElementById("modal")

does this have useRef or something

// server.tsx

const openModal = () => {
  const modal = document.getElementById("modal"); // <-- Cannot find name 'document'. Try changing the 'lib' compiler option to include 'dom'.
  modal.show();
};

const BaseHTML = ({ children }: { children?: Children }) => (
  <>
        <Header modalFun={openModal} />
        <tag of="dialog">sdafkjdsaf</tag>
  </>
);
// header.tsx

export const Header = ({ modalFun }: { modalFun: () => void }) => (
  <header>    
      <button onclick={modalFun}>Log in</button> // <-- Type '() => void' is not assignable to type 'string'.
  </header>
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.