blitz-pdf 0.1.3 → 0.1.4

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.
Files changed (64) hide show
  1. package/README.md +6 -6
  2. package/THIRD_PARTY_NOTICES.md +5 -2
  3. package/docs/layout-regressions.md +65 -0
  4. package/docs/pagination-regressions.md +7 -6
  5. package/package.json +1 -1
  6. package/vendor/README.md +35 -0
  7. package/vendor/blitz-dom/Cargo.toml +113 -0
  8. package/vendor/blitz-dom/LICENSE-APACHE +176 -0
  9. package/vendor/blitz-dom/LICENSE-MIT +23 -0
  10. package/vendor/blitz-dom/assets/default.css +1142 -0
  11. package/vendor/blitz-dom/assets/moz-bullet-font.otf +0 -0
  12. package/vendor/blitz-dom/src/accessibility.rs +255 -0
  13. package/vendor/blitz-dom/src/config.rs +97 -0
  14. package/vendor/blitz-dom/src/cssom.rs +971 -0
  15. package/vendor/blitz-dom/src/debug.rs +206 -0
  16. package/vendor/blitz-dom/src/document.rs +3395 -0
  17. package/vendor/blitz-dom/src/events/driver.rs +427 -0
  18. package/vendor/blitz-dom/src/events/focus.rs +40 -0
  19. package/vendor/blitz-dom/src/events/ime.rs +31 -0
  20. package/vendor/blitz-dom/src/events/keyboard.rs +174 -0
  21. package/vendor/blitz-dom/src/events/mod.rs +315 -0
  22. package/vendor/blitz-dom/src/events/pointer.rs +849 -0
  23. package/vendor/blitz-dom/src/font_metrics.rs +177 -0
  24. package/vendor/blitz-dom/src/form.rs +463 -0
  25. package/vendor/blitz-dom/src/html.rs +38 -0
  26. package/vendor/blitz-dom/src/iframe.rs +186 -0
  27. package/vendor/blitz-dom/src/layout/construct.rs +1328 -0
  28. package/vendor/blitz-dom/src/layout/damage.rs +642 -0
  29. package/vendor/blitz-dom/src/layout/inline.rs +1160 -0
  30. package/vendor/blitz-dom/src/layout/list.rs +237 -0
  31. package/vendor/blitz-dom/src/layout/mod.rs +969 -0
  32. package/vendor/blitz-dom/src/layout/paint_tree.rs +462 -0
  33. package/vendor/blitz-dom/src/layout/replaced.rs +439 -0
  34. package/vendor/blitz-dom/src/layout/table.rs +967 -0
  35. package/vendor/blitz-dom/src/layout/text_transform.rs +979 -0
  36. package/vendor/blitz-dom/src/layout/writing_mode.rs +437 -0
  37. package/vendor/blitz-dom/src/lib.rs +160 -0
  38. package/vendor/blitz-dom/src/mutator.rs +1818 -0
  39. package/vendor/blitz-dom/src/net.rs +649 -0
  40. package/vendor/blitz-dom/src/node/attributes.rs +60 -0
  41. package/vendor/blitz-dom/src/node/custom_widget.rs +178 -0
  42. package/vendor/blitz-dom/src/node/element.rs +1106 -0
  43. package/vendor/blitz-dom/src/node/mod.rs +30 -0
  44. package/vendor/blitz-dom/src/node/node.rs +2036 -0
  45. package/vendor/blitz-dom/src/node/scrollbar.rs +237 -0
  46. package/vendor/blitz-dom/src/node/serialize.rs +225 -0
  47. package/vendor/blitz-dom/src/node/stylo_data.rs +142 -0
  48. package/vendor/blitz-dom/src/node/svg.rs +265 -0
  49. package/vendor/blitz-dom/src/node/text.rs +804 -0
  50. package/vendor/blitz-dom/src/query_selector.rs +275 -0
  51. package/vendor/blitz-dom/src/resolve.rs +474 -0
  52. package/vendor/blitz-dom/src/resolved_style.rs +797 -0
  53. package/vendor/blitz-dom/src/scrolling.rs +780 -0
  54. package/vendor/blitz-dom/src/selection.rs +122 -0
  55. package/vendor/blitz-dom/src/stylo.rs +1518 -0
  56. package/vendor/blitz-dom/src/stylo_device.rs +88 -0
  57. package/vendor/blitz-dom/src/stylo_to_cursor_icon.rs +49 -0
  58. package/vendor/blitz-dom/src/stylo_to_kurbo.rs +129 -0
  59. package/vendor/blitz-dom/src/stylo_to_parley.rs +655 -0
  60. package/vendor/blitz-dom/src/traversal.rs +600 -0
  61. package/vendor/blitz-dom/src/tree.rs +136 -0
  62. package/vendor/blitz-dom/src/url.rs +63 -0
  63. package/vendor/blitz-dom/src/util.rs +256 -0
  64. package/wasm/blitz_pdf_bg.wasm +0 -0
@@ -0,0 +1,177 @@
1
+ use std::sync::{Arc, Mutex};
2
+
3
+ use crate::stylo_to_parley;
4
+ use app_units::Au;
5
+ use parley::{FontContext, FontVariation};
6
+ use skrifa::MetadataProvider as _;
7
+ use skrifa::charmap::Charmap;
8
+ use style::properties::style_structs::Font as FontStyles;
9
+ use style::{
10
+ device::servo::FontMetricsProvider,
11
+ font_metrics::FontMetrics,
12
+ values::computed::{CSSPixelLength, font::QueryFontMetricsFlags},
13
+ };
14
+
15
+ /// Query fontique for the fonts matching `font_styles` (family list and attributes).
16
+ fn query_for_font_styles<'a>(
17
+ font_ctx: &'a mut FontContext,
18
+ font_styles: &'a FontStyles,
19
+ ) -> parley::fontique::Query<'a> {
20
+ use parley::fontique::Attributes;
21
+
22
+ let mut query = font_ctx.collection.query(&mut font_ctx.source_cache);
23
+ let families = font_styles
24
+ .font_family
25
+ .families
26
+ .iter()
27
+ .map(stylo_to_parley::query_font_family);
28
+ query.set_families(families);
29
+ query.set_attributes(Attributes {
30
+ width: stylo_to_parley::font_width(font_styles.font_width),
31
+ weight: stylo_to_parley::font_weight(font_styles.font_weight),
32
+ style: stylo_to_parley::font_style(font_styles.font_style),
33
+ });
34
+ query
35
+ }
36
+
37
+ #[derive(Clone)]
38
+ pub(crate) struct BlitzFontMetricsProvider {
39
+ pub(crate) font_ctx: Arc<Mutex<FontContext>>,
40
+ }
41
+
42
+ impl core::fmt::Debug for BlitzFontMetricsProvider {
43
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44
+ write!(f, "BlitzFontMetricsProvider")
45
+ }
46
+ }
47
+
48
+ impl FontMetricsProvider for BlitzFontMetricsProvider {
49
+ fn query_font_metrics(
50
+ &self,
51
+ _vertical: bool,
52
+ font_styles: &FontStyles,
53
+ font_size: CSSPixelLength,
54
+ _flags: QueryFontMetricsFlags,
55
+ ) -> FontMetrics {
56
+ use parley::fontique::{Query, QueryFont, QueryStatus};
57
+ use skrifa::instance::{LocationRef, Size};
58
+ use skrifa::metrics::{GlyphMetrics, Metrics};
59
+
60
+ // Lock font_ctx. Explicit reborrow required for borrow checker.
61
+ let mut font_ctx = self.font_ctx.lock().unwrap();
62
+ let font_ctx = &mut *font_ctx;
63
+
64
+ // Query fontique for the font that matches the font styles
65
+ let mut query = query_for_font_styles(font_ctx, font_styles);
66
+ // let fb_script = crate::swash_convert::script_to_fontique(script);
67
+ // let fb_language = locale.and_then(crate::swash_convert::locale_to_fontique);
68
+ // query.set_fallbacks(fontique::FallbackKey::new(fb_script, fb_language.as_ref()));
69
+
70
+ let variations = stylo_to_parley::font_variations(&font_styles.font_variation_settings);
71
+ // let features = self.rcx.features(style.font_features).unwrap_or(&[]);
72
+
73
+ // fn name_of(font_ref: &skrifa::FontRef) -> String {
74
+ // use skrifa::string::StringId;
75
+ // font_ref
76
+ // .localized_strings(StringId::POSTSCRIPT_NAME)
77
+ // .english_or_first()
78
+ // .unwrap()
79
+ // .chars()
80
+ // .collect()
81
+ // }
82
+
83
+ fn find_font_for(query: &mut Query, ch: char) -> Option<QueryFont> {
84
+ let mut font = None;
85
+ query.matches_with(|q_font: &QueryFont| {
86
+ use skrifa::MetadataProvider;
87
+
88
+ let Ok(font_ref) = skrifa::FontRef::from_index(q_font.blob.as_ref(), q_font.index)
89
+ else {
90
+ return QueryStatus::Continue;
91
+ };
92
+
93
+ let charmap = font_ref.charmap();
94
+ if charmap.map(ch).is_some() {
95
+ font = Some(q_font.clone());
96
+ QueryStatus::Stop
97
+ } else {
98
+ QueryStatus::Continue
99
+ }
100
+ });
101
+ font
102
+ }
103
+
104
+ /// Scales the advance the same way as Parley's shaped glyph advances (font units × size / upem)
105
+ /// rather than with skrifa's FreeType-compatible fixed-point scale, so that `ch`/`ic`
106
+ /// lengths exactly match the width of the corresponding laid-out text.
107
+ fn advance_of(
108
+ query: &mut Query,
109
+ ch: char,
110
+ font_size: f32,
111
+ variations: &[FontVariation],
112
+ ) -> Option<f32> {
113
+ let font = find_font_for(query, ch)?;
114
+ let font_ref = skrifa::FontRef::from_index(font.blob.as_ref(), font.index).ok()?;
115
+ let location = font_ref.axes().location(
116
+ variations
117
+ .iter()
118
+ .map(|v| (skrifa::Tag::from_be_bytes(v.tag.to_bytes()), v.value)),
119
+ );
120
+ let location_ref = LocationRef::from(&location);
121
+ let upem = Metrics::new(&font_ref, Size::unscaled(), location_ref).units_per_em;
122
+ if upem == 0 {
123
+ return None;
124
+ }
125
+ let glyph_metrics = GlyphMetrics::new(&font_ref, Size::unscaled(), location_ref);
126
+ let char_map = Charmap::new(&font_ref);
127
+ let glyph_id = char_map.map(ch)?;
128
+ let advance = glyph_metrics.advance_width(glyph_id)?;
129
+ Some(advance * (font_size / upem as f32))
130
+ }
131
+
132
+ fn metrics_of(
133
+ query: &mut Query,
134
+ ch: char,
135
+ font_size: Size,
136
+ variations: &[FontVariation],
137
+ ) -> Option<(f32, Option<f32>, Option<f32>)> {
138
+ let font = find_font_for(query, ch)?;
139
+ let font_ref = skrifa::FontRef::from_index(font.blob.as_ref(), font.index).ok()?;
140
+ let location = font_ref.axes().location(
141
+ variations
142
+ .iter()
143
+ .map(|v| (skrifa::Tag::from_be_bytes(v.tag.to_bytes()), v.value)),
144
+ );
145
+ let location_ref = LocationRef::from(&location);
146
+ let metrics = Metrics::new(&font_ref, font_size, location_ref);
147
+ Some((metrics.ascent, metrics.x_height, metrics.cap_height))
148
+ }
149
+
150
+ let zero_advance = advance_of(&mut query, '0', font_size.px(), &variations);
151
+ let ic_advance = advance_of(&mut query, '\u{6C34}', font_size.px(), &variations);
152
+ let (ascent, x_height, cap_height) =
153
+ metrics_of(&mut query, ' ', Size::new(font_size.px()), &variations)
154
+ .unwrap_or((0.0, None, None));
155
+
156
+ FontMetrics {
157
+ ascent: CSSPixelLength::new(ascent),
158
+ x_height: x_height.filter(|xh| *xh != 0.0).map(CSSPixelLength::new),
159
+ cap_height: cap_height.map(CSSPixelLength::new),
160
+ zero_advance_measure: zero_advance.map(CSSPixelLength::new),
161
+ ic_width: ic_advance.map(CSSPixelLength::new),
162
+ script_percent_scale_down: None,
163
+ script_script_percent_scale_down: None,
164
+ }
165
+ }
166
+
167
+ fn base_size_for_generic(
168
+ &self,
169
+ generic: style::values::computed::font::GenericFontFamily,
170
+ ) -> style::values::computed::Length {
171
+ let size = match generic {
172
+ style::values::computed::font::GenericFontFamily::Monospace => 13.0,
173
+ _ => 16.0,
174
+ };
175
+ style::values::computed::Length::from(Au::from_f32_px(size))
176
+ }
177
+ }
@@ -0,0 +1,463 @@
1
+ use blitz_traits::node_id::NodeId;
2
+ use markup5ever::{LocalName, local_name};
3
+
4
+ use crate::{
5
+ BaseDocument, ElementData,
6
+ traversal::{AncestorTraverser, TreeTraverser},
7
+ };
8
+ use blitz_traits::{
9
+ navigation::NavigationOptions,
10
+ net::{Body, Entry, EntryValue, FormData, Method},
11
+ };
12
+ use core::str::FromStr;
13
+ use std::fmt::Display;
14
+
15
+ /// https://url.spec.whatwg.org/#default-encode-set
16
+ const DEFAULT_ENCODE_SET: percent_encoding::AsciiSet = percent_encoding::CONTROLS
17
+ // Query Set
18
+ .add(b' ')
19
+ .add(b'"')
20
+ .add(b'#')
21
+ .add(b'<')
22
+ .add(b'>')
23
+ // Path Set
24
+ .add(b'?')
25
+ .add(b'`')
26
+ .add(b'{')
27
+ .add(b'}');
28
+
29
+ impl BaseDocument {
30
+ /// Resets the form owner for a given node by either using an explicit form attribute
31
+ /// or finding the nearest ancestor form element
32
+ ///
33
+ /// # Arguments
34
+ /// * `node_id` - The ID of the node whose form owner needs to be reset
35
+ ///
36
+ /// <https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#reset-the-form-owner>
37
+ pub fn reset_form_owner(&mut self, node_id: NodeId) {
38
+ let node = &self.nodes[node_id];
39
+ let Some(element) = node.element_data() else {
40
+ return;
41
+ };
42
+
43
+ // First try explicit form attribute
44
+ let final_owner_id = element
45
+ .attr(local_name!("form"))
46
+ .and_then(|owner| self.get_element_by_id(owner))
47
+ .filter(|owner_id| {
48
+ self.get_node(*owner_id)
49
+ .is_some_and(|node| node.data.is_element_with_tag_name(&local_name!("form")))
50
+ })
51
+ .or_else(|| {
52
+ AncestorTraverser::new(self, node_id).find(|ancestor_id| {
53
+ self.nodes[*ancestor_id]
54
+ .data
55
+ .is_element_with_tag_name(&local_name!("form"))
56
+ })
57
+ });
58
+
59
+ if let Some(final_owner_id) = final_owner_id {
60
+ self.controls_to_form.insert(node_id, final_owner_id);
61
+ }
62
+ }
63
+
64
+ /// Submits a form with the given form node ID and submitter node ID
65
+ ///
66
+ /// # Arguments
67
+ /// * `node_id` - The ID of the form node to submit
68
+ /// * `submitter_id` - The ID of the node that triggered the submission
69
+ ///
70
+ /// <https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-algorithm>
71
+ pub fn submit_form(&self, node_id: NodeId, submitter_id: NodeId) {
72
+ let node = &self.nodes[node_id];
73
+ let Some(element) = node.element_data() else {
74
+ return;
75
+ };
76
+
77
+ let entry = construct_entry_list(self, node_id, submitter_id);
78
+
79
+ let method = get_form_attr(
80
+ self,
81
+ element,
82
+ local_name!("method"),
83
+ submitter_id,
84
+ local_name!("formmethod"),
85
+ )
86
+ .and_then(|method| method.parse::<FormMethod>().ok())
87
+ .unwrap_or(FormMethod::Get);
88
+
89
+ let action = get_form_attr(
90
+ self,
91
+ element,
92
+ local_name!("action"),
93
+ submitter_id,
94
+ local_name!("formaction"),
95
+ )
96
+ .unwrap_or_default();
97
+
98
+ let mut parsed_action = self.resolve_url(action);
99
+
100
+ let scheme = parsed_action.scheme();
101
+
102
+ let enctype = get_form_attr(
103
+ self,
104
+ element,
105
+ local_name!("enctype"),
106
+ submitter_id,
107
+ local_name!("formenctype"),
108
+ )
109
+ .and_then(|enctype| enctype.parse::<RequestContentType>().ok())
110
+ .unwrap_or(RequestContentType::FormUrlEncoded);
111
+
112
+ let mut post_resource = Body::Empty;
113
+
114
+ match (scheme, method) {
115
+ ("http" | "https" | "data", FormMethod::Get) => {
116
+ let pairs = convert_to_list_of_name_value_pairs(entry);
117
+ let mut query = String::new();
118
+ url::form_urlencoded::Serializer::new(&mut query).extend_pairs(pairs);
119
+ parsed_action.set_query(Some(&query));
120
+ }
121
+ ("http" | "https", FormMethod::Post) => post_resource = Body::Form(entry),
122
+ ("mailto", FormMethod::Get) => {
123
+ let pairs = convert_to_list_of_name_value_pairs(entry);
124
+ parsed_action.query_pairs_mut().extend_pairs(pairs);
125
+ }
126
+ ("mailto", FormMethod::Post) => {
127
+ let pairs = convert_to_list_of_name_value_pairs(entry);
128
+ let body = match enctype {
129
+ RequestContentType::TextPlain => {
130
+ let body = encode_text_plain(&pairs);
131
+ percent_encoding::utf8_percent_encode(&body, &DEFAULT_ENCODE_SET)
132
+ .to_string()
133
+ }
134
+ _ => {
135
+ let mut body = String::new();
136
+ url::form_urlencoded::Serializer::new(&mut body).extend_pairs(pairs);
137
+ body
138
+ }
139
+ };
140
+ let mut query = if let Some(query) = parsed_action.query() {
141
+ let mut query = query.to_string();
142
+ query.push('&');
143
+ query
144
+ } else {
145
+ String::new()
146
+ };
147
+ query.push_str("body=");
148
+ query.push_str(&body);
149
+ parsed_action.set_query(Some(&query));
150
+ }
151
+ _ => {
152
+ #[cfg(feature = "tracing")]
153
+ tracing::warn!(
154
+ "Scheme {} with method {:?} is not implemented",
155
+ scheme,
156
+ method
157
+ );
158
+ return;
159
+ }
160
+ }
161
+
162
+ let method = method.try_into().unwrap_or_default();
163
+
164
+ let navigation_options =
165
+ NavigationOptions::new(parsed_action, Some(enctype.to_string()), self.id())
166
+ .set_document_resource(post_resource)
167
+ .set_method(method);
168
+
169
+ self.navigation_provider.navigate_to(navigation_options)
170
+ }
171
+ }
172
+
173
+ /// Constructs a list of form entries from form controls
174
+ ///
175
+ /// # Arguments
176
+ /// * `doc` - Reference to the base document
177
+ /// * `form_id` - ID of the form element
178
+ /// * `submitter_id` - ID of the element that triggered form submission
179
+ ///
180
+ /// # Returns
181
+ /// Returns an EntryList containing all valid form control entries
182
+ ///
183
+ /// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set
184
+ fn construct_entry_list(doc: &BaseDocument, form_id: NodeId, submitter_id: NodeId) -> FormData {
185
+ let mut entry_list = FormData::new();
186
+
187
+ let mut create_entry = |name: &str, value: EntryValue| {
188
+ entry_list.0.push(Entry {
189
+ name: name.to_string(),
190
+ value,
191
+ });
192
+ };
193
+
194
+ fn datalist_ancestor(doc: &BaseDocument, node_id: NodeId) -> bool {
195
+ AncestorTraverser::new(doc, node_id).any(|node_id| {
196
+ doc.nodes[node_id]
197
+ .data
198
+ .is_element_with_tag_name(&local_name!("datalist"))
199
+ })
200
+ }
201
+
202
+ // For each element field in controls, in tree order:
203
+ for control_id in TreeTraverser::new(doc) {
204
+ let Some(node) = doc.get_node(control_id) else {
205
+ continue;
206
+ };
207
+ let Some(element) = node.element_data() else {
208
+ continue;
209
+ };
210
+
211
+ // Check if the form owner is same as form_id
212
+ if doc
213
+ .controls_to_form
214
+ .get(&control_id)
215
+ .map(|owner_id| *owner_id != form_id)
216
+ .unwrap_or(true)
217
+ {
218
+ continue;
219
+ }
220
+
221
+ let element_type = element.attr(local_name!("type"));
222
+
223
+ // If any of the following are true:
224
+ // field has a datalist element ancestor;
225
+ // field is disabled;
226
+ // field is a button but it is not submitter;
227
+ // field is an input element whose type attribute is in the Checkbox state and whose checkedness is false; or
228
+ // field is an input element whose type attribute is in the Radio Button state and whose checkedness is false,
229
+ // then continue.
230
+ if datalist_ancestor(doc, node.id)
231
+ || element.attr(local_name!("disabled")).is_some()
232
+ || (element.name.local == local_name!("button") && node.id != submitter_id)
233
+ || element.name.local == local_name!("input")
234
+ && ((matches!(element_type, Some("checkbox" | "radio"))
235
+ && !element.checkbox_input_checked().unwrap_or(false))
236
+ || matches!(element_type, Some("submit" | "button")))
237
+ {
238
+ continue;
239
+ }
240
+
241
+ // If the field element is an input element whose type attribute is in the Image Button state, then:
242
+ if element_type == Some("image") {
243
+ // If the field element is not submitter, then continue.
244
+ if node.id != submitter_id {
245
+ continue;
246
+ }
247
+ // TODO: If the field element has a name attribute specified and its value is not the empty string, let name be that value followed by U+002E (.). Otherwise, let name be the empty string.
248
+ // Let namex be the concatenation of name and U+0078 (x).
249
+ // Let namey be the concatenation of name and U+0079 (y).
250
+ // Let (x, y) be the selected coordinate.
251
+ // Create an entry with namex and x, and append it to entry list.
252
+ // Create an entry with namey and y, and append it to entry list.
253
+ // Continue.
254
+ continue;
255
+ }
256
+
257
+ // TODO: If the field is a form-associated custom element,
258
+ // then perform the entry construction algorithm given field and entry list,
259
+ // then continue.
260
+
261
+ // If either the field element does not have a name attribute specified, or its name attribute's value is the empty string, then continue.
262
+ // Let name be the value of the field element's name attribute.
263
+ let Some(name) = element
264
+ .attr(local_name!("name"))
265
+ .filter(|str| !str.is_empty())
266
+ else {
267
+ continue;
268
+ };
269
+
270
+ // TODO: If the field element is a select element,
271
+ // then for each option element in the select element's
272
+ // list of options whose selectedness is true and that is not disabled,
273
+ // create an entry with name and the value of the option element,
274
+ // and append it to entry list.
275
+
276
+ // Otherwise, if the field element is an input element whose type attribute is in the Checkbox state or the Radio Button state, then:
277
+ if element.name.local == local_name!("input")
278
+ && matches!(element_type, Some("checkbox" | "radio"))
279
+ {
280
+ // If the field element has a value attribute specified, then let value be the value of that attribute; otherwise, let value be the string "on".
281
+ let value = element.attr(local_name!("value")).unwrap_or("on");
282
+ // Create an entry with name and value, and append it to entry list.
283
+ create_entry(name, value.into());
284
+ continue;
285
+ }
286
+ // Otherwise, if the field element is an input element whose type attribute is in the File Upload state, then:
287
+ #[cfg(feature = "file-input")]
288
+ if element.name.local == local_name!("input") && matches!(element_type, Some("file")) {
289
+ // If there are no selected files, then create an entry with name and a new File object with an empty name, application/octet-stream as type, and an empty body, and append it to entry list.
290
+ let Some(files) = element.file_data() else {
291
+ create_entry(name, EntryValue::EmptyFile);
292
+ continue;
293
+ };
294
+ if files.is_empty() {
295
+ create_entry(name, EntryValue::EmptyFile);
296
+ }
297
+ // Otherwise, for each file in selected files, create an entry with name and a File object representing the file, and append it to entry list.
298
+ else {
299
+ for path_buf in files.iter() {
300
+ create_entry(name, path_buf.clone().into());
301
+ }
302
+ }
303
+ continue;
304
+ }
305
+ //Otherwise, if the field element is an input element whose type attribute is in the Hidden state and name is an ASCII case-insensitive match for "_charset_":
306
+ if element.name.local == local_name!("input")
307
+ && element_type == Some("hidden")
308
+ && name.eq_ignore_ascii_case("_charset_")
309
+ {
310
+ // Let charset be the name of encoding.
311
+ let charset = "UTF-8"; // TODO: Support multiple encodings.
312
+ // Create an entry with name and charset, and append it to entry list.
313
+ create_entry(name, charset.into());
314
+ }
315
+ // Otherwise, create an entry with name and the value of the field element, and append it to entry list.
316
+ else if let Some(text) = element.text_input_data() {
317
+ create_entry(name, text.editor.text().to_string().as_str().into());
318
+ } else if let Some(value) = element.attr(local_name!("value")) {
319
+ create_entry(name, value.into());
320
+ }
321
+ }
322
+ entry_list
323
+ }
324
+
325
+ fn get_form_attr<'a>(
326
+ doc: &'a BaseDocument,
327
+ form: &'a ElementData,
328
+ form_local: impl PartialEq<LocalName>,
329
+ submitter_id: NodeId,
330
+ submitter_local: impl PartialEq<LocalName>,
331
+ ) -> Option<&'a str> {
332
+ get_submitter_attr(doc, submitter_id, submitter_local).or_else(|| form.attr(form_local))
333
+ }
334
+
335
+ fn get_submitter_attr(
336
+ doc: &BaseDocument,
337
+ submitter_id: NodeId,
338
+ local_name: impl PartialEq<LocalName>,
339
+ ) -> Option<&str> {
340
+ doc.get_node(submitter_id)
341
+ .and_then(|node| node.element_data())
342
+ .and_then(|element_data| {
343
+ if element_data.name.local == local_name!("button")
344
+ && element_data.attr(local_name!("type")) == Some("submit")
345
+ {
346
+ element_data.attr(local_name)
347
+ } else {
348
+ None
349
+ }
350
+ })
351
+ }
352
+
353
+ #[derive(Debug, Copy, Clone, PartialEq, Eq)]
354
+ enum FormMethod {
355
+ Get,
356
+ Post,
357
+ Dialog,
358
+ }
359
+ impl FromStr for FormMethod {
360
+ type Err = ();
361
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
362
+ Ok(match s.to_lowercase().as_str() {
363
+ "get" => FormMethod::Get,
364
+ "post" => FormMethod::Post,
365
+ "dialog" => FormMethod::Dialog,
366
+ _ => return Err(()),
367
+ })
368
+ }
369
+ }
370
+ impl TryFrom<FormMethod> for Method {
371
+ type Error = &'static str;
372
+ fn try_from(method: FormMethod) -> Result<Self, Self::Error> {
373
+ Ok(match method {
374
+ FormMethod::Get => Method::GET,
375
+ FormMethod::Post => Method::POST,
376
+ FormMethod::Dialog => return Err("Dialog is not an HTTP method"),
377
+ })
378
+ }
379
+ }
380
+ /// Supported content types for HTTP requests
381
+ #[derive(Debug, Clone)]
382
+ pub enum RequestContentType {
383
+ /// application/x-www-form-urlencoded
384
+ FormUrlEncoded,
385
+ /// multipart/form-data
386
+ MultipartFormData,
387
+ /// text/plain
388
+ TextPlain,
389
+ }
390
+
391
+ impl FromStr for RequestContentType {
392
+ type Err = ();
393
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
394
+ Ok(match s {
395
+ "application/x-www-form-urlencoded" => RequestContentType::FormUrlEncoded,
396
+ "multipart/form-data" => RequestContentType::MultipartFormData,
397
+ "text/plain" => RequestContentType::TextPlain,
398
+ _ => return Err(()),
399
+ })
400
+ }
401
+ }
402
+
403
+ impl Display for RequestContentType {
404
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405
+ match self {
406
+ RequestContentType::FormUrlEncoded => write!(f, "application/x-www-form-urlencoded"),
407
+ RequestContentType::MultipartFormData => write!(f, "multipart/form-data"),
408
+ RequestContentType::TextPlain => write!(f, "text/plain"),
409
+ }
410
+ }
411
+ }
412
+
413
+ /// Converts the entry list to a vector of name-value pairs with normalized line endings
414
+ /// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
415
+ fn convert_to_list_of_name_value_pairs(form_data: FormData) -> Vec<(String, String)> {
416
+ form_data
417
+ .iter()
418
+ .map(|Entry { name, value }| {
419
+ let name = normalize_line_endings(name.as_ref());
420
+ let value = normalize_line_endings(value.as_ref());
421
+ (name, value)
422
+ })
423
+ .collect()
424
+ }
425
+
426
+ /// Normalizes line endings in a string according to HTML spec
427
+ /// Converts single CR or LF to CRLF pairs according to HTML form submission requirements
428
+ fn normalize_line_endings(input: &str) -> String {
429
+ // Replace every occurrence of U+000D (CR) not followed by U+000A (LF),
430
+ // and every occurrence of U+000A (LF) not preceded by U+000D (CR),
431
+ // in value, by a string consisting of U+000D (CR) and U+000A (LF).
432
+
433
+ let mut result = String::with_capacity(input.len());
434
+ let mut chars = input.chars().peekable();
435
+
436
+ while let Some(current) = chars.next() {
437
+ match (current, chars.peek()) {
438
+ ('\r', Some('\n')) => {
439
+ result.push_str("\r\n");
440
+ chars.next();
441
+ }
442
+ ('\r' | '\n', _) => {
443
+ result.push_str("\r\n");
444
+ }
445
+ _ => result.push(current),
446
+ }
447
+ }
448
+
449
+ result
450
+ }
451
+
452
+ /// Encodes form data as text/plain according to HTML spec given an slice of name-value pairs
453
+ /// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#text/plain-encoding-algorithm
454
+ fn encode_text_plain<T: AsRef<str>, U: AsRef<str>>(input: &[(T, U)]) -> String {
455
+ let mut out = String::new();
456
+ for (name, value) in input {
457
+ out.push_str(name.as_ref());
458
+ out.push('=');
459
+ out.push_str(value.as_ref());
460
+ out.push_str("\r\n");
461
+ }
462
+ out
463
+ }
@@ -0,0 +1,38 @@
1
+ use crate::{BaseDocument, Document, DocumentConfig, DocumentMutator, PlainDocument};
2
+ use blitz_traits::node_id::NodeId;
3
+
4
+ pub trait HtmlParserProvider {
5
+ fn parse_inner_html<'m, 'doc>(
6
+ &self,
7
+ mutr: &'m mut DocumentMutator<'doc>,
8
+ element_id: NodeId,
9
+ html: &str,
10
+ );
11
+
12
+ /// Parse a full HTML document (e.g. the contents of an `<iframe>`).
13
+ ///
14
+ /// The default implementation ignores the HTML and returns an empty document.
15
+ fn parse_document(&self, html: &str, config: DocumentConfig) -> Box<dyn Document> {
16
+ let _ = html;
17
+ Box::new(PlainDocument(BaseDocument::new(config)))
18
+ }
19
+ }
20
+
21
+ pub struct DummyHtmlParserProvider;
22
+ impl HtmlParserProvider for DummyHtmlParserProvider {
23
+ fn parse_inner_html<'m, 'doc>(
24
+ &self,
25
+ mutr: &'m mut DocumentMutator<'doc>,
26
+ element_id: NodeId,
27
+ html: &str,
28
+ ) {
29
+ let _ = mutr;
30
+ let _ = element_id;
31
+ let _ = html;
32
+ // Do nothing for now
33
+ //
34
+ // TODO: do something:
35
+ // - Print warning?
36
+ // - Parse HTML as plain text?
37
+ }
38
+ }