@omnisass/library 0.2.0 → 0.3.0

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 (81) hide show
  1. package/CHANGELOG.md +101 -3
  2. package/README.md +94 -0
  3. package/modules/utilities/converters/_convert-camel2kebab.scss +5 -4
  4. package/modules/utilities/converters/_convert-em2px.scss +5 -3
  5. package/modules/utilities/converters/_convert-hex2rgb.scss +4 -0
  6. package/modules/utilities/converters/_convert-hex2rgba.scss +5 -0
  7. package/modules/utilities/converters/_convert-kebab2camel.scss +5 -4
  8. package/modules/utilities/converters/_convert-kebab2snake.scss +4 -4
  9. package/modules/utilities/converters/_convert-px2em.scss +5 -4
  10. package/modules/utilities/converters/_convert-px2rem.scss +5 -4
  11. package/modules/utilities/converters/_convert-rem2px.scss +5 -3
  12. package/modules/utilities/converters/_convert-snake2kebab.scss +4 -4
  13. package/modules/utilities/getters/color/_get-color-brightness.scss +4 -0
  14. package/modules/utilities/getters/color/_get-color-darkest.scss +5 -1
  15. package/modules/utilities/getters/list/_get-list-item-end.scss +4 -2
  16. package/modules/utilities/getters/list/_get-list-item-start.scss +4 -2
  17. package/modules/utilities/getters/list/_get-list-item.scss +6 -4
  18. package/modules/utilities/getters/number/_get-number-from-percent.scss +6 -2
  19. package/modules/utilities/getters/number/_get-number-height-by-ratio.scss +5 -0
  20. package/modules/utilities/getters/number/_get-number-max.scss +4 -0
  21. package/modules/utilities/getters/number/_get-number-min.scss +4 -0
  22. package/modules/utilities/getters/number/_get-number-percentage-of.scss +6 -1
  23. package/modules/utilities/getters/number/_get-number-unit.scss +4 -2
  24. package/modules/utilities/getters/number/_get-number-width-by-ratio.scss +5 -0
  25. package/modules/utilities/helpers/color/_color-blend-steps.scss +6 -0
  26. package/modules/utilities/helpers/color/_color-blend.scss +6 -0
  27. package/modules/utilities/helpers/color/_color-hue-shift.scss +5 -0
  28. package/modules/utilities/helpers/color/_color-scale.scss +5 -0
  29. package/modules/utilities/helpers/color/_color-shade.scss +5 -0
  30. package/modules/utilities/helpers/color/_color-tint.scss +5 -0
  31. package/modules/utilities/helpers/color/_color-triad.scss +4 -1
  32. package/modules/utilities/helpers/list/_list-dedupe.scss +4 -0
  33. package/modules/utilities/helpers/list/_list-insert-at.scss +5 -0
  34. package/modules/utilities/helpers/list/_list-merge.scss +54 -8
  35. package/modules/utilities/helpers/list/_list-remove-at.scss +5 -0
  36. package/modules/utilities/helpers/list/_list-sum-numbers-safe.scss +3 -0
  37. package/modules/utilities/helpers/list/_list-sum-numbers.scss +3 -0
  38. package/modules/utilities/helpers/misc/_url-encode.scss +5 -6
  39. package/modules/utilities/helpers/number/_number-ceil-to.scss +56 -4
  40. package/modules/utilities/helpers/number/_number-clamp-max.scss +65 -10
  41. package/modules/utilities/helpers/number/_number-clamp-min.scss +65 -10
  42. package/modules/utilities/helpers/number/_number-clamp.scss +88 -12
  43. package/modules/utilities/helpers/number/_number-denormalize.scss +87 -9
  44. package/modules/utilities/helpers/number/_number-fibonacci.scss +62 -9
  45. package/modules/utilities/helpers/number/_number-floor-to.scss +57 -3
  46. package/modules/utilities/helpers/number/_number-format-with-separator.scss +99 -16
  47. package/modules/utilities/helpers/number/_number-normalize.scss +88 -10
  48. package/modules/utilities/helpers/number/_number-random-between-int.scss +74 -13
  49. package/modules/utilities/helpers/number/_number-random-between.scss +76 -15
  50. package/modules/utilities/helpers/number/_number-range.scss +105 -12
  51. package/modules/utilities/helpers/number/_number-round-to-nearest.scss +58 -1
  52. package/modules/utilities/helpers/number/_number-round-to.scss +65 -2
  53. package/modules/utilities/helpers/number/_number-strip-unit.scss +43 -9
  54. package/modules/utilities/helpers/string/_string-capitalize.scss +46 -5
  55. package/modules/utilities/helpers/string/_string-replace.scss +82 -4
  56. package/modules/utilities/helpers/string/_string-trim-end.scss +49 -6
  57. package/modules/utilities/helpers/string/_string-trim-start.scss +49 -6
  58. package/modules/utilities/helpers/string/_string-trim.scss +56 -11
  59. package/modules/utilities/loggers/_log-invalid-type.scss +1 -1
  60. package/modules/utilities/loggers/_log-invalid-value.scss +1 -1
  61. package/modules/utilities/validators/color/_is-color-light.scss +61 -4
  62. package/modules/utilities/validators/color/_is-color-list.scss +41 -9
  63. package/modules/utilities/validators/list/_is-list-contained.scss +42 -3
  64. package/modules/utilities/validators/misc/_is-time.scss +29 -0
  65. package/modules/utilities/validators/number/_is-int-even.scss +50 -8
  66. package/modules/utilities/validators/number/_is-int-odd.scss +51 -9
  67. package/modules/utilities/validators/number/_is-int.scss +71 -12
  68. package/modules/utilities/validators/number/_is-number-has-unit.scss +55 -13
  69. package/modules/utilities/validators/number/_is-number-negative.scss +53 -11
  70. package/modules/utilities/validators/number/_is-number-positive.scss +52 -10
  71. package/modules/utilities/validators/number/_is-number-unitless.scss +53 -12
  72. package/modules/utilities/validators/number/_is-number-zero.scss +54 -10
  73. package/modules/utilities/validators/string/_is-string-contained.scss +59 -4
  74. package/modules/utilities/validators/string/_is-string-empty.scss +48 -8
  75. package/modules/utilities/validators/string/_is-string-ending-with.scss +64 -5
  76. package/modules/utilities/validators/string/_is-string-starting-with.scss +60 -8
  77. package/package.json +1 -1
  78. package/package.scss +9 -8
  79. package/test.md +0 -168
  80. package/test.scss +0 -405
  81. package/test.sh +0 -149
package/test.md DELETED
@@ -1,168 +0,0 @@
1
- Напиши мне комментарии SassDoc для этой функции:
2
-
3
- ```scss
4
- @function convert-camel2kebab($value) {
5
-
6
- $-result: '';
7
- $-length: string.length($value);
8
-
9
- @for $i from 1 through $-length {
10
-
11
- $-char: string.slice($value, $i, $i);
12
-
13
- @if $-char == string.to-upper-case($-char) and $i > 1 {
14
- $-result: $-result + '-' + string.to-lower-case($-char);
15
- } @else {
16
- $-result: $-result + string.to-lower-case($-char);
17
- }
18
-
19
- }
20
-
21
- @return $-result;
22
-
23
- }
24
- ```
25
- но, так, как это сделано на примере этой функции:
26
-
27
- ```scss
28
- /// Конвертирует значения из относительных единиц (`em`) в
29
- /// пиксели (`px`).
30
- ///
31
- /// Функция выполняет преобразование значений в единицах `em`
32
- /// в пиксели относительно заданного базового размера. Это
33
- /// особенно полезно для обратных расчетов, когда необходимо
34
- /// получить точное пиксельное значение из относительного,
35
- /// учитывая контекст родительского элемента.
36
- ///
37
- /// Важные особенности функции:
38
- /// - Преобразует `em` в `px` с указанием единиц `px`
39
- /// - Поддерживает кастомный базовый размер (по умолчанию 16px)
40
- /// - Удаляет единицы измерения для корректного математического
41
- /// расчета
42
- /// - Возвращает результат с единицами `px` для семантической
43
- /// ясности
44
- /// - Обрабатывает целые и дробные значения
45
- /// - Полезен для расчета точных размеров из относительных
46
- /// величин
47
- /// - Обеспечивает обратное преобразование к `convert-px2em`
48
- /// - Учитывает относительную природу `em` единиц
49
- /// ---
50
- /// @name convert-em2px
51
- /// @group utilities-converters
52
- /// @since 2025.12.27
53
- /// @access public
54
- /// @author Murad Rustamov (therteenten)
55
- /// @link https://sourcecraft.dev/users/therteenten/overview SourceCraft - therteenten
56
- /// @link https://sourcecraft.dev/omnisass/library SourceCraft - OmniSass
57
- /// @link https://sass-lang.com/documentation/values/numbers См. также: Официальная документация Sass - Тип данных "Числа"
58
- /// @link https://sass-lang.com/documentation/values/numbers#units См. также: Официальная документация Sass - Единицы измерения в числах
59
- /// @link https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units См. также: MDN Web Docs - Значения и единицы измерения CSS
60
- /// @link https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Sizing_items_in_CSS См. также: MDN Web Docs - Размеры элементов в CSS
61
- /// @link https://developer.mozilla.org/en-US/docs/Web/CSS/length См. также: MDN Web Docs - CSS-тип <length>
62
- /// @link https://css-tricks.com/snippets/sass/ См. также: CSS-Tricks - Коллекция сниппетов Sass
63
- /// @link https://css-tricks.com/snippets/css/guide-to-em-and-rem-units-in-css/ См. также: CSS-Tricks - Руководство по em и rem единицам в CSS
64
- /// @link https://sass-guidelin.es/ru/#section-41 См. также: Sass Guidelines - Раздел про математические операции
65
- /// @link https://www.w3schools.com/css/css_units.asp См. также: W3Schools - CSS единицы измерения
66
- /// @example scss - Стандартное преобразование (базовый размер 16px)
67
- /// @debug convert-em2px(1em); // 16px
68
- /// @debug convert-em2px(0.5em); // 8px
69
- /// @debug convert-em2px(1.5em); // 24px
70
- /// @debug convert-em2px(2em); // 32px
71
- /// @debug convert-em2px(3em); // 48px
72
- /// @debug convert-em2px(0.25em); // 4px
73
- /// @debug convert-em2px(0.0625em); // 1px
74
- /// @example scss - Дробные значения em
75
- /// @debug convert-em2px(0.78125em); // 12.5px
76
- /// @debug convert-em2px(1.171875em); // 18.75px
77
- /// @debug convert-em2px(0.03125em); // 0.5px
78
- /// @debug convert-em2px(0.9em); // 14.4px
79
- /// @debug convert-em2px(1.125em); // 18px
80
- /// @debug convert-em2px(1.333em); // 21.328px
81
- /// @example scss - Кастомный базовый размер
82
- /// @debug convert-em2px(1em, 10px); // 10px (база 10px)
83
- /// @debug convert-em2px(2em, 10px); // 20px (база 10px)
84
- /// @debug convert-em2px(0.8em, 10px); // 8px (база 10px)
85
- /// @debug convert-em2px(0.8em, 20px); // 16px (база 20px)
86
- /// @debug convert-em2px(1.2em, 20px); // 24px (база 20px)
87
- /// @debug convert-em2px(0.5em, 20px); // 10px (база 20px)
88
- /// @example scss - Граничные случаи
89
- /// @debug convert-em2px(0em); // 0px
90
- /// @debug convert-em2px(0em, 16px); // 0px
91
- /// @debug convert-em2px(10em); // 160px
92
- /// @debug convert-em2px(62.5em); // 1000px
93
- /// @debug convert-em2px(0.01em, 100px); // 1px
94
- /// @debug convert-em2px(100em); // 1600px
95
- /// @example scss - Отрицательные значения
96
- /// @debug convert-em2px(-1em); // -16px
97
- /// @debug convert-em2px(-0.5em); // -8px
98
- /// @debug convert-em2px(-1.5em); // -24px
99
- /// @debug convert-em2px(-2em, 8px); // -16px
100
- /// @example scss - Безразмерные числа как аргументы
101
- /// @debug convert-em2px(1, 16); // 16px (без единиц, но работает)
102
- /// @debug convert-em2px(0.5, 16); // 8px
103
- /// @debug convert-em2px(1.5, 16); // 24px
104
- /// @example scss - Контекст вложенности em
105
- /// // em зависят оass-lang.com/documentation/values/numbers#unitsт контекста родительского элемента
106
- /// .parent { font-size: 20px; }
107
- /// .child {
108
- /// // 1em внутри .parent равно 20px
109
- /// $px-value: convert-em2px(1em, 20px); // 20px
110
- /// // 0.5em внутри .parent равно 10px
111
- /// $px-value: convert-em2px(0.5em, 20px); // 10px
112
- /// }
113
- ///
114
- /// // Вложенные em множатся
115
- /// .grandparent { font-size: 16px; }
116
- /// .parent { font-size: 1.5em; } // 24px
117
- /// .child {
118
- /// // 1em внутри .parent равно 24px, а не 16px!
119
- /// $px-value: convert-em2px(1em, 24px); // 24px
120
- /// }
121
- /// @example css - Результат
122
- /// .parent {
123
- /// font-size: 20px;
124
- /// }
125
- ///
126
- /// .grandparent {
127
- /// font-size: 16px;
128
- /// }
129
- ///
130
- /// .parent {
131
- /// font-size: 1.5em;
132
- /// }
133
- /// @param {Number} $em - Значение в единицах `em` для
134
- /// конвертации. Может быть целым или дробным числом,
135
- /// положительным или отрицательным. Единицы измерения (`em`)
136
- /// удаляются для расчета, но ожидается, что значение
137
- /// изначально выражено в `em`.
138
- /// @param {Number} $base [16px] - Базовый размер в пикселях
139
- /// для расчета. По умолчанию используется `16px`, что
140
- /// соответствует стандартному размеру шрифта в большинстве
141
- /// браузеров. Может быть любым положительным числом (обычно
142
- /// в пикселях). Важно, что параметр представляет размер
143
- /// шрифта родительского элемента, относительно которого
144
- /// рассчитываются `em`.
145
- /// @return {Number} - Значение в единицах `px`, рассчитанное
146
- /// по формуле: `($em * $base) * 1px`. Возвращает дробное
147
- /// или целое число с единицами измерения `px`.
148
- /// @throws {Error} - Может выбросить ошибку при передаче
149
- /// нечисловых значений. Для корректной работы оба
150
- /// аргумента должны быть числами.
151
- @function convert-em2px($em, $base: 16px) {
152
- @return helpers.number-strip-unit($em) * helpers.number-strip-unit($base) * 1px;
153
- }
154
- ```
155
-
156
- но, учти несколько моментов:
157
-
158
- 1. Старайся описания укладывать такую же ширину строки
159
- 2. В строке `/// @since` нужно указать текущую дату в формате `YYYY.MM.DD`
160
- 3. Строку `/// @author Murad Rustamov (therteenten)` менять не нужно, как и строку `/// @group`
161
- 4. Первые две ссылки также необходимо не трогать:
162
- ```scss
163
- /// @link https://sourcecraft.dev/users/therteenten/overview SourceCraft - therteenten
164
- /// @link https://sourcecraft.dev/omnisass/library SourceCraft - OmniSass
165
- ```
166
- 5. Ссылки должны быть по теме, к которой относится смысл функции и ссылки должны быть в виде `/// @link https://some.com См. также: Название сайта - Название старницы` (данное правило не относится к первым двум ссылкам из пункта 4)
167
- 6. Количество ссылок не меньше 8
168
- 7. Примеры `/// @example` должны быть достоверны и без ошибок
package/test.scss DELETED
@@ -1,405 +0,0 @@
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
- // ============================================================================
11
- // 7. ФУНКЦИИ ЭКРАНИРОВАНИЯ И КОДИРОВАНИЯ
12
- // ============================================================================
13
-
14
- // Простое URL-кодирование
15
-
16
-
17
- // Экранирование кавычек
18
- @function escape-quotes($string) {
19
- $string: string-replace($string, '"', '\"');
20
- $string: string-replace($string, "'", "\'");
21
- @return $string;
22
- }
23
-
24
- // Экранирование для использования в CSS-контенте
25
- @function escape-css-content($string) {
26
- $string: string-replace($string, "\\", "\\\\");
27
- $string: string-replace($string, '"', '\"');
28
- $string: string-replace($string, "'", "\'");
29
- $string: string-replace($string, "\n", "\\A ");
30
- @return $string;
31
- }
32
-
33
- // ============================================================================
34
- // 8. ФУНКЦИИ ДЛЯ РАБОТЫ С ПУТЯМИ И ФАЙЛАМИ
35
- // ============================================================================
36
-
37
- // Получение имени файла из пути
38
- @function get-filename($path) {
39
- $last-slash: string-index($path, "/");
40
- @if $last-slash {
41
- @return string.slice($path, $last-slash + 1);
42
- }
43
-
44
- $last-backslash: string-index($path, "\\");
45
- @if $last-backslash {
46
- @return string.slice($path, $last-backslash + 1);
47
- }
48
-
49
- @return $path;
50
- }
51
-
52
- // Получение расширения файла
53
- @function get-extension($filename) {
54
- $last-dot: string-index($filename, ".");
55
- @if $last-dot {
56
- @return string.slice($filename, $last-dot + 1);
57
- }
58
- @return "";
59
- }
60
-
61
- // Получение имени файла без расширения
62
- @function get-filename-without-extension($filename) {
63
- $extension: get-extension($filename);
64
- @if string-length($extension) > 0 {
65
- $extension-length: string-length($extension) + 1; // +1 для точки
66
- @return string.slice($filename, 1, -$extension-length - 1);
67
- }
68
- @return $filename;
69
- }
70
-
71
- // Получение директории из пути
72
- @function get-directory($path) {
73
- $last-slash: string-index($path, "/");
74
- @if $last-slash {
75
- @return string.slice($path, 1, $last-slash);
76
- }
77
-
78
- $last-backslash: string-index($path, "\\");
79
- @if $last-backslash {
80
- @return string.slice($path, 1, $last-backslash);
81
- }
82
-
83
- @return "./";
84
- }
85
-
86
- // ============================================================================
87
- // 9. ФУНКЦИИ ГЕНЕРАЦИИ И УНИКАЛЬНЫХ ИДЕНТИФИКАТОРОВ
88
- // ============================================================================
89
-
90
- // Генерация уникального идентификатора с префиксом
91
- @function unique-string-id($prefix: "id-") {
92
- $random: random(1000000);
93
- $timestamp: unique-id(); // Встроенная функция Sass
94
- @return $prefix + $random + "-" + $timestamp;
95
- }
96
-
97
- // Генерация хеша из строки (упрощенный вариант)
98
- @function string-hash($string) {
99
- $hash: 0;
100
- $length: string-length($string);
101
-
102
- @for $i from 1 through $length {
103
- $char: string.slice($string, $i, $i);
104
- $hash: (($hash * 31) + string-index("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", $char)) % 1000000;
105
- }
106
-
107
- @return $hash;
108
- }
109
-
110
- // ============================================================================
111
- // 10. ФУНКЦИИ ДЛЯ РАБОТЫ С КЛАССАМИ И СЕЛЕКТОРАМИ
112
- // ============================================================================
113
-
114
- // Генерация модификаторов для БЭМ
115
- @function generate-bem-modifiers($block, $modifiers...) {
116
- $result: ();
117
- @each $modifier in $modifiers {
118
- $result: append($result, $block + "--" + $modifier, comma);
119
- }
120
- @return $result;
121
- }
122
-
123
- // Генерация элементов для БЭМ
124
- @function generate-bem-elements($block, $elements...) {
125
- $result: ();
126
- @each $element in $elements {
127
- $result: append($result, $block + "__" + $element, comma);
128
- }
129
- @return $result;
130
- }
131
-
132
- // Создание селектора с состоянием
133
- @function with-state($selector, $state) {
134
- @return $selector + ":" + $state;
135
- }
136
-
137
- // Создание селектора с псевдоэлементом
138
- @function with-pseudo($selector, $pseudo) {
139
- @return $selector + "::" + $pseudo;
140
- }
141
-
142
- // ============================================================================
143
- // 11. ФУНКЦИИ ПАДИНГА И ВЫРАВНИВАНИЯ
144
- // ============================================================================
145
-
146
- // Дополнение строки слева
147
- @function string-pad-left($string, $length, $pad-char: " ") {
148
- @while string-length($string) < $length {
149
- $string: $pad-char + $string;
150
- }
151
- @return $string;
152
- }
153
-
154
- // Дополнение строки справа
155
- @function string-pad-right($string, $length, $pad-char: " ") {
156
- @while string-length($string) < $length {
157
- $string: $string + $pad-char;
158
- }
159
- @return $string;
160
- }
161
-
162
- // Дополнение строки с обеих сторон
163
- @function string-pad-both($string, $length, $pad-char: " ") {
164
- @while string-length($string) < $length {
165
- $string: $pad-char + $string + $pad-char;
166
- }
167
-
168
- // Если длина нечетная, удалить один символ справа
169
- @if string-length($string) > $length {
170
- $string: string.slice($string, 1, -2);
171
- }
172
-
173
- @return $string;
174
- }
175
-
176
- // Центрирование текста в указанной ширине
177
- @function string-center($string, $width, $pad-char: " ") {
178
- $string-length: string-length($string);
179
- @if $string-length >= $width {
180
- @return $string;
181
- }
182
-
183
- $padding: $width - $string-length;
184
- $left-padding: floor($padding / 2);
185
- $right-padding: $padding - $left-padding;
186
-
187
- $result: $string;
188
- @for $i from 1 through $left-padding {
189
- $result: $pad-char + $result;
190
- }
191
- @for $i from 1 through $right-padding {
192
- $result: $result + $pad-char;
193
- }
194
-
195
- @return $result;
196
- }
197
-
198
- // ============================================================================
199
- // 12. ФУНКЦИИ ПОВТОРЕНИЯ И ГЕНЕРАЦИИ
200
- // ============================================================================
201
-
202
- // Повторение строки указанное количество раз
203
- @function string-repeat($string, $times) {
204
- $result: "";
205
- @for $i from 1 through $times {
206
- $result: $result + $string;
207
- }
208
- @return $result;
209
- }
210
-
211
- // Генерация последовательности символов
212
- @function generate-sequence($start, $end) {
213
- $result: "";
214
- @for $i from $start through $end {
215
- $result: $result + string.slice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", $i, $i);
216
- }
217
- @return $result;
218
- }
219
-
220
- // Генерация Lorem Ipsum текста
221
- @function lorem-ipsum($words: 10) {
222
- $lorem-words: "lorem" "ipsum" "dolor" "sit" "amet" "consectetur" "adipiscing" "elit" "sed" "do"
223
- "eiusmod" "tempor" "incididunt" "ut" "labore" "et" "dolore" "magna" "aliqua" "ut"
224
- "enim" "ad" "minim" "veniam" "quis" "nostrud" "exercitation" "ullamco" "laboris"
225
- "nisi" "ut" "aliquip" "ex" "ea" "commodo" "consequat";
226
-
227
- $result: "";
228
- @for $i from 1 through $words {
229
- $word-index: ($i - 1) % length($lorem-words) + 1;
230
- $word: nth($lorem-words, $word-index);
231
- $result: $result + $word;
232
- @if $i != $words {
233
- $result: $result + " ";
234
- }
235
- }
236
-
237
- @return capitalize($result) + ".";
238
- }
239
-
240
- // ============================================================================
241
- // 13. ВСПОМОГАТЕЛЬНЫЕ И КОМБИНИРОВАННЫЕ ФУНКЦИИ
242
- // ============================================================================
243
-
244
- // Обращение строки
245
- @function string-reverse($string) {
246
- $result: "";
247
- $length: string-length($string);
248
-
249
- @for $i from $length through 1 {
250
- $result: $result + string.slice($string, $i, $i);
251
- }
252
-
253
- @return $result;
254
- }
255
-
256
- // Подсчет вхождений подстроки
257
- @function string-count($string, $substring) {
258
- $count: 0;
259
- $index: string-index($string, $substring);
260
-
261
- @while $index != null {
262
- $count: $count + 1;
263
- $string: string.slice($string, $index + string-length($substring));
264
- $index: string-index($string, $substring);
265
- }
266
-
267
- @return $count;
268
- }
269
-
270
- // Удаление всех пробелов
271
- @function remove-spaces($string) {
272
- @return string-replace($string, " ", "");
273
- }
274
-
275
- // Удаление всех указанных символов
276
- @function remove-chars($string, $chars) {
277
- @each $char in $chars {
278
- $string: string-replace($string, $char, "");
279
- }
280
- @return $string;
281
- }
282
-
283
- // Получение уникальных символов из строки
284
- @function unique-chars($string) {
285
- $result: "";
286
- $length: string-length($string);
287
-
288
- @for $i from 1 through $length {
289
- $char: string.slice($string, $i, $i);
290
- @if not contains($result, $char) {
291
- $result: $result + $char;
292
- }
293
- }
294
-
295
- @return $result;
296
- }
297
-
298
- // ============================================================================
299
- // 14. ФУНКЦИИ ДЛЯ РАБОТЫ С ЦВЕТАМИ (Строковые представления)
300
- // ============================================================================
301
-
302
- // Извлечение hex значения из строки цвета
303
- @function extract-hex($color-string) {
304
- $color-string: to-lower-case($color-string);
305
- $hash-index: string-index($color-string, "#");
306
-
307
- @if $hash-index {
308
- $hex-start: $hash-index + 1;
309
- $hex: string.slice($color-string, $hex-start);
310
-
311
- // Убираем все не-hex символы
312
- $hex: remove-chars($hex, (" ", ";", ")", "(", ","));
313
-
314
- @return "#" + $hex;
315
- }
316
-
317
- @return null;
318
- }
319
-
320
- // Проверка, является ли строка hex-цветом
321
- @function is-hex-color($string) {
322
- $string: to-lower-case(string-trim($string));
323
- @if not string-starts-with($string, "#") {
324
- @return false;
325
- }
326
-
327
- $hex: string.slice($string, 2);
328
- $hex-length: string-length($hex);
329
-
330
- @if $hex-length != 3 and $hex-length != 6 and $hex-length != 8 {
331
- @return false;
332
- }
333
-
334
- $valid-chars: "0123456789abcdef";
335
-
336
- @for $i from 1 through $hex-length {
337
- $char: string.slice($hex, $i, $i);
338
- @if not contains($valid-chars, $char) {
339
- @return false;
340
- }
341
- }
342
-
343
- @return true;
344
- }
345
-
346
- // ============================================================================
347
- // 15. ФУНКЦИИ ДЛЯ РАБОТЫ С МЕДИА-ЗАПРОСАМИ
348
- // ============================================================================
349
-
350
- // Создание медиа-запроса с минимальной шириной
351
- @function min-width-query($width) {
352
- @return "(min-width: " + $width + ")";
353
- }
354
-
355
- // Создание медиа-запроса с максимальной шириной
356
- @function max-width-query($width) {
357
- @return "(max-width: " + $width + ")";
358
- }
359
-
360
- // Создание медиа-запроса для диапазона ширины
361
- @function width-range-query($min, $max) {
362
- @return "(min-width: " + $min + ") and (max-width: " + $max + ")";
363
- }
364
-
365
- // ============================================================================
366
- // ПРИМЕРЫ ИСПОЛЬЗОВАНИЯ
367
- // ============================================================================
368
-
369
- /*
370
- // Примеры использования функций:
371
-
372
- // 1. Базовые операции
373
- $test: "Hello World";
374
- $length: string-length($test); // 11
375
- $upper: to-upper-case($test); // "HELLO WORLD"
376
- $substr: string.slice($test, 7, 11); // "World"
377
-
378
- // 2. Проверки
379
- $has-world: contains($test, "World"); // true
380
- $starts-hello: string-starts-with($test, "Hello"); // true
381
- $ends-world: string-ends-with($test, "World"); // true
382
-
383
- // 3. Обрезка
384
- $trimmed: string-trim(" Hello "); // "Hello"
385
-
386
- // 4. Замена
387
- $replaced: string-replace($test, "World", "Sass"); // "Hello Sass"
388
-
389
- // 5. Преобразование регистра
390
- $kebab: camel-to-kebab("helloWorld"); // "hello-world"
391
- $camel: kebab-to-camel("hello-world"); // "helloWorld"
392
-
393
- // 6. Работа с CSS значениями
394
- $unit: get-unit("10px"); // "px"
395
- $number: get-number("10px"); // 10
396
- $no-unit: strip-unit("10px"); // 10
397
-
398
- // 7. Генерация классов
399
- $modifiers: generate-bem-modifiers("button", "primary", "large");
400
- // ".button--primary, .button--large"
401
- */
402
-
403
- // ============================================================================
404
- // КОНЕЦ БИБЛИОТЕКИ ФУНКЦИЙ ДЛЯ РАБОТЫ СО СТРОКАМИ
405
- // ============================================================================