acts_as_avatar 1.8.4

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f958dbdc84480a56642cf4ae701b0a4498e6f5cb4cda49da6b8fe90f70abcf38
4
+ data.tar.gz: ff15926c6a360283b3d33f3847f77c58460741fcde2c2cd92e0e6b8f4b769f5b
5
+ SHA512:
6
+ metadata.gz: 7f57cd7125ac0e2c71f7ed708335a7d5b2bd4a0f67db543f70e86306cca67213ae0e076d8ac416d4ad795b65497cca6635435f6fcc70a56ec918c3e117c8c6a0
7
+ data.tar.gz: a63742196b1ec51d321ae82a5082d37438391b8a06a0a6ff7e3559f551e090b2c5b278d3f73dbfb71e0c93938ceb4a0ac2855bed1462c48aa6a952b57e8f2fc1
data/LICENSE ADDED
@@ -0,0 +1,320 @@
1
+ Mozilla Public License, version 2.0
2
+
3
+ Copyright (c) 2022, qiuzhi99
4
+
5
+ 1. Definitions
6
+
7
+ 1.1. “Contributor” means each individual or legal entity that
8
+ creates, contributes to the creation of, or owns Covered Software.
9
+
10
+ 1.2. “Contributor Version” means the combination of the
11
+ Contributions of others (if any) used by a Contributor and that
12
+ particular Contributor’s Contribution.
13
+
14
+ 1.3. “Contribution” means Covered Software of a particular
15
+ Contributor.
16
+
17
+ 1.4. “Covered Software” means Source Code Form to which the initial
18
+ Contributor has attached the notice in Exhibit A, the Executable
19
+ Form of such Source Code Form, and Modifications of such Source Code
20
+ Form, in each case including portions thereof.
21
+
22
+ 1.5. “Incompatible With Secondary Licenses” means
23
+
24
+ that the initial Contributor has attached the notice described in
25
+ Exhibit B to the Covered Software; or
26
+
27
+ that the Covered Software was made available under the terms of
28
+ version 1.1 or earlier of the License, but not also under the terms
29
+ of a Secondary License.
30
+
31
+ 1.6. “Executable Form” means any form of the work other than Source
32
+ Code Form.
33
+
34
+ 1.7. “Larger Work” means a work that combines Covered Software with
35
+ other material, in a separate file or files, that is not Covered
36
+ Software.
37
+
38
+ 1.8. “License” means this document.
39
+
40
+ 1.9. “Licensable” means having the right to grant, to the maximum
41
+ extent possible, whether at the time of the initial grant or
42
+ subsequently, any and all of the rights conveyed by this License.
43
+
44
+ 1.10. “Modifications” means any of the following:
45
+
46
+ any file in Source Code Form that results from an addition to,
47
+ deletion from, or modification of the contents of Covered Software;
48
+ or
49
+
50
+ any new file in Source Code Form that contains any Covered Software.
51
+
52
+ 1.11. “Patent Claims” of a Contributor means any patent claim(s),
53
+ including without limitation, method, process, and apparatus claims,
54
+ in any patent Licensable by such Contributor that would be
55
+ infringed, but for the grant of the License, by the making, using,
56
+ selling, offering for sale, having made, import, or transfer of
57
+ either its Contributions or its Contributor Version.
58
+
59
+ 1.12. “Secondary License” means either the GNU General Public
60
+ License, Version 2.0, the GNU Lesser General Public License, Version
61
+ 2.1, the GNU Affero General Public License, Version 3.0, or any
62
+ later versions of those licenses.
63
+
64
+ 1.13. “Source Code Form” means the form of the work preferred for
65
+ making modifications.
66
+
67
+ 1.14. “You” (or “Your”) means an individual or a legal entity
68
+ exercising rights under this License. For legal entities, “You”
69
+ includes any entity that controls, is controlled by, or is under
70
+ common control with You. For purposes of this definition, “control”
71
+ means (a) the power, direct or indirect, to cause the direction or
72
+ management of such entity, whether by contract or otherwise, or (b)
73
+ ownership of more than fifty percent (50%) of the outstanding shares
74
+ or beneficial ownership of such entity.
75
+
76
+
77
+ 2. License Grants and Conditions
78
+
79
+ 2.1. Grants Each Contributor hereby grants You a world-wide,
80
+ royalty-free, non-exclusive license:
81
+
82
+ under intellectual property rights (other than patent or trademark)
83
+ Licensable by such Contributor to use, reproduce, make available,
84
+ modify, display, perform, distribute, and otherwise exploit its
85
+ Contributions, either on an unmodified basis, with Modifications, or
86
+ as part of a Larger Work; and
87
+
88
+ under Patent Claims of such Contributor to make, use, sell, offer
89
+ for sale, have made, import, and otherwise transfer either its
90
+ Contributions or its Contributor Version.
91
+
92
+ 2.2. Effective Date The licenses granted in Section 2.1 with respect
93
+ to any Contribution become effective for each Contribution on the
94
+ date the Contributor first distributes such Contribution.
95
+
96
+ 2.3. Limitations on Grant Scope The licenses granted in this Section
97
+ 2 are the only rights granted under this License. No additional
98
+ rights or licenses will be implied from the distribution or
99
+ licensing of Covered Software under this License. Notwithstanding
100
+ Section 2.1(b) above, no patent license is granted by a Contributor:
101
+
102
+ for any code that a Contributor has removed from Covered Software;
103
+ or
104
+
105
+ for infringements caused by: (i) Your and any other third party’s
106
+ modifications of Covered Software, or (ii) the combination of its
107
+ Contributions with other software (except as part of its Contributor
108
+ Version); or
109
+
110
+ under Patent Claims infringed by Covered Software in the absence of
111
+ its Contributions.
112
+
113
+ This License does not grant any rights in the trademarks, service
114
+ marks, or logos of any Contributor (except as may be necessary to
115
+ comply with the notice requirements in Section 3.4).
116
+
117
+ 2.4. Subsequent Licenses No Contributor makes additional grants as a
118
+ result of Your choice to distribute the Covered Software under a
119
+ subsequent version of this License (see Section 10.2) or under the
120
+ terms of a Secondary License (if permitted under the terms of
121
+ Section 3.3).
122
+
123
+ 2.5. Representation Each Contributor represents that the Contributor
124
+ believes its Contributions are its original creation(s) or it has
125
+ sufficient rights to grant the rights to its Contributions conveyed
126
+ by this License.
127
+
128
+ 2.6. Fair Use This License is not intended to limit any rights You
129
+ have under applicable copyright doctrines of fair use, fair dealing,
130
+ or other equivalents.
131
+
132
+ 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of
133
+ the licenses granted in Section 2.1.
134
+
135
+
136
+ 3. Responsibilities
137
+
138
+ 3.1. Distribution of Source Form All distribution of Covered
139
+ Software in Source Code Form, including any Modifications that You
140
+ create or to which You contribute, must be under the terms of this
141
+ License. You must inform recipients that the Source Code Form of the
142
+ Covered Software is governed by the terms of this License, and how
143
+ they can obtain a copy of this License. You may not attempt to alter
144
+ or restrict the recipients’ rights in the Source Code Form.
145
+
146
+ 3.2. Distribution of Executable Form If You distribute Covered
147
+ Software in Executable Form then:
148
+
149
+ such Covered Software must also be made available in Source Code
150
+ Form, as described in Section 3.1, and You must inform recipients of
151
+ the Executable Form how they can obtain a copy of such Source Code
152
+ Form by reasonable means in a timely manner, at a charge no more
153
+ than the cost of distribution to the recipient; and
154
+
155
+ You may distribute such Executable Form under the terms of this
156
+ License, or sublicense it under different terms, provided that the
157
+ license for the Executable Form does not attempt to limit or alter
158
+ the recipients’ rights in the Source Code Form under this License.
159
+
160
+ 3.3. Distribution of a Larger Work You may create and distribute a
161
+ Larger Work under terms of Your choice, provided that You also
162
+ comply with the requirements of this License for the Covered
163
+ Software. If the Larger Work is a combination of Covered Software
164
+ with a work governed by one or more Secondary Licenses, and the
165
+ Covered Software is not Incompatible With Secondary Licenses, this
166
+ License permits You to additionally distribute such Covered Software
167
+ under the terms of such Secondary License(s), so that the recipient
168
+ of the Larger Work may, at their option, further distribute the
169
+ Covered Software under the terms of either this License or such
170
+ Secondary License(s).
171
+
172
+ 3.4. Notices You may not remove or alter the substance of any
173
+ license notices (including copyright notices, patent notices,
174
+ disclaimers of warranty, or limitations of liability) contained
175
+ within the Source Code Form of the Covered Software, except that You
176
+ may alter any license notices to the extent required to remedy known
177
+ factual inaccuracies.
178
+
179
+ 3.5. Application of Additional Terms You may choose to offer, and to
180
+ charge a fee for, warranty, support, indemnity or liability
181
+ obligations to one or more recipients of Covered Software. However,
182
+ You may do so only on Your own behalf, and not on behalf of any
183
+ Contributor. You must make it absolutely clear that any such
184
+ warranty, support, indemnity, or liability obligation is offered by
185
+ You alone, and You hereby agree to indemnify every Contributor for
186
+ any liability incurred by such Contributor as a result of warranty,
187
+ support, indemnity or liability terms You offer. You may include
188
+ additional disclaimers of warranty and limitations of liability
189
+ specific to any jurisdiction.
190
+
191
+
192
+ 4. Inability to Comply Due to Statute or Regulation
193
+
194
+ If it is impossible for You to comply with any of the terms of this
195
+ License with respect to some or all of the Covered Software due to
196
+ statute, judicial order, or regulation then You must: (a) comply
197
+ with the terms of this License to the maximum extent possible; and
198
+ (b) describe the limitations and the code they affect. Such
199
+ description must be placed in a text file included with all
200
+ distributions of the Covered Software under this License. Except to
201
+ the extent prohibited by statute or regulation, such description
202
+ must be sufficiently detailed for a recipient of ordinary skill to
203
+ be able to understand it.
204
+
205
+
206
+ 5. Termination
207
+
208
+ 5.1. The rights granted under this License will terminate
209
+ automatically if You fail to comply with any of its terms. However,
210
+ if You become compliant, then the rights granted under this License
211
+ from a particular Contributor are reinstated (a) provisionally,
212
+ unless and until such Contributor explicitly and finally terminates
213
+ Your grants, and (b) on an ongoing basis, if such Contributor fails
214
+ to notify You of the non-compliance by some reasonable means prior
215
+ to 60 days after You have come back into compliance. Moreover, Your
216
+ grants from a particular Contributor are reinstated on an ongoing
217
+ basis if such Contributor notifies You of the non-compliance by some
218
+ reasonable means, this is the first time You have received notice of
219
+ non-compliance with this License from such Contributor, and You
220
+ become compliant prior to 30 days after Your receipt of the notice.
221
+
222
+ 5.2. If You initiate litigation against any entity by asserting a
223
+ patent infringement claim (excluding declaratory judgment actions,
224
+ counter-claims, and cross-claims) alleging that a Contributor
225
+ Version directly or indirectly infringes any patent, then the rights
226
+ granted to You by any and all Contributors for the Covered Software
227
+ under Section 2.1 of this License shall terminate.
228
+
229
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above,
230
+ all end user license agreements (excluding distributors and
231
+ resellers) which have been validly granted by You or Your
232
+ distributors under this License prior to termination shall survive
233
+ termination.
234
+
235
+ 6. Disclaimer of Warranty Covered Software is provided under this
236
+ License on an “as is” basis, without warranty of any kind, either
237
+ expressed, implied, or statutory, including, without limitation,
238
+ warranties that the Covered Software is free of defects, merchantable,
239
+ fit for a particular purpose or non-infringing. The entire risk as to
240
+ the quality and performance of the Covered Software is with You.
241
+ Should any Covered Software prove defective in any respect, You (not
242
+ any Contributor) assume the cost of any necessary servicing, repair,
243
+ or correction. This disclaimer of warranty constitutes an essential
244
+ part of this License. No use of any Covered Software is authorized
245
+ under this License except under this disclaimer.
246
+
247
+ 7. Limitation of Liability Under no circumstances and under no legal
248
+ theory, whether tort (including negligence), contract, or otherwise,
249
+ shall any Contributor, or anyone who distributes Covered Software as
250
+ permitted above, be liable to You for any direct, indirect, special,
251
+ incidental, or consequential damages of any character including,
252
+ without limitation, damages for lost profits, loss of goodwill, work
253
+ stoppage, computer failure or malfunction, or any and all other
254
+ commercial damages or losses, even if such party shall have been
255
+ informed of the possibility of such damages. This limitation of
256
+ liability shall not apply to liability for death or personal injury
257
+ resulting from such party’s negligence to the extent applicable law
258
+ prohibits such limitation. Some jurisdictions do not allow the
259
+ exclusion or limitation of incidental or consequential damages, so
260
+ this exclusion and limitation may not apply to You.
261
+
262
+ 8. Litigation Any litigation relating to this License may be brought
263
+ only in the courts of a jurisdiction where the defendant maintains its
264
+ principal place of business and such litigation shall be governed by
265
+ laws of that jurisdiction, without reference to its conflict-of-law
266
+ provisions. Nothing in this Section shall prevent a party’s ability to
267
+ bring cross-claims or counter-claims.
268
+
269
+ 9. Miscellaneous This License represents the complete agreement
270
+ concerning the subject matter hereof. If any provision of this License
271
+ is held to be unenforceable, such provision shall be reformed only to
272
+ the extent necessary to make it enforceable. Any law or regulation
273
+ which provides that the language of a contract shall be construed
274
+ against the drafter shall not be used to construe this License against
275
+ a Contributor.
276
+
277
+ 10. Versions of the License
278
+
279
+ 10.1. New Versions Mozilla Foundation is the license steward. Except
280
+ as provided in Section 10.3, no one other than the license steward
281
+ has the right to modify or publish new versions of this License.
282
+ Each version will be given a distinguishing version number.
283
+
284
+ 10.2. Effect of New Versions You may distribute the Covered Software
285
+ under the terms of the version of the License under which You
286
+ originally received the Covered Software, or under the terms of any
287
+ subsequent version published by the license steward.
288
+
289
+ 10.3. Modified Versions If you create software not governed by this
290
+ License, and you want to create a new license for such software, you
291
+ may create and use a modified version of this License if you rename
292
+ the license and remove any references to the name of the license
293
+ steward (except to note that such modified license differs from this
294
+ License).
295
+
296
+ 10.4. Distributing Source Code Form that is Incompatible With
297
+ Secondary Licenses If You choose to distribute Source Code Form that
298
+ is Incompatible With Secondary Licenses under the terms of this
299
+ version of the License, the notice described in Exhibit B of this
300
+ License must be attached.
301
+
302
+ Exhibit A - Source Code Form License Notice
303
+
304
+ This Source Code Form is subject to the terms of the Mozilla Public
305
+ License, v. 2.0. If a copy of the MPL was not distributed with this
306
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
307
+
308
+ If it is not possible or desirable to put the notice in a particular
309
+ file, then You may include the notice in a location (such as a
310
+ LICENSE file in a relevant directory) where a recipient would be
311
+ likely to look for such a notice.
312
+
313
+ You may add additional accurate notices of copyright ownership.
314
+
315
+ Exhibit B - “Incompatible With Secondary Licenses” Notice
316
+
317
+ This Source Code Form is “Incompatible With Secondary Licenses”, as
318
+ defined by the Mozilla Public License, v. 2.0.
319
+
320
+
data/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # acts_as_avatar
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/acts_as_avatar.svg)](https://rubygems.org/gems/acts_as_avatar)
4
+ [![Circle](https://circleci.com/gh/hfpp2012/acts_as_avatar/tree/main.svg?style=shield)](https://app.circleci.com/pipelines/github/hfpp2012/acts_as_avatar?branch=main)
5
+ [![Code Climate](https://codeclimate.com/github/hfpp2012/acts_as_avatar/badges/gpa.svg)](https://codeclimate.com/github/hfpp2012/acts_as_avatar)
6
+
7
+ TODO: Description of this gem goes here.
8
+
9
+ ---
10
+
11
+ - [Quick start](#quick-start)
12
+ - [Support](#support)
13
+ - [License](#license)
14
+ - [Code of conduct](#code-of-conduct)
15
+ - [Contribution guide](#contribution-guide)
16
+
17
+ ## Quick start
18
+
19
+ ```
20
+ $ gem install acts_as_avatar
21
+ ```
22
+
23
+ ```ruby
24
+ require "acts_as_avatar"
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ```
30
+ # view
31
+ <%= acts_as_avatar_tag(admin_user, class: "rounded-circle") %>
32
+
33
+ <%= acts_as_avatar_tag(current_admin_user, size: 36, class: "rounded-circle") %>
34
+
35
+ <%= acts_as_avatar_tag(current_admin_user, name: :avatar_name, class: "rounded-circle") %>
36
+
37
+ <%= github_avatar_tag complexity: 5, size: 60 %>
38
+
39
+ <%= github_avatar_tag size: 60, rounded_circle: true %>
40
+
41
+ # model
42
+ acts_as_avatar inline_svg_engine: :initial_avatar
43
+ ```
44
+
45
+ ## Support
46
+
47
+ If you want to report a bug, or have ideas, feedback or questions about the gem, [let me know via GitHub issues](https://github.com/hfpp2012/acts_as_avatar/issues/new) and I will do my best to provide a helpful answer. Happy hacking!
48
+
49
+ ## License
50
+
51
+ The gem is available as open source under the terms of the [MIT License](LICENSE.txt).
52
+
53
+ ## Code of conduct
54
+
55
+ Everyone interacting in this project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](CODE_OF_CONDUCT.md).
56
+
57
+ ## Contribution guide
58
+
59
+ Pull requests are welcome!
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tempfile"
4
+
5
+ class ActsAsAvatar::SanitizeSvgJob < ActiveJob::Base
6
+ include ActsAsAvatar::Scrubber
7
+ queue_as :default
8
+
9
+ def perform(blob)
10
+ return unless blob.svg?
11
+ return if blob.metadata[:sanitized]
12
+
13
+ sanitized = sanitize(blob.download)
14
+ Tempfile.open([blob.filename.base, blob.filename.extension]) do |file|
15
+ file.print sanitized
16
+ file.rewind
17
+ blob.upload file
18
+ end
19
+
20
+ blob.metadata[:sanitized] = true
21
+ blob.save
22
+ end
23
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ class ActsAsAvatar::UiFacesAvatarJob < ActiveJob::Base
4
+ queue_as :default
5
+
6
+ def perform(global_id)
7
+ object = GlobalID::Locator.locate global_id
8
+
9
+ object.avatar.send(:add_uifaces_avatar)
10
+ end
11
+ end
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ # == Schema Information
4
+ #
5
+ # Table name: act_as_avatars
6
+ #
7
+ # id :bigint not null, primary key
8
+ # avatarable_type :string not null
9
+ # created_at :datetime not null
10
+ # updated_at :datetime not null
11
+ # avatarable_id :bigint not null
12
+ #
13
+ # Indexes
14
+ #
15
+ # index_avatars_on_avatarable (avatarable_type,avatarable_id)
16
+ #
17
+ require "marcel"
18
+ require "ruby_identicon"
19
+ require "letter_avatar"
20
+ require "active_storage_validations"
21
+
22
+ module ActsAsAvatar
23
+ class Avatar < ActiveRecord::Base
24
+ # Table name
25
+ self.table_name = "acts_as_avatars"
26
+
27
+ # belongs_to :avatarable, polymorphic: true
28
+ delegated_type :avatarable, types: ActsAsAvatar.configuration.class_type
29
+ validates :avatarable_type, presence: true
30
+ # delegate :email, to: :avatarable
31
+ # accepts_nested_attributes_for :avatarable
32
+ has_one_attached :upload_avatar
33
+ has_one_attached :default_avatar
34
+ after_create_commit :add_default_avatar, if: -> { random_image_engine.present? }
35
+ validates :upload_avatar, size: { less_than: ActsAsAvatar.configuration.upload_max_size },
36
+ content_type: %r{\Aimage/.*\z}
37
+ after_create_commit :sanitize_svg, if: :svg?
38
+
39
+ def current_avatar
40
+ upload_avatar.attached? ? upload_avatar : default_avatar
41
+ end
42
+
43
+ def add_default_avatar
44
+ # return if default_avatar.attached?
45
+
46
+ case random_image_engine.to_sym
47
+ when :uifaces_avatar
48
+ ActsAsAvatar::UiFacesAvatarJob.perform_later(avatarable.to_global_id.to_s)
49
+ when :letter_avatar
50
+ add_letter_avatar
51
+ when :identicon_avatar
52
+ add_identicon_avatar
53
+ when :github_avatar
54
+ add_github_avatar
55
+ end
56
+ end
57
+
58
+ private
59
+
60
+ def svg?
61
+ return if current_avatar.blob.nil?
62
+
63
+ current_avatar.blob.filename.extension == "svg"
64
+ end
65
+
66
+ def sanitize_svg
67
+ ActsAsAvatar::SanitizeSvgJob.set(wait: 10.seconds).perform_later current_avatar.blob
68
+ end
69
+
70
+ def random_image_engine
71
+ avatarable.class.random_image_engine
72
+ end
73
+
74
+ def add_identicon_avatar
75
+ io = RubyIdenticon.create(text)
76
+
77
+ default_avatar.attach(
78
+ io: StringIO.new(io),
79
+ filename: default_file_name,
80
+ content_type: content_type(io)
81
+ )
82
+ end
83
+
84
+ def add_uifaces_avatar
85
+ io = ActsAsAvatar::Request.read_image
86
+
87
+ return unless io
88
+
89
+ default_avatar.attach(
90
+ io: io,
91
+ filename: default_file_name,
92
+ content_type: content_type(io)
93
+ )
94
+ end
95
+
96
+ def add_letter_avatar
97
+ io = File.open(LetterAvatar.generate(text, 200))
98
+
99
+ default_avatar.attach(
100
+ io: io,
101
+ filename: default_file_name,
102
+ content_type: content_type(io)
103
+ )
104
+ end
105
+
106
+ def add_github_avatar
107
+ size = ActsAsAvatar.configuration.avatar_size
108
+
109
+ complexity = ActsAsAvatar.configuration.github_complexity
110
+ render_method = ActsAsAvatar.configuration.github_render_method
111
+ rounded_circle = ActsAsAvatar.configuration.github_rounded_circle
112
+
113
+ io = ActsAsAvatar::GithubAvatar.instance.random_svg_avatar(
114
+ size: size,
115
+ github_complexity: complexity,
116
+ github_render_method: render_method,
117
+ github_rounded_circle: rounded_circle
118
+ )
119
+
120
+ filename = "#{default_file_name}.svg"
121
+
122
+ default_avatar.attach(
123
+ io: StringIO.new(io),
124
+ filename: filename,
125
+ content_type: "image/svg+xml"
126
+ )
127
+ end
128
+
129
+ def default_file_name
130
+ ActsAsAvatar.configuration.default_file_name
131
+ end
132
+
133
+ def text
134
+ name = ActsAsAvatar.configuration.avatar_name.to_sym
135
+ avatarable.send(name.to_sym)
136
+ end
137
+
138
+ def content_type(io)
139
+ Marcel::MimeType.for(io)
140
+ end
141
+ end
142
+ end
data/github_avatar.js ADDED
@@ -0,0 +1,121 @@
1
+ function decToHexColor(colorNumber) {
2
+ return `${colorNumber.toString(16).padStart(6, "0")}`;
3
+ }
4
+
5
+ function getBinaryList(number, size) {
6
+ return number.toString(2).padStart(size, "0").split("");
7
+ }
8
+
9
+ function parseAvatarData(data, separator) {
10
+ const ret = {
11
+ xAxis: 0,
12
+ yAxis: 0,
13
+ colorMap: [],
14
+ };
15
+
16
+ if (!data) {
17
+ return ret;
18
+ }
19
+
20
+ data.split(separator).forEach((element, index) => {
21
+ let intVal = parseInt(element, 36);
22
+
23
+ switch (index) {
24
+ case 0:
25
+ ret.xAxis = intVal;
26
+ break;
27
+ case 1:
28
+ ret.yAxis = intVal;
29
+ break;
30
+
31
+ default:
32
+ ret.colorMap.push(decToHexColor(intVal));
33
+ break;
34
+ }
35
+ });
36
+
37
+ return ret;
38
+ }
39
+
40
+ function generateRandomAvatarData(complexity = 16, avatarDataSeparator = "-") {
41
+ const xAxis = Math.floor(Math.random() * Math.pow(2, complexity - 1));
42
+ const yAxis = Math.floor(Math.random() * (Math.pow(2, complexity) - 1)) + 1;
43
+
44
+ const rows = getBinaryList(yAxis, complexity);
45
+ let ret = `${xAxis.toString(36)}${avatarDataSeparator}${yAxis.toString(36)}`;
46
+ let color;
47
+
48
+ rows.forEach(() => {
49
+ color = Math.floor(Math.random() * 16777215);
50
+ ret += `${avatarDataSeparator}${color.toString(36)}`;
51
+ });
52
+
53
+ return ret;
54
+ }
55
+
56
+ function getAvatarFromData(
57
+ avatarData,
58
+ renderMethod = "square",
59
+ size = 256,
60
+ roundedCircle = false,
61
+ avatarDataSeparator = "-"
62
+ ) {
63
+ const { xAxis, yAxis, colorMap } = parseAvatarData(
64
+ avatarData,
65
+ avatarDataSeparator
66
+ );
67
+ const complexity = colorMap.length;
68
+ const resolution = Math.floor(size / complexity);
69
+
70
+ if (complexity < 1 || xAxis >= Math.pow(2, complexity)) {
71
+ throw Error("Incorrect avatar data");
72
+ }
73
+
74
+ let renderProcess = (resolution, indexX, indexY) =>
75
+ `M${indexX * resolution},${
76
+ indexY * resolution
77
+ } h${resolution} v${resolution} h${0 - resolution}Z`;
78
+
79
+ if (renderMethod === "circle") {
80
+ renderProcess = (resolution, indexX, indexY) => {
81
+ const radius = resolution / 2;
82
+ return `M${indexX * resolution},${
83
+ indexY * resolution + radius
84
+ } a${radius} ${radius} 0 1,1 ${resolution},0 a${radius} ${radius} 0 1,1 -${resolution},0`;
85
+ };
86
+ } else if (typeof renderMethod === "function") {
87
+ renderProcess = renderMethod;
88
+ }
89
+
90
+ if (roundedCircle) {
91
+ inlineStyle = "style='border-radius: 50%'";
92
+ } else {
93
+ inlineStyle = "";
94
+ }
95
+
96
+ const rows = getBinaryList(yAxis, complexity);
97
+ const cols = getBinaryList(xAxis, complexity);
98
+ let ret = `<svg xmlns="http://www.w3.org/2000/svg" ${inlineStyle} width="${size}" height="${size}">`;
99
+
100
+ rows.forEach((rowItem, indexY) => {
101
+ let draw = [];
102
+ cols.forEach((colItem, indexX) => {
103
+ if (parseInt(rowItem, 10) ^ parseInt(colItem, 10)) {
104
+ draw.push(renderProcess(resolution, indexX, indexY));
105
+ }
106
+ });
107
+ ret += `<path fill="#${colorMap[indexY]}" d="${draw.join(" ")}"/>`;
108
+ });
109
+
110
+ return `${ret}</svg>`;
111
+ }
112
+
113
+ function getRandomAvatar(
114
+ complexity = 16,
115
+ renderMethod = "square",
116
+ size = 256,
117
+ roundedCircle = false
118
+ ) {
119
+ let avatarData = generateRandomAvatarData(complexity);
120
+ return getAvatarFromData(avatarData, renderMethod, size, roundedCircle);
121
+ }