Giter Site home page Giter Site logo

piranha / twinspark-js Goto Github PK

View Code? Open in Web Editor NEW
403.0 13.0 18.0 598 KB

Declarative enhancement for HTML: simple, composable, lean.

Home Page: https://twinspark.js.org/

License: MIT License

JavaScript 63.41% HTML 34.33% Makefile 0.95% CSS 1.30%
hateoas hotwire html htmx javascript rest turbolinks

twinspark-js's Introduction

TwinSpark

Declarative enhancement for HTML: simple, composable, lean. It's main goal is to eliminate most of the logic from JS, while allowing to make a good interactive site.

It engages this problem from a few angles:

  • partial page updates facilitated via HTML attributes (no JS needed)
  • actions - incredibly simple promise-enabled language for (limited) client-side scripting
  • morphing - a strategy to update HTML graduallly, without breaking state and focus

Simple: it's only a handful core attributes (like ts-req, ts-action, ts-trigger), with no surprising behavior (whatever is declared on top of your DOM tree will not affect your code).

Composable: there are enough extension points to compose with whatever your needs are. You can add more directives like ts-req, you can add more actions, you can customize requests being sent out. Whatever you need.

Lean: source is a full 2000 lines of code and only 8KB .min.gz. We believe in less is more.

It's a battle-tested technology used on websites with 100k+ daily active users.

Read more in docs.

twinspark-js's People

Contributors

ckald avatar edofic avatar hastebrot avatar jetmind avatar lour2002 avatar lpite avatar nunzioc avatar nyanja avatar piranha avatar roman-koshchei avatar vldmr-k avatar vsolovyov avatar waldyrious 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twinspark-js's Issues

Best way to handler redirect after sumit form?

Hi!

I want to use ts-swap="morph" and redirect after submit form, but it doesn't work well.

attribute ts-req-after don't triggired, bcs status 3xx is not true

I found solution, response <script>window.location.href = '...';</script>, but this method remove form, and customer see white block while page reloading.

How it doing better?

Have You Seen HTMX?

The Intercooler JS successor is HTMX, with no Jquery dependency. Could you help explain how this library differs and why one would choose TwinsparkJS from HTMX?

Вопросы к стриму "Викинь ти той React"

@piranha На прошлом стриме был вопросник. Почему бы не бахнуть и к этому?

Чаво больше всего интересно:

  • Почему не получилось пофиксить реакт сервер сайд рендерингом, отложенной загрузкой и прочими оптимизациями? Было бы сложнее/дороже, невозможно или пришло осознание того что э-комерсу реакт оверкилл?
  • Реакт вообще ненужен? Может тогда и для SPA юзать какой нибудь Vaadin?
  • Не будет ли дешевле перейти на htmx, что бы не майнтейнить свою либу. Чем она лучше? Может все таки форкнуть/закомитить нужные улучшения в htmx и юзать его?
  • Планируете так и рендерить html фрагменты на сервере rum-ом?
  • Не было бы лучше разделить куски страницы на шаблоны (<template> или тупо регекспом подставлять) и тянуть с сервера только данные. Теми же service worker можно прозрачно проксировать запросы с минимальными измененьями в самой либе. Тогда можно будет кешировать шаблоны, префетчить шаблоны альтернативных вьюшек когда запрашивается родительский элемент, отображать шаблон с плейсхолдер данными пока реальные подтягиваются и тп. Серверный код тоже не будет сильно сложнее. Если объяснить генератору html фрагментов концепцию шаблона (верстка+данные) то он сможет сразу генерить для эндпоинта где это запрашивается одним куском + еще 2 с данными и шаблоном отдельно.
  • Как обстоит дело с дебагом и насколько агрессивно все кешируется? Если от юзера прилетел кривой запрос, то как понять как он оказался в стейте который позволяет его сделать?
  • queue.request = setTimeout(executeRequests, 16); трюк с 16 реально с фреймрейтом помогает?
  • Этот IntersectionObserver интересная штука. Может устроить тур по коду?

'ts-req-selector="children ul"' doesn't activate children elements

Example:

<div ts-req="<url>" ts-trigger="load" ts-swap="replace" ts-req-selector="children ul"></div>

Problem:
When using 'ts-req-selector="children ul"' for swapping it will use DocumentFragment. But during swap DocumentFragment will become empty. This means activate() function will be called on DocumentFragment with no children - no elements will be activated. And 'ts-ready' event will not fire.

Not sure if it is wanted behaviour or not?

як замінити store pattern?

Вводні данні.

Уявимо що на сторінці є 4 місця, які треба оновлювати після якихось дій. Хай це буде компонент counter який перемножае ціну товара на кілкість в input counter.

Як це правильно організувати в twinspark?

Думки

  1. запіляхати функця htmlToHtml і передати як рагументи всі місця які треба оновити, але це не дуже удобно. Бо якщо добавиться на сторінку ще один компонент counter - то це буде просто витік мозку.
  2. реалізувати це через сервер та ts-swap-push (фігня повна, але як хак може і норм)

В тому самому react/vue/svelte, це вирішуеться store - як це вирішити в ts без больових відчуттів?

PS: Якщо що, то це реальний кейс. Є магаз, в ньому на сторінці товара є два компонента каунтера (статичний і флоатовий). при клікі на + значення збільшуеться, також оновлюється ціна на кнопкі "Поклад в корзину".

Question/concern About Mixing Logic Between Separate Responsibilities

So, I have a question/concern about mixing logic between separate modules/responsibilities.

My page has two forms:

  • Subscription form (enter your email and submit)
  • Feedback form (enter text and submit)

I show the subscription form first. Once it's submitted, I replace it with the feedback form. Both submissions go to separate routes and API endpoints and are handled by separate modules/services/controllers/etc.

Now, to hide one form and show another, both forms/logic must know about each other. That's what concerns me.

Either the subscription controller

  • must render the subscription-form-initial-view first,
  • then, upon submission, it renders the feedback-form-initial-view.

Or the feedback controller

  • renders the subscription-form-initial-view first,
  • then, upon submission, it renders the feedback-form-initial-view.

Or

  • both controllers render both forms (pieces) and inject them into the page via, e.g., partial views,
  • the subscription-form-initial-view is visible,
  • the feedback-form-initial-view is hidden,
  • and a third entity manages the visibility of blocks depending on submit/click events (which is also an implementation question):
    -- either make another request to render the block
    -- or have the feedback form "listen" to the subscription form's "state"
    -- or?

I'm missing some obvious implementation or still thinking in the 'old way'.

I would appreciate any insights from you or any suggestions on this.

twinspark.js.org domain

js.org provide a free domain for javascript-related projects. You can quickly get twinspark.js.org domain. It will be excellent for popularizing the library. Htmx is getting attention last few weeks. TwinSpark is also a valuable library with a similar purpose that can also be an interesting alternative to htmx. I also appreciate moving development forward from the people of my native country.

twinspark та npm-registry

Доброго дня!
А можливо додати лібу в npm-registry щоб встановлювати її через npm, yarn?

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.