mosaic-headless 1.32.2 → 1.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -68,6 +68,8 @@ import os
68
68
  import re
69
69
  import sys
70
70
 
71
+ from inline_html import blocks_from_html, inline_children
72
+
71
73
  # Elementor's responsive suffix -> Mosaic's breakpoint key. Elementor also has
72
74
  # `_widescreen`/`_laptop` etc. on some installs; anything not in this map is
73
75
  # reported rather than folded into the desktop value.
@@ -248,7 +250,7 @@ def as_heading(el, ctx):
248
250
  if tag not in ("h1", "h2", "h3", "h4", "h5", "h6", "p", "div", "span"):
249
251
  tag = "h2"
250
252
  node = {"type": "text", "data": {"tagName": tag, "attrID": ctx.attr(el)},
251
- "text": s.get("title") or ""}
253
+ "children": inline_children(s.get("title") or "")}
252
254
  node = styled(node, s)
253
255
  return ctx.maybe_link(node, s.get("link"), el)
254
256
 
@@ -256,11 +258,16 @@ def as_heading(el, ctx):
256
258
  @handler("text-editor", "e-paragraph")
257
259
  def as_text(el, ctx):
258
260
  s = el.get("settings") or {}
259
- # Elementor's editor content is HTML. It goes into the wysiwyg child, which
260
- # is what that child is for - the same path every text node on the worked
261
- # example uses.
262
- node = {"type": "text", "data": {"tagName": "div", "attrID": ctx.attr(el)},
263
- "text": s.get("editor") or ""}
261
+ # Elementor's editor content is HTML. Through 1.0.10 it could go into one
262
+ # wysiwyg-text run as-is; since 1.0.11 a run escapes `<` and `>`, so the
263
+ # paragraphs, bold, links and breaks arrive as literal tags. It is parsed
264
+ # into text / list nodes with wysiwyg-span / -link / -linebreak inside.
265
+ blocks = blocks_from_html(s.get("editor") or "")
266
+ if len(blocks) == 1 and blocks[0]["type"] == "text":
267
+ node = blocks[0]
268
+ node["data"]["attrID"] = ctx.attr(el)
269
+ else:
270
+ node = {"type": "div", "data": {"attrID": ctx.attr(el)}, "children": blocks}
264
271
  return styled(node, s)
265
272
 
266
273
 
@@ -279,7 +286,7 @@ def as_button(el, ctx):
279
286
  if link.get("nofollow"):
280
287
  data["rel"] = "nofollow"
281
288
  node = {"type": "button", "data": data,
282
- "text": s.get("text") or s.get("button_text") or ""}
289
+ "children": inline_children(s.get("text") or s.get("button_text") or "")}
283
290
  extra = {}
284
291
  if colour(s.get("button_text_color")):
285
292
  extra["color"] = s["button_text_color"]
@@ -366,7 +373,7 @@ def as_icon_list(el, ctx):
366
373
  {"type": "text",
367
374
  "data": {"tagName": "span",
368
375
  "attrID": "%s-i%dt" % (ctx.attr(el, bump=False), i)},
369
- "text": it.get("text") or ""}, it.get("link"), el)]}
376
+ "children": inline_children(it.get("text") or "")}, it.get("link"), el)]}
370
377
  rows.append(row)
371
378
  # The icon itself is an Elementor icon-library reference (`selected_icon`
372
379
  # -> {value: "fas fa-check", library: "fa-solid"}). Mosaic's `icon` type
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env python3
2
+ """Turn an HTML fragment into Mosaic text nodes - for content that arrives as HTML.
3
+
4
+ Since 1.0.11 a `wysiwyg-text` run escapes `<` and `>` on output
5
+ (WysiwygTextNodeMResource::getEscapedText), so `<strong>` or `<br>` inside a run
6
+ prints as literal characters. Formatting has to be nodes:
7
+
8
+ <strong>/<b> wysiwyg-span, fontWeight 700
9
+ <em>/<i> wysiwyg-span, fontStyle italic
10
+ <u> wysiwyg-span, textDecorationLine underline
11
+ <s>/<del> wysiwyg-span, textDecorationLine line-through
12
+ <a href> wysiwyg-link with url (+ target, rel)
13
+ <br> wysiwyg-linebreak
14
+ other inline their children, unwrapped
15
+ <p>, <h1>-<h6>, <div>, <blockquote>
16
+ one `text` node per block, tagName kept
17
+ <ul>/<ol> list > list-item ; <ol> gets listType "1"
18
+
19
+ Text is stored the way a run is meant to hold it - HTML with `&`, `<` and `>`
20
+ escaped - so an entity in the source prints as its character on every version.
21
+
22
+ blocks_from_html(html) -> list of nodes (text / list), for a block container
23
+ inline_children(html) -> list of inline nodes, for one text-holding node
24
+ """
25
+ import html as _html
26
+ from html.parser import HTMLParser
27
+
28
+ BLOCK = {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "section",
29
+ "article", "header", "footer", "figure", "figcaption", "pre"}
30
+ LIST = {"ul", "ol"}
31
+ VOID = {"br", "img", "hr", "wbr", "input", "meta", "link", "source"}
32
+ SPAN_STYLE = {
33
+ "strong": {"fontWeight": "700"}, "b": {"fontWeight": "700"},
34
+ "em": {"fontStyle": "italic"}, "i": {"fontStyle": "italic"},
35
+ "u": {"textDecorationLine": "underline"},
36
+ "s": {"textDecorationLine": "line-through"}, "del": {"textDecorationLine": "line-through"},
37
+ "strike": {"textDecorationLine": "line-through"},
38
+ }
39
+ TEXT_TAGS = {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote"}
40
+
41
+
42
+ class _Tree(HTMLParser):
43
+ """A minimal DOM: [tag, attrs, children] lists and plain strings."""
44
+
45
+ def __init__(self):
46
+ super().__init__(convert_charrefs=True)
47
+ self.root = ["#root", {}, []]
48
+ self.stack = [self.root]
49
+
50
+ def handle_starttag(self, tag, attrs):
51
+ el = [tag, dict(attrs), []]
52
+ self.stack[-1][2].append(el)
53
+ if tag not in VOID:
54
+ self.stack.append(el)
55
+
56
+ def handle_startendtag(self, tag, attrs):
57
+ self.stack[-1][2].append([tag, dict(attrs), []])
58
+
59
+ def handle_endtag(self, tag):
60
+ for i in range(len(self.stack) - 1, 0, -1):
61
+ if self.stack[i][0] == tag:
62
+ del self.stack[i:]
63
+ return
64
+
65
+ def handle_data(self, data):
66
+ self.stack[-1][2].append(data)
67
+
68
+
69
+ def _parse(fragment):
70
+ t = _Tree()
71
+ t.feed(fragment or "")
72
+ t.close()
73
+ return t.root[2]
74
+
75
+
76
+ def _run(text):
77
+ return {"type": "wysiwyg-text", "data": {"text": _html.escape(text, quote=False)}}
78
+
79
+
80
+ def _inline(nodes):
81
+ out = []
82
+ for n in nodes:
83
+ if isinstance(n, str):
84
+ if n:
85
+ if out and out[-1]["type"] == "wysiwyg-text":
86
+ out[-1]["data"]["text"] += _html.escape(n, quote=False)
87
+ else:
88
+ out.append(_run(n))
89
+ continue
90
+ tag, attrs, kids = n
91
+ if tag == "br":
92
+ out.append({"type": "wysiwyg-linebreak", "data": {}})
93
+ elif tag == "a" and attrs.get("href"):
94
+ data = {"url": attrs["href"]}
95
+ if attrs.get("target") in ("_self", "_blank", "_parent", "_top"):
96
+ data["target"] = attrs["target"]
97
+ if attrs.get("rel"):
98
+ data["rel"] = attrs["rel"]
99
+ out.append({"type": "wysiwyg-link", "data": data, "children": _inline(kids)})
100
+ elif tag in SPAN_STYLE:
101
+ out.append({"type": "wysiwyg-span", "data": {},
102
+ "style": {"&": {"_": dict(SPAN_STYLE[tag])}},
103
+ "children": _inline(kids)})
104
+ elif tag in VOID:
105
+ continue
106
+ else:
107
+ out.extend(_inline(kids))
108
+ # trim the whitespace HTML source formatting leaves at the edges
109
+ if out and out[0]["type"] == "wysiwyg-text":
110
+ out[0]["data"]["text"] = out[0]["data"]["text"].lstrip()
111
+ if out and out[-1]["type"] == "wysiwyg-text":
112
+ out[-1]["data"]["text"] = out[-1]["data"]["text"].rstrip()
113
+ return [o for o in out if not (o["type"] == "wysiwyg-text" and not o["data"]["text"])]
114
+
115
+
116
+ def inline_children(fragment):
117
+ return _inline(_parse(fragment))
118
+
119
+
120
+ def _blocks(nodes):
121
+ out, pending = [], []
122
+
123
+ def flush():
124
+ kids = _inline(pending)
125
+ if kids:
126
+ out.append({"type": "text", "data": {"tagName": "p"}, "children": kids})
127
+ pending.clear()
128
+
129
+ for n in nodes:
130
+ if isinstance(n, str) or (n[0] not in BLOCK and n[0] not in LIST):
131
+ pending.append(n)
132
+ continue
133
+ flush()
134
+ tag, attrs, kids = n
135
+ if tag in LIST:
136
+ items = []
137
+ for li in kids:
138
+ if isinstance(li, list) and li[0] == "li":
139
+ items.append({"type": "list-item", "data": {}, "children": _inline(li[2])})
140
+ if items:
141
+ data = {"listType": "1"} if tag == "ol" else {}
142
+ out.append({"type": "list", "data": data, "children": items})
143
+ elif any(isinstance(k, list) and (k[0] in BLOCK or k[0] in LIST) for k in kids):
144
+ out.extend(_blocks(kids)) # a div of paragraphs: flatten
145
+ else:
146
+ ch = _inline(kids)
147
+ if ch:
148
+ out.append({"type": "text", "data": {"tagName": tag if tag in TEXT_TAGS else "p"},
149
+ "children": ch})
150
+ flush()
151
+ return out
152
+
153
+
154
+ def blocks_from_html(fragment):
155
+ return _blocks(_parse(fragment))
156
+
157
+
158
+ if __name__ == "__main__":
159
+ import json
160
+ import sys
161
+ print(json.dumps(blocks_from_html(sys.stdin.read()), ensure_ascii=False, indent=1))