Skip to main content

script/dom/execcommand/commands/
forecolor.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use js::context::JSContext;
6use style::color::AbsoluteColor;
7
8use crate::dom::bindings::str::{DOMString, FromInputValueString};
9use crate::dom::document::Document;
10use crate::dom::execcommand::basecommand::CommandName;
11use crate::dom::selection::Selection;
12
13/// <https://w3c.github.io/editing/docs/execCommand/#the-forecolor-command>
14pub(crate) fn execute_forecolor_command(
15    cx: &mut JSContext,
16    document: &Document,
17    selection: &Selection,
18    value: DOMString,
19) -> bool {
20    // Step 1. If value is not a valid CSS color, prepend "#" to it.
21    let value = if !value.str().is_valid_simple_color_string() {
22        ("#".to_owned() + &*value.str()).into()
23    } else {
24        value
25    };
26    // Step 2. If value is still not a valid CSS color, or if it is currentColor, return false.
27    //
28    // TODO: figure out what to do with currentColor
29    if !value.str().is_valid_simple_color_string() {
30        return false;
31    }
32    // Step 3. Set the selection's value to value.
33    selection.set_the_selection_value(cx, Some(value), CommandName::ForeColor, document);
34    // Step 4. Return true.
35    true
36}
37
38pub(crate) fn serialize_to_simple_color(absolute_color: AbsoluteColor) -> DOMString {
39    let r = absolute_color
40        .c0()
41        .map(|v| (v * 255.0).round() as u8)
42        .unwrap_or_default();
43    let g = absolute_color
44        .c1()
45        .map(|v| (v * 255.0).round() as u8)
46        .unwrap_or_default();
47    let b = absolute_color
48        .c2()
49        .map(|v| (v * 255.0).round() as u8)
50        .unwrap_or_default();
51
52    format!("#{r:02x}{g:02x}{b:02x}").into()
53}