Giter Site home page Giter Site logo

plugin-data-transform's Introduction

Data Transform Plugin for Pattern Lab

Installation

To install and use the plugin run the following command in the Pattern Lab root directory:

composer require aleksip/plugin-data-transform

Configuration options

For Attribute object support to work properly, your Pattern Lab config.yml file needs to have the following setting:

twigAutoescape: false

The default values for Data Transform Plugin specific options in config.yml are:

plugins:
    dataTransform:
        enabled: true
        verbose: false

Enabling and disabling the plugin

Once installed, it is possible to enable and disable Data Transform Plugin using the enabled setting.

Verbose mode

Occasionally it might happen that there is a problem with a data file, and PHP notices and/or warnings with long stack traces are displayed when Pattern Lab is generated. In a large project it can be difficult to find the problematic data file, but turning on Data Transform Plugin's verbose mode using the verbose setting can help.

In verbose mode Data Transform plugin reports each pattern it processes and all data transform functions performed. It also suppresses regular PHP error messages and reports about errors in an easier to read way.

Important note: due to the way verbose mode is implemented, it might not work if other plugins that interact with the Twig Environment object are used.

Features

Pattern-specific data file support for included patterns

Pattern Lab core only supports global data files and a pattern-specific data file for the main pattern. This plugin adds pattern-specific data file support for included patterns. This feature works with the include function provided by this plugin with all PatternEngines and also with regular includes in template files with Twig PatternEngine.

Please note that global data from the _data directory is considered to be pattern-specific data and will overwrite data inherited from a parent pattern. If you want to override data of an included pattern you can use the with keyword.

Data transform functions

Currently the plugin provides four transform functions for the data read by Pattern Lab. The examples provided are in JSON but Pattern Lab supports YAML too.

Include pattern files

If a value contains the name of a pattern in shorthand partials syntax, the plugin will replace the value with the rendered pattern:

{
    "key": "atoms-form-element-label-html"
}

Advanced syntax with support for passing variables (with) and disabling access to the default data (only):

{
    "key": {
        "include()": {
            "pattern": "atoms-form-element-label-html",
            "with": {
                "title": "Textfield label"
            },
            "only": true
        }
    }
}

In both examples the value of key will replaced with the rendered pattern.

For more information about with and only please refer to the Twig include documentation.

Include pseudo-pattern files

It is also possible to include pseudo-patterns using the shorthand partials syntax, by replacing the tilde (~) with a dash (-). So for example the pseudo-pattern shila-card.html~variant.json can be included like so:

{
    "key": "molecules-shila-card-html-variant"
}

Join text values

{
    "key": {
        "join()": [
            "molecules-comment-html",
            "<div class=\"indented\">",
            "molecules-comment-html",
            "</div>",
            "molecules-comment-html"
        ]
    }
}

The value of key will be replaced with the joined strings. Note that in the example molecules-comment-html is the name of a pattern in shorthand partials syntax. These will be replaced with the rendered pattern before the join.

Create Drupal Attribute objects

{
    "key": {
        "Attribute()": {
            "id": ["edit-submit"],
            "type": ["submit"],
            "value": ["Submit"],
            "class": ["button", "button-primary"]
        }
    }
}

The value of key will be replaced with an Attribute object.

Create Drupal Url objects

{
    "key": {
        "Url()": {
            "url": "http://example.com",
            "options": {
                "attributes": {
                    "Attribute()": {
                        "class": ["link"]
                    }
                }
            }
        }
    }
}

The value of key will be replaced with an Url object. Note that in the example the value of attributes will be replaced with an Attribute object before the Url object is created.

plugin-data-transform's People

Contributors

aleksip avatar charlotte17 avatar evanlovely avatar gambry avatar stmh 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

Watchers

 avatar  avatar  avatar  avatar  avatar

plugin-data-transform's Issues

what does this repo do?

Pattern Lab core only supports global data files and a pattern-specific data file for the main pattern. This plugin adds pattern-specific data file support for included patterns.

Could you elaborate a bit more what this repository is doing? It's a dependency of pattern-lab-starter and the edition-php-drupal-standard that's how far i got :)

`Include pattern files` more info

Hi, could you please provide more info on how to use Include pattern files feature?
It doesn't work for me, may be I do something wrong.

Where to store the html pattern file? Is it relative path to it?
How to put this parameter into twig? {{ key }}?

Thank you.

Pattern state and data inheritance

Hello,

First of all cograts for the great plugin ;)!

I couldn't find a similar issue so.. In a current a project we tried to use pattern states with data-transform plugin and it seems that it's not working as expected(?).

More specifically, we tried to include a card pattern (file name [email protected]) inside another as shown below:

{% include '@components/00-common/card/[email protected]' %}

The pattern's markup is included but it does not inherit data from card.yml file.

Any ideas on this one?

Thanks!

Attribute() doesn't work

Expected: render class passed inside Attribute() object

Result: error message PHP Notice: Array to string conversion in ...pattern-lab/vendor/twig/twig/lib/Twig/Environment.php(462) : eval()'d code on line 60

Pattern-Lab version:

"name":             "pattern-lab/edition-twig-standard",
"require": {
	"php": ">=5.4",
	"pattern-lab/core": "^2.0.0",
	"pattern-lab/patternengine-twig": "^2.0.0",
	"pattern-lab/styleguidekit-twig-default": "^3.0.0",
	"pattern-lab/drupal-twig-components": "^2.2",
	"aleksip/plugin-data-transform": "^1.1"
}

Twigs:
child.twig

<div {{ attributes }}></div>

parent.twig

{% include "@atoms/child.twig"
  with {
    attributes: {
      "Attribute()": {
        "class": ["test"]
      }
    }
  }
%}

Shorthand partials syntax

I just wondered if the shorthand partials syntax for include() only works in the format TYPE-TPLNAMEWITHOUTEXT?

We are running into problems with this, because we have templates saved like this (to keep the patternlab menu links as short as possible):

  • atoms
    • component
      • default.twig
      • xyz.twig
    • another-component
      • default.twig

As you can see, shorthand syntax atoms-default would target two different templates. So is this by design (I know templates should normally have the component name as filename), or is there any possibility to target an exact component, even if there is another one with the same template name?

Thanx in advance

Twig extensions loaded through PL 'twigPatternLoader.customize' are not loaded if 'include()' transformer is used

I created this twig extension and provided an autoload for PL using the 'twigPatternLoader.customize'.

The extension is not loaded if the 'include()' data transformer is used. It looks like when 'include()' is used the twig renderer is loaded earlier then needed, which setTwig_Environment::extensionInitialized to TRUE when actually things may still be loaded later on.

I tried to dig in to give more details, but didn't have enough time.

I believe the best - probably even long term - solution is to set priority -99 on subscriber $this->addListener('twigPatternLoader.customize', 'addNodeVisitor');. In this way this loader is likely to be loaded as last one, letting other plugins adding or altering twig extensions.

addcslashes() throws warning when passed objects in PatternDataNodeTrait.php

Using the Pattern Lab Faker plugin can sometimes generate objects instead of strings from data.json values. For instance:

"timestamp": "2016-05-21T17:02:39+00:00",
"test_timestamp": "Faker.dateTime()",

test_timestamp would be a DateTime object sent to Twig, instead of, say, an ISO string. This situation results in the following warning:

Warning: addcslashes() expects parameter 1 to be string, object given in /home/illepic/dev/downfall-guild/project/build/dev/d8/themes/custom/patternlab/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/Twig/PatternDataNodeTrait.php on line 45

Note: I'm using the preconfiguration of Pattern Lab Starter which enables both Faker and DataTransformer plugins.

Excessive performance downfall after updating to 1.0.0

I just wanted to update from 0.10.2 to 1.0.0, but sadly with the update the generation is taking massively longer and the memory need has increased massively too.

  • Before: site generation took 6.36483597755 seconds and used 35.25MB of memory.
  • After: site generation took 31.1519939899 seconds and used 406MB of memory

Do you have a clue where this huge step comes from?

Console output

$ php pattern-lab/core/console --generate
Could not open input file: pattern-lab/core/console
$ php core/console --generate
configuring pattern lab...
your site has been generated...
site generation took 6.36483597755 seconds and used 35.25MB of memory...
$ composer require "aleksip/plugin-data-transform":"^1.0.0"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Removing aleksip/plugin-data-transform (v0.10.2)
  - Installing aleksip/plugin-data-transform (v1.0.1)
    Loading from cache

> PatternLab\Installer::postPackageUpdate
Writing lock file
Generating autoload files
> PatternLab\Installer::postUpdateCmd
$ php core/console --generate
configuring pattern lab...

Notice: Undefined index: icon in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: icon in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: icon in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: icon in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: icon in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: icon in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64

Notice: Undefined index: visual in [...]/pattern-lab/vendor/aleksip/plugin-data-transform/src/aleksip/DataTransformPlugin/DataTransformer.php on line 64
your site has been generated...
site generation took 31.1519939899 seconds and used 406MB of memory...

Undefined Index

The undefined index notice comes from pattern specific json values being declared as "icon": null. Maybe that is something to look into in a separate issue.

include() in pattern data only working on initial build

Hi,

when working on a pattern in which I include another pattern using the [pattern].yml or [pattern].json file, it only works on the initial build of the pattern lab. When running php core/console --watch and i change that data file or simply some css that makes PL recompile to the public folder, I only get Array as output.

Then I have to quit the PL watch task an rerun it.

Example YAML:

mol_accordion_elements:
  '1':
    title: A File
    icon: 'icon_download'
    content:
      include():
        pattern: atoms-file
        with:
          file:
            filename: file.pdf
            filesize: 96KB
            permalink: http://test.com/file.pdf
        only: true

Discussion/Request: Include patterns in lineage

It would be helpful if patterns included using plugin-data-transform were added to the lineage and therefore included in pattern info.

Any idea on how it might be possible?
I guess it would mean amending patternlab-php-core Helper files to look in the yaml/json for any pattern: child of an include():

Or might there be a way to workaround that?

Add dummy drupal Url object

If you want to do something like the following in your twig template, it isn't possible without an actual Url object. This is a very simple getter/setter of the Drupal's. It needs to be simple because we cannot expect to have a fully bootstrapped Drupal and there are too many dependencies on the verbatim class.

twig:
<a href="{{ item.url }}"><i class="{{ item.url.option('attributes').class }}" ></i>{{ item.title }}</a>

data.json:

"items": [
          {
            "title": "Facebook",
            "url": {
              "Url()": {
                "url": "#",
                "options": {
                  "attributes": {
                    "class": "fa"
                  }
                }
              }
            }
          },

Attributes() and the need for the raw filter?

Thank you for your work on this. It's my first time using this plugin. For some reason I have to use the raw filter or else the " will be output as html entities.

I'm expecting to do this:

{%
set classes = [
  'mini-thumb'|clean_class,
  title or summary ? 'has-content',
]
%}
<div{{ attributes.addClass(classes) }}>

But that leads to this output:

<div class=&quot;mini-thumb has-content&quot;>

However this works...

{%
set classes = [
  'mini-thumb'|clean_class,
  title or summary ? 'has-content',
]
%}
<div{{ attributes.addClass(classes)|raw }}>

I'm sure I'm missing something, but I don't know what. My understanding is that in D8 I should not have to use the raw filter, so I want to keep that the same in Pattern Lab. I tried setting to false the autoescape function in config.yml, but that didn't seem to affect it.

twigAutoescape: false

1.3.1 Update causes deprecation warnings in console on build

I am including some components with the include() syntax in the corresponding yaml file like so:

---
nav:
  include():
    pattern: template-components-navigation

The build seems to work, all patterns can be rendered but I get a lot of warnings now:

[data transform plugin] pattern templates-page
  error rendering template-components-navigation
  The Twig\Node\Node::getLine method is deprecated since version 1.27 and will be removed in 2.0. Use getTemplateLine() instead.

Any idea on how to fix this? Not something that brakes the workflow but this did't happen with version 1.3.0

include() should support longform-syntax

It would be great if include() can support also the "longform"-include syntax of twig, as this will give us more flexibility and avoid collisions when using more than 2 hierarchy-levels.

Here's an example of a possible collision:

long-form short-hand
@components/one/two/three components-three
@components/two/two/three components-three

Attributes in macros are double quoted

This is cross-posted at pattern-lab/patternengine-php-twig.

This is working fine in a pattern:
<div {{ attributes.addClass('test') }}>test</div>
<div class="test">test</div>

But if this is inside a macro, I get:
<div class=""test"">test</div>

I can work around this by including the macro file like another pattern.

Not able to `join()` hidden patterns with `_` prefix

We're not able to use join() (I'm assuming it's the same for includes) with patterns that have a filename that starts with a _ (i.e. hidden). Let me know if you'd like some code snippets or more info. Thanks!

What does only do?

What does only: true do here?

{
    "key": {
        "include()": {
            "pattern": "atoms-form-element-label.html",
            "with": {
                "title": "Textfield label"
            },
            "only": true
        }
    }
}

Markup Outputting Double Quotes in Attribute Values

I've been attempting to use this plugin and I'm seeing the following result when setting any attribute in the global PL data file. I've tested the same with other attributes (id as an example) which gave me the same result.

I'm using versions:
pattern-lab/core => 2.9.0
aleksip/plugin-data-transform => 1.2.0

<div class=""layout"">
 </div>

I've tried setting this attribute value with both the JSON and YAML formats. See below.

JSON Format:

{
  "layout_title": "Singe Column Layout",
  "items": [
    {
      "attributes": {
        "Attribute()": {
          "class": ["layout"]
        }
      }
    },
    {
      "attributes": {
        "Attribute()": {
          "class": ["layout"]
        }
      }
    },
    {
      "attributes": {
        "Attribute()": {
          "class": ["layout"]
        }
      }
    }
  ],
  "modifiers": {
    "1": "pl"
  }
}

YAML Format:

layout_title:
  "Singe Column Layout"
items:
  one:
    attributes:
      Attribute():
        class: ["layout"]
  two:
    attributes:
      Attribute():
        class: ["layout"]
  three:
    attributes:
      Attribute():
        class: ["layout"]
modifiers:
  1:
    pl

The Twig template markup is as follows:

{% if layout_title %}
  <div class="layout__title-wrap">
    <h2>{{ layout_title }}</h2>
  </div>
{% endif %}

<div class="component-layout-container {{ layout_class }} {% for modifier in modifiers %}layout--{{ modifier }}{% endfor %}">
  {% if content %}
    {{ content }}
  {% else %}
    {% for item in items %}
      <div{{ item.attributes }}>
        {{ item.content }}
      </div>
    {% endfor %}
  {% endif %}
</div>

Allow global defaults

It would be great if I could use these tools in data.json. In particular, I would like to have this in it:

{
  "attributes": {
    "Attribute()": {
      "class": []
    }
  }
}

Otherwise I need to have that same thing in every pattern's sidecar json file so things like this work:

{%
  set classes = [
    'block'
  ]
%}
<div{{ attributes.addClass(classes) }}>
  <p>Cool stuff here</p>
</div>

Let me know if you'd like me to spin up a sample repo that shows this with more detail; thanks!

Future plans for Pattern Lab 3

Hi @aleksip, this is more of an enquiry than a bug.

Thank you for all your work on this module, I use it really heavily at work, mostly for the Attributes object but also for referencing patterns inside other patterns as example data.

What are your thoughts about the future of the plugin with Pattern Lab 3's switch to Node? I don't fully understand the implications but presumably this will make it harder to run Drupal code inside PL? Or could plugins run PHP code in the same way as Pattern Lab itself will run Twig via PHP rather than JS?

Use include() inside join()?

Is something like this possible? Thanks.

{
  "page": {
    "title": "Act Now to Save Lives",
    "content": {
      "join()": [
        "atoms-paragraph-monthly-donor",
        "components-infographic-impact",
        "components-mega-card-gift-array",
        "include()": {
          "pattern": "components-related-card-group",
          "with": {
            "page": "fundraising"
          }
        },
        "components-newsletter"
      ]
    },
    "footer": "components-footer"
  }
}

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.