Browse Source

Merge pull request #4303 from xQwexx/styleable

Convert Styleable to StyleableModel class
pull/4309/head
Artur Arseniev 4 years ago
committed by GitHub
parent
commit
73d1099df5
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 389
      docs/api/component.md
  2. 85
      docs/api/css_rule.md
  3. 4
      src/css_composer/model/CssRule.js
  4. 8
      src/dom_components/model/Component.js
  5. 25
      src/domain_abstract/model/StyleableModel.js
  6. 2
      test/specs/style_manager/view/PropertyRadioView.js

389
docs/api/component.md

@ -2,7 +2,7 @@
## Component ## Component
**Extends Model.extend(Styleable)** **Extends StyleableModel**
The Component object represents a single node of our template structure, so when you update its properties the changes are The Component object represents a single node of our template structure, so when you update its properties the changes are
immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all
@ -19,50 +19,50 @@ component.get('tagName');
// -> 'span' // -> 'span'
``` ```
[Component]: component.html [component]: component.html
### Properties ### Properties
* `type` **[String][1]?** Component type, eg. `text`, `image`, `video`, etc. - `type` **[String][1]?** Component type, eg. `text`, `image`, `video`, etc.
* `tagName` **[String][1]?** HTML tag of the component, eg. `span`. Default: `div` - `tagName` **[String][1]?** HTML tag of the component, eg. `span`. Default: `div`
* `attributes` **[Object][2]?** Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` - `attributes` **[Object][2]?** Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}`
* `name` **[String][1]?** Name of the component. Will be used, for example, in Layers and badges - `name` **[String][1]?** Name of the component. Will be used, for example, in Layers and badges
* `removable` **[Boolean][3]?** When `true` the component is removable from the canvas, default: `true` - `removable` **[Boolean][3]?** When `true` the component is removable from the canvas, default: `true`
* `draggable` **([Boolean][3] | [String][1] | [Function][4])?** Indicates if it's possible to drag the component inside others. - `draggable` **([Boolean][3] | [String][1] | [Function][4])?** Indicates if it's possible to drag the component inside others.
You can also specify a query string to indentify elements, You can also specify a query string to indentify elements,
eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements
containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true` containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true`
* `droppable` **([Boolean][3] | [String][1] | [Function][4])?** Indicates if it's possible to drop other components inside. You can use - `droppable` **([Boolean][3] | [String][1] | [Function][4])?** Indicates if it's possible to drop other components inside. You can use
a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true` a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true`
* `badgable` **[Boolean][3]?** Set to false if you don't want to see the badge (with the name) over the component. Default: `true` - `badgable` **[Boolean][3]?** Set to false if you don't want to see the badge (with the name) over the component. Default: `true`
* `stylable` **([Boolean][3] | [Array][5]<[String][1]>)?** True if it's possible to style the component. - `stylable` **([Boolean][3] | [Array][5]<[String][1]>)?** True if it's possible to style the component.
You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties
will be hidden from the style manager. Default: `true` will be hidden from the style manager. Default: `true`
* `stylable-require` **[Array][5]<[String][1]>?** Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]` - `stylable-require` **[Array][5]<[String][1]>?** Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]`
* `unstylable` **[Array][5]<[String][1]>?** Indicate an array of style properties which should be hidden from the style manager. Default: `[]` - `unstylable` **[Array][5]<[String][1]>?** Indicate an array of style properties which should be hidden from the style manager. Default: `[]`
* `highlightable` **[Boolean][3]?** It can be highlighted with 'dotted' borders if true. Default: `true` - `highlightable` **[Boolean][3]?** It can be highlighted with 'dotted' borders if true. Default: `true`
* `copyable` **[Boolean][3]?** True if it's possible to clone the component. Default: `true` - `copyable` **[Boolean][3]?** True if it's possible to clone the component. Default: `true`
* `resizable` **[Boolean][3]?** Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer][6]. Default: `false` - `resizable` **[Boolean][3]?** Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer][6]. Default: `false`
* `editable` **[Boolean][3]?** Allow to edit the content of the component (used on Text components). Default: `false` - `editable` **[Boolean][3]?** Allow to edit the content of the component (used on Text components). Default: `false`
* `layerable` **[Boolean][3]?** Set to `false` if you need to hide the component inside Layers. Default: `true` - `layerable` **[Boolean][3]?** Set to `false` if you need to hide the component inside Layers. Default: `true`
* `selectable` **[Boolean][3]?** Allow component to be selected when clicked. Default: `true` - `selectable` **[Boolean][3]?** Allow component to be selected when clicked. Default: `true`
* `hoverable` **[Boolean][3]?** Shows a highlight outline when hovering on the element if `true`. Default: `true` - `hoverable` **[Boolean][3]?** Shows a highlight outline when hovering on the element if `true`. Default: `true`
* `void` **[Boolean][3]?** This property is used by the HTML exporter as void elements don't have closing tags, eg. `<br/>`, `<hr/>`, etc. Default: `false` - `void` **[Boolean][3]?** This property is used by the HTML exporter as void elements don't have closing tags, eg. `<br/>`, `<hr/>`, etc. Default: `false`
* `style` **[Object][2]?** Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }` - `style` **[Object][2]?** Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }`
* `styles` **[String][1]?** Component related styles, eg. `.my-component-class { color: red }` - `styles` **[String][1]?** Component related styles, eg. `.my-component-class { color: red }`
* `content` **[String][1]?** Content of the component (not escaped) which will be appended before children rendering. Default: `''` - `content` **[String][1]?** Content of the component (not escaped) which will be appended before children rendering. Default: `''`
* `icon` **[String][1]?** Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string '<i class="fa fa-square-o"></i>'. Default: `''` - `icon` **[String][1]?** Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string '<i class="fa fa-square-o"></i>'. Default: `''`
* `script` **([String][1] | [Function][4])?** Component's javascript. More about it [here][7]. Default: `''` - `script` **([String][1] | [Function][4])?** Component's javascript. More about it [here][7]. Default: `''`
* `script-export` **([String][1] | [Function][4])?** You can specify javascript available only in export functions (eg. when you get the HTML). - `script-export` **([String][1] | [Function][4])?** You can specify javascript available only in export functions (eg. when you get the HTML).
If this property is defined it will overwrite the `script` one (in export functions). Default: `''` If this property is defined it will overwrite the `script` one (in export functions). Default: `''`
* `traits` **[Array][5]<([Object][2] | [String][1])>?** Component's traits. More about it [here][8]. Default: `['id', 'title']` - `traits` **[Array][5]<([Object][2] | [String][1])>?** Component's traits. More about it [here][8]. Default: `['id', 'title']`
* `propagate` **[Array][5]<[String][1]>?** Indicates an array of properties which will be inhereted by all NEW appended children. - `propagate` **[Array][5]<[String][1]>?** Indicates an array of properties which will be inhereted by all NEW appended children.
For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }` For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }`
and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]` and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]`
* `toolbar` **[Array][5]<[Object][2]>?** Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). - `toolbar` **[Array][5]<[Object][2]>?** Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete).
Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`. Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`.
By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`).
* `components` **Collection<[Component][9]>?** Children components. Default: `null` - `components` **Collection<[Component][9]>?** Children components. Default: `null`
### init ### init
@ -74,9 +74,9 @@ Hook method, called when the model has been updated (eg. updated some model's pr
#### Parameters #### Parameters
* `property` **[String][1]** Property name, if triggered after some property update - `property` **[String][1]** Property name, if triggered after some property update
* `value` **any** Property value, if triggered after some property update - `value` **any** Property value, if triggered after some property update
* `previous` **any** Property previous value, if triggered after some property update - `previous` **any** Property previous value, if triggered after some property update
### removed ### removed
@ -88,28 +88,28 @@ Check component's type
#### Parameters #### Parameters
* `type` **[string][1]** Component type - `type` **[string][1]** Component type
#### Examples #### Examples
```javascript ```javascript
component.is('image') component.is("image");
// -> false // -> false
``` ```
Returns **[Boolean][3]** Returns **[Boolean][3]**
### props ### props
Return all the propeties Return all the propeties
Returns **[Object][2]** Returns **[Object][2]**
### index ### index
Get the index of the component in the parent collection. Get the index of the component in the parent collection.
Returns **[Number][10]** Returns **[Number][10]**
### setDragMode ### setDragMode
@ -118,9 +118,9 @@ To get more about this feature read: [https://github.com/artf/grapesjs/issues/19
#### Parameters #### Parameters
* `value` **[String][1]** Drag mode, options: 'absolute' | 'translate' - `value` **[String][1]** Drag mode, options: 'absolute' | 'translate'
Returns **this** Returns **this**
### find ### find
@ -129,12 +129,12 @@ Find inner components by query string.
#### Parameters #### Parameters
* `query` **[String][1]** Query string - `query` **[String][1]** Query string
#### Examples #### Examples
```javascript ```javascript
component.find('div > .class'); component.find("div > .class");
// -> [Component, Component, ...] // -> [Component, Component, ...]
``` ```
@ -148,16 +148,16 @@ also before rendering the component
#### Parameters #### Parameters
* `type` **[String][1]** Component type - `type` **[String][1]** Component type
#### Examples #### Examples
```javascript ```javascript
const allImages = component.findType('image'); const allImages = component.findType("image");
console.log(allImages[0]) // prints the first found component console.log(allImages[0]); // prints the first found component
``` ```
Returns **[Array][5]<[Component][9]>** Returns **[Array][5]<[Component][9]>**
### closest ### closest
@ -166,16 +166,16 @@ Find the closest parent component by query string.
#### Parameters #### Parameters
* `query` **[string][1]** Query string - `query` **[string][1]** Query string
#### Examples #### Examples
```javascript ```javascript
component.closest('div.some-class'); component.closest("div.some-class");
// -> Component // -> Component
``` ```
Returns **[Component][9]** Returns **[Component][9]**
### closestType ### closestType
@ -185,12 +185,12 @@ also before rendering the component
#### Parameters #### Parameters
* `type` **[String][1]** Component type - `type` **[String][1]** Component type
#### Examples #### Examples
```javascript ```javascript
const Section = component.closestType('section'); const Section = component.closestType("section");
console.log(Section); console.log(Section);
``` ```
@ -203,9 +203,9 @@ component is a descendant of a given component
#### Parameters #### Parameters
* `component` **[Component][9]** Component to check - `component` **[Component][9]** Component to check
Returns **[Boolean][3]** Returns **[Boolean][3]**
### replaceWith ### replaceWith
@ -213,12 +213,12 @@ Replace a component with another one
#### Parameters #### Parameters
* `el` **([String][1] | [Component][9])** Component or HTML string - `el` **([String][1] | [Component][9])** Component or HTML string
#### Examples #### Examples
```javascript ```javascript
component.replaceWith('<div>Some new content</div>'); component.replaceWith("<div>Some new content</div>");
// -> Component // -> Component
``` ```
@ -230,17 +230,17 @@ Update attributes of the component
#### Parameters #### Parameters
* `attrs` **[Object][2]** Key value attributes - `attrs` **[Object][2]** Key value attributes
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
* `options` **[Object][2]** Options for the model update - `options` **[Object][2]** Options for the model update
#### Examples #### Examples
```javascript ```javascript
component.setAttributes({ id: 'test', 'data-key': 'value' }); component.setAttributes({ id: "test", "data-key": "value" });
``` ```
Returns **this** Returns **this**
### addAttributes ### addAttributes
@ -248,17 +248,17 @@ Add attributes to the component
#### Parameters #### Parameters
* `attrs` **[Object][2]** Key value attributes - `attrs` **[Object][2]** Key value attributes
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
* `options` **[Object][2]** Options for the model update - `options` **[Object][2]** Options for the model update
#### Examples #### Examples
```javascript ```javascript
component.addAttributes({ 'data-key': 'value' }); component.addAttributes({ "data-key": "value" });
``` ```
Returns **this** Returns **this**
### removeAttributes ### removeAttributes
@ -266,18 +266,18 @@ Remove attributes from the component
#### Parameters #### Parameters
* `attrs` **([String][1] | [Array][5]<[String][1]>)** Array of attributes to remove (optional, default `[]`) - `attrs` **([String][1] | [Array][5]<[String][1]>)** Array of attributes to remove (optional, default `[]`)
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
* `options` **[Object][2]** Options for the model update - `options` **[Object][2]** Options for the model update
#### Examples #### Examples
```javascript ```javascript
component.removeAttributes('some-attr'); component.removeAttributes("some-attr");
component.removeAttributes(['some-attr1', 'some-attr2']); component.removeAttributes(["some-attr1", "some-attr2"]);
``` ```
Returns **this** Returns **this**
### getStyle ### getStyle
@ -285,10 +285,10 @@ Get the style of the component
#### Parameters #### Parameters
* `options` (optional, default `{}`) - `options` (optional, default `{}`)
* `optsAdd` (optional, default `{}`) - `optsAdd` (optional, default `{}`)
Returns **[Object][2]** Returns **[Object][2]**
### setStyle ### setStyle
@ -296,16 +296,16 @@ Set the style on the component
#### Parameters #### Parameters
* `prop` **[Object][2]** Key value style object (optional, default `{}`) - `prop` **[Object][2]** Key value style object (optional, default `{}`)
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
#### Examples #### Examples
```javascript ```javascript
component.setStyle({ color: 'red' }); component.setStyle({ color: "red" });
``` ```
Returns **[Object][2]** Returns **[Object][2]**
### getAttributes ### getAttributes
@ -313,9 +313,9 @@ Return all component's attributes
#### Parameters #### Parameters
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
Returns **[Object][2]** Returns **[Object][2]**
### addClass ### addClass
@ -323,14 +323,14 @@ Add classes
#### Parameters #### Parameters
* `classes` **([Array][5]<[String][1]> | [String][1])** Array or string of classes - `classes` **([Array][5]<[String][1]> | [String][1])** Array or string of classes
#### Examples #### Examples
```javascript ```javascript
model.addClass('class1'); model.addClass("class1");
model.addClass('class1 class2'); model.addClass("class1 class2");
model.addClass(['class1', 'class2']); model.addClass(["class1", "class2"]);
// -> [SelectorObject, ...] // -> [SelectorObject, ...]
``` ```
@ -342,14 +342,14 @@ Set classes (resets current collection)
#### Parameters #### Parameters
* `classes` **([Array][5]<[String][1]> | [String][1])** Array or string of classes - `classes` **([Array][5]<[String][1]> | [String][1])** Array or string of classes
#### Examples #### Examples
```javascript ```javascript
model.setClass('class1'); model.setClass("class1");
model.setClass('class1 class2'); model.setClass("class1 class2");
model.setClass(['class1', 'class2']); model.setClass(["class1", "class2"]);
// -> [SelectorObject, ...] // -> [SelectorObject, ...]
``` ```
@ -361,14 +361,14 @@ Remove classes
#### Parameters #### Parameters
* `classes` **([Array][5]<[String][1]> | [String][1])** Array or string of classes - `classes` **([Array][5]<[String][1]> | [String][1])** Array or string of classes
#### Examples #### Examples
```javascript ```javascript
model.removeClass('class1'); model.removeClass("class1");
model.removeClass('class1 class2'); model.removeClass("class1 class2");
model.removeClass(['class1', 'class2']); model.removeClass(["class1", "class2"]);
// -> [SelectorObject, ...] // -> [SelectorObject, ...]
``` ```
@ -378,7 +378,7 @@ Returns **[Array][5]** Array of removed selectors
Returns component's classes as an array of strings Returns component's classes as an array of strings
Returns **[Array][5]** Returns **[Array][5]**
### append ### append
@ -386,16 +386,16 @@ Add new component children
#### Parameters #### Parameters
* `components` **([Component][9] | [String][1])** Component to add - `components` **([Component][9] | [String][1])** Component to add
* `opts` **[Object][2]** Options for the append action (optional, default `{}`) - `opts` **[Object][2]** Options for the append action (optional, default `{}`)
#### Examples #### Examples
```javascript ```javascript
someComponent.get('components').length // -> 0 someComponent.get("components").length; // -> 0
const videoComponent = someComponent.append('<video></video><div></div>')[0]; const videoComponent = someComponent.append("<video></video><div></div>")[0];
// This will add 2 components (`video` and `div`) to your `someComponent` // This will add 2 components (`video` and `div`) to your `someComponent`
someComponent.get('components').length // -> 2 someComponent.get("components").length; // -> 2
// You can pass components directly // You can pass components directly
otherComponent.append(otherComponent2); otherComponent.append(otherComponent2);
otherComponent.append([otherComponent3, otherComponent4]); otherComponent.append([otherComponent3, otherComponent4]);
@ -412,21 +412,21 @@ current collection is returned
#### Parameters #### Parameters
* `components` **([Component][9] | [String][1])?** Component Definitions or HTML string - `components` **([Component][9] | [String][1])?** Component Definitions or HTML string
* `opts` **[Object][2]** Options, same as in `Component.append()` (optional, default `{}`) - `opts` **[Object][2]** Options, same as in `Component.append()` (optional, default `{}`)
#### Examples #### Examples
```javascript ```javascript
// Set new collection // Set new collection
component.components('<span></span><div></div>'); component.components("<span></span><div></div>");
// Get current collection // Get current collection
const collection = component.components(); const collection = component.components();
console.log(collection.length); console.log(collection.length);
// -> 2 // -> 2
``` ```
Returns **(Collection | [Array][5]<[[Component][9]]>)** Returns **(Collection | [Array][5]<[[Component][9]]>)**
### getChildAt ### getChildAt
@ -434,7 +434,7 @@ If exists, returns the child component at specific index.
#### Parameters #### Parameters
* `index` **[Number][10]** Index of the component to return - `index` **[Number][10]** Index of the component to return
#### Examples #### Examples
@ -445,7 +445,7 @@ component.getChildAt(0);
component.getChildAt(1); component.getChildAt(1);
``` ```
Returns **([[Component][9]] | null)** Returns **([[Component][9]] | null)**
### getLastChild ### getLastChild
@ -457,17 +457,17 @@ If exists, returns the last child component.
const lastChild = component.getLastChild(); const lastChild = component.getLastChild();
``` ```
Returns **([[Component][9]] | null)** Returns **([[Component][9]] | null)**
### empty ### empty
Remove all inner components Remove all inner components
* @return {this} - @return {this}
#### Parameters #### Parameters
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
### parent ### parent
@ -475,7 +475,7 @@ Get the parent component, if exists
#### Parameters #### Parameters
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
#### Examples #### Examples
@ -484,7 +484,7 @@ component.parent();
// -> Component // -> Component
``` ```
Returns **([Component][9] | null)** Returns **([Component][9] | null)**
### getTraits ### getTraits
@ -498,7 +498,7 @@ console.log(traits);
// [Trait, Trait, Trait, ...] // [Trait, Trait, Trait, ...]
``` ```
Returns **[Array][5]\<Trait>** Returns **[Array][5]\<Trait>**
### setTraits ### setTraits
@ -506,7 +506,7 @@ Replace current collection of traits with a new one.
#### Parameters #### Parameters
* `traits` **[Array][5]<[Object][2]>** Array of trait definitions - `traits` **[Array][5]<[Object][2]>** Array of trait definitions
#### Examples #### Examples
@ -516,7 +516,7 @@ console.log(traits);
// [Trait, ...] // [Trait, ...]
``` ```
Returns **[Array][5]\<Trait>** Returns **[Array][5]\<Trait>**
### getTrait ### getTrait
@ -524,13 +524,13 @@ Get the trait by id/name.
#### Parameters #### Parameters
* `id` **[String][1]** The `id` or `name` of the trait - `id` **[String][1]** The `id` or `name` of the trait
#### Examples #### Examples
```javascript ```javascript
const traitTitle = component.getTrait('title'); const traitTitle = component.getTrait("title");
traitTitle && traitTitle.set('label', 'New label'); traitTitle && traitTitle.set("label", "New label");
``` ```
Returns **(Trait | null)** Trait getModelToStyle Returns **(Trait | null)** Trait getModelToStyle
@ -541,19 +541,19 @@ Update a trait.
#### Parameters #### Parameters
* `id` **[String][1]** The `id` or `name` of the trait - `id` **[String][1]** The `id` or `name` of the trait
* `props` **[Object][2]** Object with the props to update - `props` **[Object][2]** Object with the props to update
#### Examples #### Examples
```javascript ```javascript
component.updateTrait('title', { component.updateTrait("title", {
type: 'select', type: "select",
options: [ 'Option 1', 'Option 2' ], options: ["Option 1", "Option 2"],
}); });
``` ```
Returns **this** Returns **this**
### getTraitIndex ### getTraitIndex
@ -562,12 +562,12 @@ replace some trait, at runtime, with something else.
#### Parameters #### Parameters
* `id` **[String][1]** The `id` or `name` of the trait - `id` **[String][1]** The `id` or `name` of the trait
#### Examples #### Examples
```javascript ```javascript
const traitTitle = component.getTraitIndex('title'); const traitTitle = component.getTraitIndex("title");
console.log(traitTitle); // 1 console.log(traitTitle); // 1
``` ```
@ -579,13 +579,13 @@ Remove trait/s by id/s.
#### Parameters #### Parameters
* `id` **([String][1] | [Array][5]<[String][1]>)** The `id`/`name` of the trait (or an array) - `id` **([String][1] | [Array][5]<[String][1]>)** The `id`/`name` of the trait (or an array)
#### Examples #### Examples
```javascript ```javascript
component.removeTrait('title'); component.removeTrait("title");
component.removeTrait(['title', 'id']); component.removeTrait(["title", "id"]);
``` ```
Returns **[Array][5]\<Trait>** Array of removed traits Returns **[Array][5]\<Trait>** Array of removed traits
@ -596,8 +596,8 @@ Add new trait/s.
#### Parameters #### Parameters
* `trait` **([String][1] | [Object][2] | [Array][5]<([String][1] | [Object][2])>)** Trait to add (or an array of traits) - `trait` **([String][1] | [Object][2] | [Array][5]<([String][1] | [Object][2])>)** Trait to add (or an array of traits)
* `opts` **Options** Options for the add (optional, default `{}`) - `opts` **Options** Options for the add (optional, default `{}`)
#### Examples #### Examples
@ -616,13 +616,13 @@ Returns **[Array][5]\<Trait>** Array of added traits
Get the name of the component Get the name of the component
Returns **[String][1]** Returns **[String][1]**
### getIcon ### getIcon
Get the icon string Get the icon string
Returns **[String][1]** Returns **[String][1]**
### toHTML ### toHTML
@ -630,34 +630,34 @@ Return HTML string of the component
#### Parameters #### Parameters
* `opts` **[Object][2]** Options (optional, default `{}`) - `opts` **[Object][2]** Options (optional, default `{}`)
* `opts.tag` **[String][1]?** Custom tagName - `opts.tag` **[String][1]?** Custom tagName
* `opts.attributes` **([Object][2] | [Function][4])** You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. (optional, default `null`) - `opts.attributes` **([Object][2] | [Function][4])** You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. (optional, default `null`)
* `opts.withProps` **[Boolean][3]?** Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML. - `opts.withProps` **[Boolean][3]?** Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML.
* `opts.altQuoteAttr` **[Boolean][3]?** In case the attribute value contains a `"` char, instead of escaping it (`attr="value &quot;"`), the attribute will be quoted using single quotes (`attr='value "'`). - `opts.altQuoteAttr` **[Boolean][3]?** In case the attribute value contains a `"` char, instead of escaping it (`attr="value &quot;"`), the attribute will be quoted using single quotes (`attr='value "'`).
#### Examples #### Examples
```javascript ```javascript
// Simple HTML return // Simple HTML return
component.set({ tagName: 'span' }); component.set({ tagName: "span" });
component.setAttributes({ title: 'Hello' }); component.setAttributes({ title: "Hello" });
component.toHTML(); component.toHTML();
// -> <span title="Hello"></span> // -> <span title="Hello"></span>
// Custom attributes // Custom attributes
component.toHTML({ attributes: { 'data-test': 'Hello' } }); component.toHTML({ attributes: { "data-test": "Hello" } });
// -> <span data-test="Hello"></span> // -> <span data-test="Hello"></span>
// Custom dynamic attributes // Custom dynamic attributes
component.toHTML({ component.toHTML({
attributes(component, attributes) { attributes(component, attributes) {
if (component.get('tagName') == 'span') { if (component.get("tagName") == "span") {
attributes.title = 'Custom attribute'; attributes.title = "Custom attribute";
} }
return attributes; return attributes;
}, },
}); });
// -> <span title="Custom attribute"></span> // -> <span title="Custom attribute"></span>
``` ```
@ -670,7 +670,7 @@ Get inner HTML of the component
#### Parameters #### Parameters
* `opts` **[Object][2]** Same options of `toHTML` (optional, default `{}`) - `opts` **[Object][2]** Same options of `toHTML` (optional, default `{}`)
Returns **[String][1]** HTML string Returns **[String][1]** HTML string
@ -680,13 +680,13 @@ Return an object containing only changed props
#### Parameters #### Parameters
* `res` - `res`
### getId ### getId
Return the component id Return the component id
Returns **[String][1]** Returns **[String][1]**
### setId ### setId
@ -694,10 +694,10 @@ Set new id on the component
#### Parameters #### Parameters
* `id` **[String][1]** - `id` **[String][1]**
* `opts` - `opts`
Returns **this** Returns **this**
### getEl ### getEl
@ -706,9 +706,9 @@ This works only if the component is already rendered
#### Parameters #### Parameters
* `frame` **Frame** Specific frame from which taking the element - `frame` **Frame** Specific frame from which taking the element
Returns **[HTMLElement][12]** Returns **[HTMLElement][12]**
### getView ### getView
@ -717,9 +717,9 @@ This works only if the component is already rendered
#### Parameters #### Parameters
* `frame` **Frame** Get View of a specific frame - `frame` **Frame** Get View of a specific frame
Returns **ComponentView** Returns **ComponentView**
### onAll ### onAll
@ -727,17 +727,17 @@ Execute callback function on itself and all inner components
#### Parameters #### Parameters
* `clb` **[Function][4]** Callback function, the model is passed as an argument - `clb` **[Function][4]** Callback function, the model is passed as an argument
#### Examples #### Examples
```javascript ```javascript
component.onAll(component => { component.onAll((component) => {
// do something with component // do something with component
}) });
``` ```
Returns **this** Returns **this**
### remove ### remove
@ -745,9 +745,9 @@ Remove the component
#### Parameters #### Parameters
* `opts` (optional, default `{}`) - `opts` (optional, default `{}`)
Returns **this** Returns **this**
### move ### move
@ -755,8 +755,8 @@ Move the component to another destination component
#### Parameters #### Parameters
* `component` **[Component][9]** Destination component (so the current one will be appended as a child) - `component` **[Component][9]** Destination component (so the current one will be appended as a child)
* `opts` **[Object][2]** Options for the append action (optional, default `{}`) - `opts` **[Object][2]** Options for the append action (optional, default `{}`)
#### Examples #### Examples
@ -766,7 +766,7 @@ const dest = editor.getWrapper();
editor.getSelected().move(dest, { at: 0 }); editor.getSelected().move(dest, { at: 0 });
``` ```
Returns **this** Returns **this**
### isInstanceOf ### isInstanceOf
@ -774,20 +774,20 @@ Check if the component is an instance of some component type.
#### Parameters #### Parameters
* `type` **[String][1]** Component type - `type` **[String][1]** Component type
#### Examples #### Examples
```javascript ```javascript
// Add a new component type by extending an existing one // Add a new component type by extending an existing one
editor.Components.addType('text-ext', { extend: 'text' }); editor.Components.addType("text-ext", { extend: "text" });
// Append a new component somewhere // Append a new component somewhere
const newTextExt = editor.getSelected().append({ type: 'text-ext' })[0]; const newTextExt = editor.getSelected().append({ type: "text-ext" })[0];
newTextExt.isInstanceOf('text-ext'); // true newTextExt.isInstanceOf("text-ext"); // true
newTextExt.isInstanceOf('text'); // true newTextExt.isInstanceOf("text"); // true
``` ```
Returns **[Boolean][3]** Returns **[Boolean][3]**
### isChildOf ### isChildOf
@ -795,43 +795,32 @@ Check if the component is a child of some other component (or component type)
#### Parameters #### Parameters
* `component` **([[Component][9]] | [String][1])** Component parent to check. In case a string is passed, - `component` **([[Component][9]] | [String][1])** Component parent to check. In case a string is passed,
the check will be performed on the component type. the check will be performed on the component type.
#### Examples #### Examples
```javascript ```javascript
const newTextComponent = editor.getSelected().append({ const newTextComponent = editor.getSelected().append({
type: 'text', type: "text",
components: 'My text <b>here</b>', components: "My text <b>here</b>",
})[0]; })[0];
const innerComponent = newTextComponent.find('b')[0]; const innerComponent = newTextComponent.find("b")[0];
innerComponent.isChildOf(newTextComponent); // true innerComponent.isChildOf(newTextComponent); // true
innerComponent.isChildOf('text'); // true innerComponent.isChildOf("text"); // true
``` ```
Returns **[Boolean][3]** Returns **[Boolean][3]**
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String [1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean [3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function [4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function
[5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array [5]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[6]: https://github.com/artf/grapesjs/blob/master/src/utils/Resizer.js [6]: https://github.com/artf/grapesjs/blob/master/src/utils/Resizer.js
[7]: /modules/Components-js.html [7]: /modules/Components-js.html
[8]: /modules/Traits.html [8]: /modules/Traits.html
[9]: #component [9]: #component
[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number [10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[11]: https://github.com/artf/grapesjs/issues/1936 [11]: https://github.com/artf/grapesjs/issues/1936
[12]: https://developer.mozilla.org/docs/Web/HTML/Element [12]: https://developer.mozilla.org/docs/Web/HTML/Element

85
docs/api/css_rule.md

@ -2,19 +2,19 @@
## CssRule ## CssRule
**Extends Model.extend(Styleable)** **Extends StyleableModel**
### Properties ### Properties
* `selectors` **[Array][1]\<Selector>** Array of selectors - `selectors` **[Array][1]\<Selector>** Array of selectors
* `style` **[Object][2]** Object containing style definitions - `style` **[Object][2]** Object containing style definitions
* `selectorsAdd` **[String][3]?** Additional string css selectors - `selectorsAdd` **[String][3]?** Additional string css selectors
* `atRuleType` **[String][3]?** Type of at-rule, eg. `media`, 'font-face' - `atRuleType` **[String][3]?** Type of at-rule, eg. `media`, 'font-face'
* `mediaText` **[String][3]?** At-rule value, eg. `(max-width: 1000px)` - `mediaText` **[String][3]?** At-rule value, eg. `(max-width: 1000px)`
* `singleAtRule` **[Boolean][4]?** This property is used only on at-rules, like 'page' or 'font-face', where the block containes only style declarations - `singleAtRule` **[Boolean][4]?** This property is used only on at-rules, like 'page' or 'font-face', where the block containes only style declarations
* `state` **[String][3]?** State of the rule, eg: `hover`, `focused` - `state` **[String][3]?** State of the rule, eg: `hover`, `focused`
* `important` **([Boolean][4] | [Array][1]<[String][3]>)?** If true, sets `!important` on all properties. You can also pass an array to specify properties on which use important - `important` **([Boolean][4] | [Array][1]<[String][3]>)?** If true, sets `!important` on all properties. You can also pass an array to specify properties on which use important
* `stylable` **[Boolean][4]?** Indicates if the rule is stylable from the editor[Device]: device.html[State]: state.html[Component]: component.html - `stylable` **[Boolean][4]?** Indicates if the rule is stylable from the editor[Device]: device.html[State]: state.html[Component]: component.html
### getAtRule ### getAtRule
@ -23,14 +23,18 @@ Returns the at-rule statement when exists, eg. `@media (...)`, `@keyframes`
#### Examples #### Examples
```javascript ```javascript
const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { const cssRule = editor.Css.setRule(
atRuleType: 'media', ".class1",
atRuleParams: '(min-width: 500px)' { color: "red" },
}); {
atRuleType: "media",
atRuleParams: "(min-width: 500px)",
}
);
cssRule.getAtRule(); // "@media (min-width: 500px)" cssRule.getAtRule(); // "@media (min-width: 500px)"
``` ```
Returns **[String][3]** Returns **[String][3]**
### selectorsToString ### selectorsToString
@ -38,19 +42,19 @@ Return selectors of the rule as a string
#### Parameters #### Parameters
* `opts` **[Object][2]?** Options (optional, default `{}`) - `opts` **[Object][2]?** Options (optional, default `{}`)
* `opts.skipState` **[Boolean][4]?** Skip state from the result - `opts.skipState` **[Boolean][4]?** Skip state from the result
#### Examples #### Examples
```javascript ```javascript
const cssRule = editor.Css.setRule('.class1:hover', { color: 'red' }); const cssRule = editor.Css.setRule(".class1:hover", { color: "red" });
cssRule.selectorsToString(); // ".class1:hover" cssRule.selectorsToString(); // ".class1:hover"
cssRule.selectorsToString({ skipState: true }); // ".class1" cssRule.selectorsToString({ skipState: true }); // ".class1"
``` ```
Returns **[String][3]** Returns **[String][3]**
### getDeclaration ### getDeclaration
@ -58,19 +62,23 @@ Get declaration block (without the at-rule statement)
#### Parameters #### Parameters
* `opts` **[Object][2]** Options (same as in `selectorsToString`) (optional, default `{}`) - `opts` **[Object][2]** Options (same as in `selectorsToString`) (optional, default `{}`)
#### Examples #### Examples
```javascript ```javascript
const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { const cssRule = editor.Css.setRule(
atRuleType: 'media', ".class1",
atRuleParams: '(min-width: 500px)' { color: "red" },
}); {
cssRule.getDeclaration() // ".class1{color:red;}" atRuleType: "media",
atRuleParams: "(min-width: 500px)",
}
);
cssRule.getDeclaration(); // ".class1{color:red;}"
``` ```
Returns **[String][3]** Returns **[String][3]**
### getDevice ### getDevice
@ -83,7 +91,7 @@ const device = rule.getDevice();
console.log(device?.getName()); console.log(device?.getName());
``` ```
Returns **([Device] | null)** Returns **([Device] | null)**
### getState ### getState
@ -96,7 +104,7 @@ const state = rule.getState();
console.log(state?.getLabel()); console.log(state?.getLabel());
``` ```
Returns **([State] | null)** Returns **([State] | null)**
### getComponent ### getComponent
@ -109,7 +117,7 @@ const cmp = rule.getComponent();
console.log(cmp?.toHTML()); console.log(cmp?.toHTML());
``` ```
Returns **([Component] | null)** Returns **([Component] | null)**
### toCSS ### toCSS
@ -117,24 +125,25 @@ Return the CSS string of the rule
#### Parameters #### Parameters
* `opts` **[Object][2]** Options (same as in `getDeclaration`) (optional, default `{}`) - `opts` **[Object][2]** Options (same as in `getDeclaration`) (optional, default `{}`)
#### Examples #### Examples
```javascript ```javascript
const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { const cssRule = editor.Css.setRule(
atRuleType: 'media', ".class1",
atRuleParams: '(min-width: 500px)' { color: "red" },
}); {
cssRule.toCSS() // "@media (min-width: 500px){.class1{color:red;}}" atRuleType: "media",
atRuleParams: "(min-width: 500px)",
}
);
cssRule.toCSS(); // "@media (min-width: 500px){.class1{color:red;}}"
``` ```
Returns **[String][3]** CSS string Returns **[String][3]** CSS string
[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array [1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object [2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String [3]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean [4]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean

4
src/css_composer/model/CssRule.js

@ -1,6 +1,6 @@
import { isEmpty, forEach, isString, isArray } from 'underscore'; import { isEmpty, forEach, isString, isArray } from 'underscore';
import { Model } from '../../common'; import { Model } from '../../common';
import Styleable from '../../domain_abstract/model/Styleable'; import StyleableModel from '../../domain_abstract/model/StyleableModel';
import Selectors from '../../selector_manager/model/Selectors'; import Selectors from '../../selector_manager/model/Selectors';
import { getMediaLength } from '../../code_manager/model/CssGenerator'; import { getMediaLength } from '../../code_manager/model/CssGenerator';
import { isEmptyObj, hasWin } from '../../utils/mixins'; import { isEmptyObj, hasWin } from '../../utils/mixins';
@ -23,7 +23,7 @@ const { CSS } = hasWin() ? window : {};
* [State]: state.html * [State]: state.html
* [Component]: component.html * [Component]: component.html
*/ */
export default class CssRule extends Model.extend(Styleable) { export default class CssRule extends StyleableModel {
defaults() { defaults() {
return { return {
selectors: [], selectors: [],

8
src/dom_components/model/Component.js

@ -12,7 +12,7 @@ import {
keys, keys,
} from 'underscore'; } from 'underscore';
import { shallowDiff, capitalize, isEmptyObj, isObject, toLowerCase } from 'utils/mixins'; import { shallowDiff, capitalize, isEmptyObj, isObject, toLowerCase } from 'utils/mixins';
import Styleable from 'domain_abstract/model/Styleable'; import StyleableModel from 'domain_abstract/model/StyleableModel';
import { Model } from 'backbone'; import { Model } from 'backbone';
import Components from './Components'; import Components from './Components';
import Selector from 'selector_manager/model/Selector'; import Selector from 'selector_manager/model/Selector';
@ -91,7 +91,7 @@ export const keyUpdateInside = `${keyUpdate}-inside`;
* By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). * By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`).
* @property {Collection<Component>} [components=null] Children components. Default: `null` * @property {Collection<Component>} [components=null] Children components. Default: `null`
*/ */
export default class Component extends Model.extend(Styleable) { export default class Component extends StyleableModel {
/** /**
* Hook method, called once the model is created * Hook method, called once the model is created
*/ */
@ -476,7 +476,7 @@ export default class Component extends Model.extend(Styleable) {
} }
} }
return Styleable.getStyle.call(this, prop); return super.getStyle.call(this, prop);
} }
/** /**
@ -502,7 +502,7 @@ export default class Component extends Model.extend(Styleable) {
this.set('style', '', { silent: 1 }); this.set('style', '', { silent: 1 });
keys(diff).forEach(pr => this.trigger(`change:style:${pr}`)); keys(diff).forEach(pr => this.trigger(`change:style:${pr}`));
} else { } else {
prop = Styleable.setStyle.apply(this, arguments); prop = super.setStyle.apply(this, arguments);
} }
return prop; return prop;

25
src/domain_abstract/model/Styleable.js → src/domain_abstract/model/StyleableModel.js

@ -1,11 +1,12 @@
import { isString, isArray, keys, isUndefined } from 'underscore'; import { isString, isArray, keys, isUndefined } from 'underscore';
import { shallowDiff } from '../../utils/mixins'; import { shallowDiff } from '../../utils/mixins';
import ParserHtml from '../../parser/model/ParserHtml'; import ParserHtml from '../../parser/model/ParserHtml';
import { Model } from 'common';
const parseStyle = ParserHtml().parseStyle; const parseStyle = ParserHtml().parseStyle;
export default { export default class StyleableModel extends Model {
parseStyle, parseStyle;
/** /**
* To trigger the style change event on models I have to * To trigger the style change event on models I have to
@ -15,7 +16,7 @@ export default {
*/ */
extendStyle(prop) { extendStyle(prop) {
return { ...this.getStyle(), ...prop }; return { ...this.getStyle(), ...prop };
}, }
/** /**
* Get style object * Get style object
@ -25,7 +26,7 @@ export default {
const style = this.get('style') || {}; const style = this.get('style') || {};
const result = { ...style }; const result = { ...style };
return prop && isString(prop) ? result[prop] : result; return prop && isString(prop) ? result[prop] : result;
}, }
/** /**
* Set new style object * Set new style object
@ -62,7 +63,7 @@ export default {
}); });
return propNew; return propNew;
}, }
/** /**
* Add style property * Add style property
@ -83,7 +84,7 @@ export default {
prop = this.extendStyle(prop); prop = this.extendStyle(prop);
this.setStyle(prop, opts); this.setStyle(prop, opts);
}, }
/** /**
* Remove style property * Remove style property
@ -93,7 +94,7 @@ export default {
let style = this.getStyle(); let style = this.getStyle();
delete style[prop]; delete style[prop];
this.setStyle(style); this.setStyle(style);
}, }
/** /**
* Returns string of style properties * Returns string of style properties
@ -113,15 +114,15 @@ export default {
} }
return result.join(''); return result.join('');
}, }
getSelectors() { getSelectors() {
return this.get('selectors') || this.get('classes'); return this.get('selectors') || this.get('classes');
}, }
getSelectorsString(opts) { getSelectorsString(opts) {
return this.selectorsToString ? this.selectorsToString(opts) : this.getSelectors().getFullString(); return this.selectorsToString ? this.selectorsToString(opts) : this.getSelectors().getFullString();
}, }
_validate(attr, opts) { _validate(attr, opts) {
const { style } = attr; const { style } = attr;
@ -141,5 +142,5 @@ export default {
} }
return true; return true;
}, }
}; }

2
test/specs/style_manager/view/PropertyRadioView.js

@ -101,7 +101,7 @@ describe('PropertyRadioView', () => {
setTimeout(() => { setTimeout(() => {
expect(getCheckedEl(view).value).toEqual(propValue); expect(getCheckedEl(view).value).toEqual(propValue);
done(); done();
}, 11); }, 15);
}); });
describe('Init property', () => { describe('Init property', () => {

Loading…
Cancel
Save