From 73e265d8fd050ae3daa67472b4465a5c49d68910 Mon Sep 17 00:00:00 2001 From: Lauri Ojansivu Date: Sat, 20 Apr 2019 15:18:33 +0300 Subject: Include to Wekan packages directory contents, so that meteor command would build all directly. This also simplifies build scripts. Thanks to xet7 ! --- packages/kadira-flow-router/.gitignore | 3 + packages/kadira-flow-router/.travis.yml | 8 + packages/kadira-flow-router/CHANGELOG.md | 155 + packages/kadira-flow-router/CONTRIBUTING.md | 16 + packages/kadira-flow-router/LICENSE | 21 + packages/kadira-flow-router/README.md | 777 +++ packages/kadira-flow-router/client/_init.js | 11 + packages/kadira-flow-router/client/group.js | 57 + packages/kadira-flow-router/client/modules.js | 2 + packages/kadira-flow-router/client/route.js | 125 + packages/kadira-flow-router/client/router.js | 587 +++ packages/kadira-flow-router/client/triggers.js | 112 + packages/kadira-flow-router/lib/router.js | 9 + packages/kadira-flow-router/package.js | 81 + packages/kadira-flow-router/server/_init.js | 4 + packages/kadira-flow-router/server/group.js | 18 + .../server/plugins/fast_render.js | 40 + packages/kadira-flow-router/server/route.js | 28 + packages/kadira-flow-router/server/router.js | 146 + .../kadira-flow-router/test/client/_helpers.js | 10 + .../kadira-flow-router/test/client/group.spec.js | 113 + .../kadira-flow-router/test/client/loader.spec.js | 17 + .../test/client/route.reactivity.spec.js | 158 + .../test/client/router.core.spec.js | 632 +++ .../test/client/router.reactivity.spec.js | 208 + .../test/client/router.subs_ready.spec.js | 225 + .../kadira-flow-router/test/client/trigger.spec.js | 570 +++ .../kadira-flow-router/test/client/triggers.js | 297 ++ .../test/common/fast_render_route.js | 48 + .../kadira-flow-router/test/common/group.spec.js | 16 + .../kadira-flow-router/test/common/route.spec.js | 15 + .../test/common/router.addons.spec.js | 30 + .../test/common/router.path.spec.js | 135 + .../test/common/router.url.spec.js | 11 + .../kadira-flow-router/test/server/_helpers.js | 38 + .../test/server/plugins/fast_render.js | 35 + packages/markdown/.gitignore | 1 + packages/markdown/README.md | 40 + packages/markdown/markdown.js | 9 + packages/markdown/marked/.editorconfig | 16 + packages/markdown/marked/.eslintignore | 1 + packages/markdown/marked/.eslintrc.json | 29 + packages/markdown/marked/.gitattributes | 2 + packages/markdown/marked/.github/ISSUE_TEMPLATE.md | 42 + .../marked/.github/ISSUE_TEMPLATE/Bug_report.md | 27 + .../.github/ISSUE_TEMPLATE/Feature_request.md | 14 + .../marked/.github/ISSUE_TEMPLATE/Proposal.md | 11 + .../marked/.github/PULL_REQUEST_TEMPLATE.md | 53 + .../marked/.github/PULL_REQUEST_TEMPLATE/badges.md | 50 + .../.github/PULL_REQUEST_TEMPLATE/release.md | 25 + packages/markdown/marked/.gitignore | 3 + packages/markdown/marked/.travis.yml | 46 + packages/markdown/marked/LICENSE.md | 43 + packages/markdown/marked/Makefile | 15 + packages/markdown/marked/README.md | 76 + packages/markdown/marked/bin/marked | 215 + packages/markdown/marked/bower.json | 23 + packages/markdown/marked/component.json | 10 + packages/markdown/marked/docs/AUTHORS.md | 269 + packages/markdown/marked/docs/CNAME | 1 + packages/markdown/marked/docs/CODE_OF_CONDUCT.md | 74 + packages/markdown/marked/docs/CONTRIBUTING.md | 92 + packages/markdown/marked/docs/PUBLISHING.md | 24 + packages/markdown/marked/docs/README.md | 85 + packages/markdown/marked/docs/USING_ADVANCED.md | 78 + packages/markdown/marked/docs/USING_PRO.md | 163 + packages/markdown/marked/docs/broken.md | 426 ++ packages/markdown/marked/docs/demo/demo.css | 72 + packages/markdown/marked/docs/demo/demo.js | 534 ++ packages/markdown/marked/docs/demo/index.html | 78 + packages/markdown/marked/docs/demo/initial.md | 36 + packages/markdown/marked/docs/demo/preview.html | 12 + packages/markdown/marked/docs/demo/quickref.md | 167 + packages/markdown/marked/docs/demo/worker.js | 105 + .../marked/docs/img/logo-black-and-white.svg | 133 + packages/markdown/marked/docs/img/logo-black.svg | 32 + packages/markdown/marked/docs/index.html | 269 + packages/markdown/marked/index.js | 1 + packages/markdown/marked/jasmine.json | 11 + packages/markdown/marked/lib/marked.js | 1689 +++++++ packages/markdown/marked/man/marked.1 | 114 + packages/markdown/marked/man/marked.1.txt | 99 + packages/markdown/marked/marked.min.js | 6 + packages/markdown/marked/package.json | 69 + packages/markdown/marked/test/README | 10 + packages/markdown/marked/test/browser/index.html | 5 + packages/markdown/marked/test/browser/index.js | 39 + packages/markdown/marked/test/browser/test.js | 66 + packages/markdown/marked/test/helpers/helpers.js | 26 + .../markdown/marked/test/helpers/html-differ.js | 38 + packages/markdown/marked/test/index.js | 551 ++ packages/markdown/marked/test/json-to-files.js | 62 + .../markdown/marked/test/new/adjacent_lists.html | 9 + .../markdown/marked/test/new/adjacent_lists.md | 5 + .../markdown/marked/test/new/autolink_lines.html | 3 + .../markdown/marked/test/new/autolink_lines.md | 2 + packages/markdown/marked/test/new/autolinks.html | 15 + packages/markdown/marked/test/new/autolinks.md | 15 + .../marked/test/new/blockquote_list_item.html | 3 + .../marked/test/new/blockquote_list_item.md | 4 + .../marked/test/new/case_insensitive_refs.html | 1 + .../marked/test/new/case_insensitive_refs.md | 3 + .../markdown/marked/test/new/cm_autolinks.html | 91 + packages/markdown/marked/test/new/cm_autolinks.md | 96 + .../markdown/marked/test/new/cm_blockquotes.html | 233 + .../markdown/marked/test/new/cm_blockquotes.md | 189 + .../markdown/marked/test/new/cm_html_blocks.html | 300 ++ .../markdown/marked/test/new/cm_html_blocks.md | 312 ++ .../markdown/marked/test/new/cm_link_defs.html | 115 + packages/markdown/marked/test/new/cm_link_defs.md | 157 + packages/markdown/marked/test/new/cm_links.html | 397 ++ packages/markdown/marked/test/new/cm_links.md | 515 ++ packages/markdown/marked/test/new/cm_raw_html.html | 77 + packages/markdown/marked/test/new/cm_raw_html.md | 78 + .../markdown/marked/test/new/cm_strong_and_em.html | 7 + .../markdown/marked/test/new/cm_strong_and_em.md | 7 + .../marked/test/new/cm_thematic_breaks.html | 106 + .../markdown/marked/test/new/cm_thematic_breaks.md | 98 + packages/markdown/marked/test/new/code_spans.html | 3 + packages/markdown/marked/test/new/code_spans.md | 3 + packages/markdown/marked/test/new/def_blocks.html | 30 + packages/markdown/marked/test/new/def_blocks.md | 21 + packages/markdown/marked/test/new/double_link.html | 5 + packages/markdown/marked/test/new/double_link.md | 5 + packages/markdown/marked/test/new/em_2char.html | 25 + packages/markdown/marked/test/new/em_2char.md | 25 + .../marked/test/new/emphasis_extra tests.html | 1 + .../marked/test/new/emphasis_extra tests.md | 1 + .../markdown/marked/test/new/escaped_angles.html | 1 + .../markdown/marked/test/new/escaped_angles.md | 1 + .../markdown/marked/test/new/gfm_autolinks.html | 83 + packages/markdown/marked/test/new/gfm_autolinks.md | 83 + packages/markdown/marked/test/new/gfm_break.html | 1 + packages/markdown/marked/test/new/gfm_break.md | 6 + packages/markdown/marked/test/new/gfm_code.html | 21 + packages/markdown/marked/test/new/gfm_code.md | 43 + .../markdown/marked/test/new/gfm_code_hr_list.html | 52 + .../markdown/marked/test/new/gfm_code_hr_list.md | 53 + packages/markdown/marked/test/new/gfm_em.html | 1 + packages/markdown/marked/test/new/gfm_em.md | 1 + packages/markdown/marked/test/new/gfm_hashtag.html | 5 + packages/markdown/marked/test/new/gfm_hashtag.md | 8 + .../marked/test/new/gfm_links_invalid.html | 1 + .../markdown/marked/test/new/gfm_links_invalid.md | 4 + packages/markdown/marked/test/new/gfm_tables.html | 37 + packages/markdown/marked/test/new/gfm_tables.md | 21 + packages/markdown/marked/test/new/headings_id.html | 13 + packages/markdown/marked/test/new/headings_id.md | 14 + .../markdown/marked/test/new/hr_list_break.html | 10 + packages/markdown/marked/test/new/hr_list_break.md | 6 + .../markdown/marked/test/new/html_comments.html | 57 + packages/markdown/marked/test/new/html_comments.md | 56 + .../markdown/marked/test/new/html_no_new_line.html | 1 + .../markdown/marked/test/new/html_no_new_line.md | 1 + packages/markdown/marked/test/new/images.html | 5 + packages/markdown/marked/test/new/images.md | 12 + .../markdown/marked/test/new/lazy_blockquotes.html | 4 + .../markdown/marked/test/new/lazy_blockquotes.md | 2 + packages/markdown/marked/test/new/link_lt.html | 1 + packages/markdown/marked/test/new/link_lt.md | 1 + .../markdown/marked/test/new/link_tick_redos.html | 31 + .../markdown/marked/test/new/link_tick_redos.md | 31 + packages/markdown/marked/test/new/links.html | 3 + packages/markdown/marked/test/new/links.md | 5 + .../markdown/marked/test/new/list_item_text.html | 1 + .../markdown/marked/test/new/list_item_text.md | 5 + packages/markdown/marked/test/new/list_table.html | 44 + packages/markdown/marked/test/new/list_table.md | 13 + packages/markdown/marked/test/new/main.html | 4 + packages/markdown/marked/test/new/main.md | 55 + packages/markdown/marked/test/new/mangle_xss.html | 3 + packages/markdown/marked/test/new/mangle_xss.md | 7 + packages/markdown/marked/test/new/nested_code.html | 9 + packages/markdown/marked/test/new/nested_code.md | 9 + packages/markdown/marked/test/new/nested_em.html | 3 + packages/markdown/marked/test/new/nested_em.md | 3 + .../marked/test/new/nested_square_link.html | 3 + .../markdown/marked/test/new/nested_square_link.md | 3 + .../markdown/marked/test/new/nogfm_hashtag.html | 5 + packages/markdown/marked/test/new/nogfm_hashtag.md | 8 + packages/markdown/marked/test/new/not_a_link.html | 1 + packages/markdown/marked/test/new/not_a_link.md | 1 + packages/markdown/marked/test/new/ref_paren.html | 1 + packages/markdown/marked/test/new/ref_paren.md | 3 + .../markdown/marked/test/new/relative_urls.html | 35 + packages/markdown/marked/test/new/relative_urls.md | 30 + packages/markdown/marked/test/new/same_bullet.html | 5 + packages/markdown/marked/test/new/same_bullet.md | 3 + .../markdown/marked/test/new/sanitize_links.html | 5 + .../markdown/marked/test/new/sanitize_links.md | 12 + packages/markdown/marked/test/new/smartypants.html | 6 + packages/markdown/marked/test/new/smartypants.md | 9 + .../markdown/marked/test/new/smartypants_code.html | 11 + .../markdown/marked/test/new/smartypants_code.md | 15 + packages/markdown/marked/test/new/table_cells.html | 27 + packages/markdown/marked/test/new/table_cells.md | 55 + .../marked/test/new/toplevel_paragraphs.html | 34 + .../marked/test/new/toplevel_paragraphs.md | 41 + packages/markdown/marked/test/new/tricky_list.html | 23 + packages/markdown/marked/test/new/tricky_list.md | 15 + .../markdown/marked/test/new/uppercase_hex.html | 2 + packages/markdown/marked/test/new/uppercase_hex.md | 5 + .../test/original/amps_and_angles_encoding.html | 17 + .../test/original/amps_and_angles_encoding.md | 25 + .../markdown/marked/test/original/auto_links.html | 18 + .../markdown/marked/test/original/auto_links.md | 13 + .../marked/test/original/backslash_escapes.html | 118 + .../marked/test/original/backslash_escapes.md | 120 + .../original/blockquotes_with_code_blocks.html | 15 + .../test/original/blockquotes_with_code_blocks.md | 11 + .../markdown/marked/test/original/code_blocks.html | 18 + .../markdown/marked/test/original/code_blocks.md | 14 + .../markdown/marked/test/original/code_spans.html | 6 + .../markdown/marked/test/original/code_spans.md | 6 + ...rd_wrapped_paragraphs_with_list_like_lines.html | 8 + ...hard_wrapped_paragraphs_with_list_like_lines.md | 8 + .../marked/test/original/horizontal_rules.html | 85 + .../marked/test/original/horizontal_rules.md | 94 + .../marked/test/original/inline_html_advanced.html | 15 + .../marked/test/original/inline_html_advanced.md | 15 + .../marked/test/original/inline_html_comments.html | 13 + .../marked/test/original/inline_html_comments.md | 13 + .../marked/test/original/inline_html_simple.html | 72 + .../marked/test/original/inline_html_simple.md | 69 + .../marked/test/original/links_inline_style.html | 15 + .../marked/test/original/links_inline_style.md | 19 + .../test/original/links_reference_style.html | 52 + .../marked/test/original/links_reference_style.md | 75 + .../test/original/links_shortcut_references.html | 9 + .../test/original/links_shortcut_references.md | 24 + .../test/original/literal_quotes_in_titles.html | 3 + .../test/original/literal_quotes_in_titles.md | 11 + .../original/markdown_documentation_basics.html | 314 ++ .../test/original/markdown_documentation_basics.md | 310 ++ .../original/markdown_documentation_syntax.html | 942 ++++ .../test/original/markdown_documentation_syntax.md | 892 ++++ .../marked/test/original/nested_blockquotes.html | 9 + .../marked/test/original/nested_blockquotes.md | 5 + .../test/original/ordered_and_unordered_lists.html | 164 + .../test/original/ordered_and_unordered_lists.md | 144 + .../test/original/strong_and_em_together.html | 7 + .../marked/test/original/strong_and_em_together.md | 7 + packages/markdown/marked/test/original/tabs.html | 25 + packages/markdown/marked/test/original/tabs.md | 21 + .../markdown/marked/test/original/tidyness.html | 8 + packages/markdown/marked/test/original/tidyness.md | 5 + .../markdown/marked/test/redos/link_redos.html | 5 + packages/markdown/marked/test/redos/link_redos.md | 2 + .../markdown/marked/test/redos/quadratic_br.js | 4 + .../markdown/marked/test/redos/quadratic_email.js | 4 + .../marked/test/redos/redos_html_closing.html | 1 + .../marked/test/redos/redos_html_closing.md | 1 + .../markdown/marked/test/redos/redos_nolink.html | 1 + .../markdown/marked/test/redos/redos_nolink.md | 1 + .../test/specs/commonmark/commonmark.0.29.json | 5327 ++++++++++++++++++++ .../marked/test/specs/commonmark/getSpecs.js | 24 + .../markdown/marked/test/specs/gfm/getSpecs.js | 44 + .../markdown/marked/test/specs/gfm/gfm.0.29.json | 147 + .../marked/test/specs/original/specs-spec.js | 12 + packages/markdown/marked/test/specs/redos-spec.js | 24 + packages/markdown/marked/test/specs/run-spec.js | 52 + packages/markdown/marked/test/unit/marked-spec.js | 73 + packages/markdown/package.js | 24 + packages/markdown/smart.json | 9 + packages/markdown/template-integration.js | 16 + packages/meteor-accounts-cas/.gitignore | 2 + packages/meteor-accounts-cas/LICENSE | 21 + packages/meteor-accounts-cas/README.md | 88 + packages/meteor-accounts-cas/cas_client.js | 112 + packages/meteor-accounts-cas/cas_client_cordova.js | 71 + packages/meteor-accounts-cas/cas_server.js | 281 ++ packages/meteor-accounts-cas/package.js | 29 + packages/meteor-useraccounts-core/.editorconfig | 18 + packages/meteor-useraccounts-core/.gitignore | 2 + packages/meteor-useraccounts-core/.jshintignore | 2 + packages/meteor-useraccounts-core/.jshintrc | 132 + packages/meteor-useraccounts-core/.travis.yml | 8 + packages/meteor-useraccounts-core/Guide.md | 1433 ++++++ packages/meteor-useraccounts-core/History.md | 353 ++ packages/meteor-useraccounts-core/LICENSE.md | 20 + packages/meteor-useraccounts-core/README.md | 104 + packages/meteor-useraccounts-core/lib/client.js | 464 ++ packages/meteor-useraccounts-core/lib/core.js | 593 +++ packages/meteor-useraccounts-core/lib/field.js | 292 ++ packages/meteor-useraccounts-core/lib/methods.js | 25 + packages/meteor-useraccounts-core/lib/server.js | 184 + .../meteor-useraccounts-core/lib/server_methods.js | 142 + .../lib/templates_helpers/at_error.js | 26 + .../lib/templates_helpers/at_form.js | 83 + .../lib/templates_helpers/at_input.js | 124 + .../lib/templates_helpers/at_message.js | 7 + .../lib/templates_helpers/at_nav_button.js | 16 + .../lib/templates_helpers/at_oauth.js | 5 + .../lib/templates_helpers/at_pwd_form.js | 331 ++ .../lib/templates_helpers/at_pwd_form_btn.js | 18 + .../lib/templates_helpers/at_pwd_link.js | 24 + .../lib/templates_helpers/at_reCaptcha.js | 19 + .../at_resend_verification_email_link.js | 24 + .../lib/templates_helpers/at_result.js | 7 + .../lib/templates_helpers/at_sep.js | 5 + .../lib/templates_helpers/at_signin_link.js | 24 + .../lib/templates_helpers/at_signup_link.js | 24 + .../lib/templates_helpers/at_social.js | 105 + .../lib/templates_helpers/at_terms_link.js | 33 + .../lib/templates_helpers/at_title.js | 7 + .../lib/templates_helpers/ensure_signed_in.html | 12 + .../lib/templates_helpers/ensure_signed_in.js | 15 + packages/meteor-useraccounts-core/lib/utils.js | 19 + packages/meteor-useraccounts-core/package.js | 94 + packages/meteor-useraccounts-core/tests/tests.js | 215 + packages/wekan-accounts-cas/LICENSE | 21 + packages/wekan-accounts-cas/README.md | 88 + packages/wekan-accounts-cas/cas_client.js | 112 + packages/wekan-accounts-cas/cas_client_cordova.js | 71 + packages/wekan-accounts-cas/cas_server.js | 281 ++ packages/wekan-accounts-cas/package.js | 29 + packages/wekan-accounts-oidc/.gitignore | 1 + packages/wekan-accounts-oidc/LICENSE.txt | 14 + packages/wekan-accounts-oidc/README.md | 75 + packages/wekan-accounts-oidc/oidc.js | 22 + packages/wekan-accounts-oidc/oidc_login_button.css | 3 + packages/wekan-accounts-oidc/package.js | 19 + packages/wekan-ldap/LICENSE | 21 + packages/wekan-ldap/README.md | 130 + packages/wekan-ldap/client/loginHelper.js | 52 + packages/wekan-ldap/package.js | 32 + packages/wekan-ldap/server/index.js | 1 + packages/wekan-ldap/server/ldap.js | 555 ++ packages/wekan-ldap/server/logger.js | 15 + packages/wekan-ldap/server/loginHandler.js | 224 + packages/wekan-ldap/server/sync.js | 447 ++ packages/wekan-ldap/server/syncUser.js | 29 + packages/wekan-ldap/server/testConnection.js | 39 + packages/wekan-oidc/.gitignore | 1 + packages/wekan-oidc/LICENSE.txt | 14 + packages/wekan-oidc/README.md | 7 + packages/wekan-oidc/oidc_client.js | 68 + packages/wekan-oidc/oidc_configure.html | 6 + packages/wekan-oidc/oidc_configure.js | 17 + packages/wekan-oidc/oidc_server.js | 143 + packages/wekan-oidc/package.js | 23 + packages/wekan-scrollbar/.gitignore | 14 + packages/wekan-scrollbar/LICENSE | 21 + .../wekan-scrollbar/jquery.mCustomScrollbar.css | 1267 +++++ .../wekan-scrollbar/jquery.mCustomScrollbar.js | 2423 +++++++++ packages/wekan-scrollbar/jquery.mousewheel.js | 221 + packages/wekan-scrollbar/package.js | 21 + packages/wekan-scrollbar/readme.md | 17 + 348 files changed, 36853 insertions(+) create mode 100644 packages/kadira-flow-router/.gitignore create mode 100644 packages/kadira-flow-router/.travis.yml create mode 100644 packages/kadira-flow-router/CHANGELOG.md create mode 100644 packages/kadira-flow-router/CONTRIBUTING.md create mode 100644 packages/kadira-flow-router/LICENSE create mode 100644 packages/kadira-flow-router/README.md create mode 100644 packages/kadira-flow-router/client/_init.js create mode 100644 packages/kadira-flow-router/client/group.js create mode 100644 packages/kadira-flow-router/client/modules.js create mode 100644 packages/kadira-flow-router/client/route.js create mode 100644 packages/kadira-flow-router/client/router.js create mode 100644 packages/kadira-flow-router/client/triggers.js create mode 100644 packages/kadira-flow-router/lib/router.js create mode 100644 packages/kadira-flow-router/package.js create mode 100644 packages/kadira-flow-router/server/_init.js create mode 100644 packages/kadira-flow-router/server/group.js create mode 100644 packages/kadira-flow-router/server/plugins/fast_render.js create mode 100644 packages/kadira-flow-router/server/route.js create mode 100644 packages/kadira-flow-router/server/router.js create mode 100644 packages/kadira-flow-router/test/client/_helpers.js create mode 100644 packages/kadira-flow-router/test/client/group.spec.js create mode 100644 packages/kadira-flow-router/test/client/loader.spec.js create mode 100644 packages/kadira-flow-router/test/client/route.reactivity.spec.js create mode 100644 packages/kadira-flow-router/test/client/router.core.spec.js create mode 100644 packages/kadira-flow-router/test/client/router.reactivity.spec.js create mode 100644 packages/kadira-flow-router/test/client/router.subs_ready.spec.js create mode 100644 packages/kadira-flow-router/test/client/trigger.spec.js create mode 100644 packages/kadira-flow-router/test/client/triggers.js create mode 100644 packages/kadira-flow-router/test/common/fast_render_route.js create mode 100644 packages/kadira-flow-router/test/common/group.spec.js create mode 100644 packages/kadira-flow-router/test/common/route.spec.js create mode 100644 packages/kadira-flow-router/test/common/router.addons.spec.js create mode 100644 packages/kadira-flow-router/test/common/router.path.spec.js create mode 100644 packages/kadira-flow-router/test/common/router.url.spec.js create mode 100644 packages/kadira-flow-router/test/server/_helpers.js create mode 100644 packages/kadira-flow-router/test/server/plugins/fast_render.js create mode 100755 packages/markdown/.gitignore create mode 100755 packages/markdown/README.md create mode 100755 packages/markdown/markdown.js create mode 100644 packages/markdown/marked/.editorconfig create mode 100644 packages/markdown/marked/.eslintignore create mode 100644 packages/markdown/marked/.eslintrc.json create mode 100644 packages/markdown/marked/.gitattributes create mode 100644 packages/markdown/marked/.github/ISSUE_TEMPLATE.md create mode 100644 packages/markdown/marked/.github/ISSUE_TEMPLATE/Bug_report.md create mode 100644 packages/markdown/marked/.github/ISSUE_TEMPLATE/Feature_request.md create mode 100644 packages/markdown/marked/.github/ISSUE_TEMPLATE/Proposal.md create mode 100644 packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/badges.md create mode 100644 packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/release.md create mode 100644 packages/markdown/marked/.gitignore create mode 100644 packages/markdown/marked/.travis.yml create mode 100644 packages/markdown/marked/LICENSE.md create mode 100644 packages/markdown/marked/Makefile create mode 100644 packages/markdown/marked/README.md create mode 100755 packages/markdown/marked/bin/marked create mode 100644 packages/markdown/marked/bower.json create mode 100644 packages/markdown/marked/component.json create mode 100644 packages/markdown/marked/docs/AUTHORS.md create mode 100644 packages/markdown/marked/docs/CNAME create mode 100644 packages/markdown/marked/docs/CODE_OF_CONDUCT.md create mode 100644 packages/markdown/marked/docs/CONTRIBUTING.md create mode 100644 packages/markdown/marked/docs/PUBLISHING.md create mode 100644 packages/markdown/marked/docs/README.md create mode 100644 packages/markdown/marked/docs/USING_ADVANCED.md create mode 100644 packages/markdown/marked/docs/USING_PRO.md create mode 100644 packages/markdown/marked/docs/broken.md create mode 100644 packages/markdown/marked/docs/demo/demo.css create mode 100644 packages/markdown/marked/docs/demo/demo.js create mode 100644 packages/markdown/marked/docs/demo/index.html create mode 100644 packages/markdown/marked/docs/demo/initial.md create mode 100644 packages/markdown/marked/docs/demo/preview.html create mode 100644 packages/markdown/marked/docs/demo/quickref.md create mode 100644 packages/markdown/marked/docs/demo/worker.js create mode 100644 packages/markdown/marked/docs/img/logo-black-and-white.svg create mode 100644 packages/markdown/marked/docs/img/logo-black.svg create mode 100644 packages/markdown/marked/docs/index.html create mode 100644 packages/markdown/marked/index.js create mode 100644 packages/markdown/marked/jasmine.json create mode 100644 packages/markdown/marked/lib/marked.js create mode 100644 packages/markdown/marked/man/marked.1 create mode 100644 packages/markdown/marked/man/marked.1.txt create mode 100644 packages/markdown/marked/marked.min.js create mode 100644 packages/markdown/marked/package.json create mode 100644 packages/markdown/marked/test/README create mode 100644 packages/markdown/marked/test/browser/index.html create mode 100644 packages/markdown/marked/test/browser/index.js create mode 100644 packages/markdown/marked/test/browser/test.js create mode 100644 packages/markdown/marked/test/helpers/helpers.js create mode 100644 packages/markdown/marked/test/helpers/html-differ.js create mode 100644 packages/markdown/marked/test/index.js create mode 100644 packages/markdown/marked/test/json-to-files.js create mode 100644 packages/markdown/marked/test/new/adjacent_lists.html create mode 100644 packages/markdown/marked/test/new/adjacent_lists.md create mode 100644 packages/markdown/marked/test/new/autolink_lines.html create mode 100644 packages/markdown/marked/test/new/autolink_lines.md create mode 100644 packages/markdown/marked/test/new/autolinks.html create mode 100644 packages/markdown/marked/test/new/autolinks.md create mode 100644 packages/markdown/marked/test/new/blockquote_list_item.html create mode 100644 packages/markdown/marked/test/new/blockquote_list_item.md create mode 100644 packages/markdown/marked/test/new/case_insensitive_refs.html create mode 100644 packages/markdown/marked/test/new/case_insensitive_refs.md create mode 100644 packages/markdown/marked/test/new/cm_autolinks.html create mode 100644 packages/markdown/marked/test/new/cm_autolinks.md create mode 100644 packages/markdown/marked/test/new/cm_blockquotes.html create mode 100644 packages/markdown/marked/test/new/cm_blockquotes.md create mode 100644 packages/markdown/marked/test/new/cm_html_blocks.html create mode 100644 packages/markdown/marked/test/new/cm_html_blocks.md create mode 100644 packages/markdown/marked/test/new/cm_link_defs.html create mode 100644 packages/markdown/marked/test/new/cm_link_defs.md create mode 100644 packages/markdown/marked/test/new/cm_links.html create mode 100644 packages/markdown/marked/test/new/cm_links.md create mode 100644 packages/markdown/marked/test/new/cm_raw_html.html create mode 100644 packages/markdown/marked/test/new/cm_raw_html.md create mode 100644 packages/markdown/marked/test/new/cm_strong_and_em.html create mode 100644 packages/markdown/marked/test/new/cm_strong_and_em.md create mode 100644 packages/markdown/marked/test/new/cm_thematic_breaks.html create mode 100644 packages/markdown/marked/test/new/cm_thematic_breaks.md create mode 100644 packages/markdown/marked/test/new/code_spans.html create mode 100644 packages/markdown/marked/test/new/code_spans.md create mode 100644 packages/markdown/marked/test/new/def_blocks.html create mode 100644 packages/markdown/marked/test/new/def_blocks.md create mode 100644 packages/markdown/marked/test/new/double_link.html create mode 100644 packages/markdown/marked/test/new/double_link.md create mode 100644 packages/markdown/marked/test/new/em_2char.html create mode 100644 packages/markdown/marked/test/new/em_2char.md create mode 100644 packages/markdown/marked/test/new/emphasis_extra tests.html create mode 100644 packages/markdown/marked/test/new/emphasis_extra tests.md create mode 100644 packages/markdown/marked/test/new/escaped_angles.html create mode 100644 packages/markdown/marked/test/new/escaped_angles.md create mode 100644 packages/markdown/marked/test/new/gfm_autolinks.html create mode 100644 packages/markdown/marked/test/new/gfm_autolinks.md create mode 100644 packages/markdown/marked/test/new/gfm_break.html create mode 100644 packages/markdown/marked/test/new/gfm_break.md create mode 100644 packages/markdown/marked/test/new/gfm_code.html create mode 100644 packages/markdown/marked/test/new/gfm_code.md create mode 100644 packages/markdown/marked/test/new/gfm_code_hr_list.html create mode 100644 packages/markdown/marked/test/new/gfm_code_hr_list.md create mode 100644 packages/markdown/marked/test/new/gfm_em.html create mode 100644 packages/markdown/marked/test/new/gfm_em.md create mode 100644 packages/markdown/marked/test/new/gfm_hashtag.html create mode 100644 packages/markdown/marked/test/new/gfm_hashtag.md create mode 100644 packages/markdown/marked/test/new/gfm_links_invalid.html create mode 100644 packages/markdown/marked/test/new/gfm_links_invalid.md create mode 100644 packages/markdown/marked/test/new/gfm_tables.html create mode 100644 packages/markdown/marked/test/new/gfm_tables.md create mode 100644 packages/markdown/marked/test/new/headings_id.html create mode 100644 packages/markdown/marked/test/new/headings_id.md create mode 100644 packages/markdown/marked/test/new/hr_list_break.html create mode 100644 packages/markdown/marked/test/new/hr_list_break.md create mode 100644 packages/markdown/marked/test/new/html_comments.html create mode 100644 packages/markdown/marked/test/new/html_comments.md create mode 100644 packages/markdown/marked/test/new/html_no_new_line.html create mode 100644 packages/markdown/marked/test/new/html_no_new_line.md create mode 100644 packages/markdown/marked/test/new/images.html create mode 100644 packages/markdown/marked/test/new/images.md create mode 100644 packages/markdown/marked/test/new/lazy_blockquotes.html create mode 100644 packages/markdown/marked/test/new/lazy_blockquotes.md create mode 100644 packages/markdown/marked/test/new/link_lt.html create mode 100644 packages/markdown/marked/test/new/link_lt.md create mode 100644 packages/markdown/marked/test/new/link_tick_redos.html create mode 100644 packages/markdown/marked/test/new/link_tick_redos.md create mode 100644 packages/markdown/marked/test/new/links.html create mode 100644 packages/markdown/marked/test/new/links.md create mode 100644 packages/markdown/marked/test/new/list_item_text.html create mode 100644 packages/markdown/marked/test/new/list_item_text.md create mode 100644 packages/markdown/marked/test/new/list_table.html create mode 100644 packages/markdown/marked/test/new/list_table.md create mode 100644 packages/markdown/marked/test/new/main.html create mode 100644 packages/markdown/marked/test/new/main.md create mode 100644 packages/markdown/marked/test/new/mangle_xss.html create mode 100644 packages/markdown/marked/test/new/mangle_xss.md create mode 100644 packages/markdown/marked/test/new/nested_code.html create mode 100644 packages/markdown/marked/test/new/nested_code.md create mode 100644 packages/markdown/marked/test/new/nested_em.html create mode 100644 packages/markdown/marked/test/new/nested_em.md create mode 100644 packages/markdown/marked/test/new/nested_square_link.html create mode 100644 packages/markdown/marked/test/new/nested_square_link.md create mode 100644 packages/markdown/marked/test/new/nogfm_hashtag.html create mode 100644 packages/markdown/marked/test/new/nogfm_hashtag.md create mode 100644 packages/markdown/marked/test/new/not_a_link.html create mode 100644 packages/markdown/marked/test/new/not_a_link.md create mode 100644 packages/markdown/marked/test/new/ref_paren.html create mode 100644 packages/markdown/marked/test/new/ref_paren.md create mode 100644 packages/markdown/marked/test/new/relative_urls.html create mode 100644 packages/markdown/marked/test/new/relative_urls.md create mode 100644 packages/markdown/marked/test/new/same_bullet.html create mode 100644 packages/markdown/marked/test/new/same_bullet.md create mode 100644 packages/markdown/marked/test/new/sanitize_links.html create mode 100644 packages/markdown/marked/test/new/sanitize_links.md create mode 100644 packages/markdown/marked/test/new/smartypants.html create mode 100644 packages/markdown/marked/test/new/smartypants.md create mode 100644 packages/markdown/marked/test/new/smartypants_code.html create mode 100644 packages/markdown/marked/test/new/smartypants_code.md create mode 100644 packages/markdown/marked/test/new/table_cells.html create mode 100644 packages/markdown/marked/test/new/table_cells.md create mode 100644 packages/markdown/marked/test/new/toplevel_paragraphs.html create mode 100644 packages/markdown/marked/test/new/toplevel_paragraphs.md create mode 100644 packages/markdown/marked/test/new/tricky_list.html create mode 100644 packages/markdown/marked/test/new/tricky_list.md create mode 100644 packages/markdown/marked/test/new/uppercase_hex.html create mode 100644 packages/markdown/marked/test/new/uppercase_hex.md create mode 100644 packages/markdown/marked/test/original/amps_and_angles_encoding.html create mode 100644 packages/markdown/marked/test/original/amps_and_angles_encoding.md create mode 100644 packages/markdown/marked/test/original/auto_links.html create mode 100644 packages/markdown/marked/test/original/auto_links.md create mode 100644 packages/markdown/marked/test/original/backslash_escapes.html create mode 100644 packages/markdown/marked/test/original/backslash_escapes.md create mode 100644 packages/markdown/marked/test/original/blockquotes_with_code_blocks.html create mode 100644 packages/markdown/marked/test/original/blockquotes_with_code_blocks.md create mode 100644 packages/markdown/marked/test/original/code_blocks.html create mode 100644 packages/markdown/marked/test/original/code_blocks.md create mode 100644 packages/markdown/marked/test/original/code_spans.html create mode 100644 packages/markdown/marked/test/original/code_spans.md create mode 100644 packages/markdown/marked/test/original/hard_wrapped_paragraphs_with_list_like_lines.html create mode 100644 packages/markdown/marked/test/original/hard_wrapped_paragraphs_with_list_like_lines.md create mode 100644 packages/markdown/marked/test/original/horizontal_rules.html create mode 100644 packages/markdown/marked/test/original/horizontal_rules.md create mode 100644 packages/markdown/marked/test/original/inline_html_advanced.html create mode 100644 packages/markdown/marked/test/original/inline_html_advanced.md create mode 100644 packages/markdown/marked/test/original/inline_html_comments.html create mode 100644 packages/markdown/marked/test/original/inline_html_comments.md create mode 100644 packages/markdown/marked/test/original/inline_html_simple.html create mode 100644 packages/markdown/marked/test/original/inline_html_simple.md create mode 100644 packages/markdown/marked/test/original/links_inline_style.html create mode 100644 packages/markdown/marked/test/original/links_inline_style.md create mode 100644 packages/markdown/marked/test/original/links_reference_style.html create mode 100644 packages/markdown/marked/test/original/links_reference_style.md create mode 100644 packages/markdown/marked/test/original/links_shortcut_references.html create mode 100644 packages/markdown/marked/test/original/links_shortcut_references.md create mode 100644 packages/markdown/marked/test/original/literal_quotes_in_titles.html create mode 100644 packages/markdown/marked/test/original/literal_quotes_in_titles.md create mode 100644 packages/markdown/marked/test/original/markdown_documentation_basics.html create mode 100644 packages/markdown/marked/test/original/markdown_documentation_basics.md create mode 100644 packages/markdown/marked/test/original/markdown_documentation_syntax.html create mode 100644 packages/markdown/marked/test/original/markdown_documentation_syntax.md create mode 100644 packages/markdown/marked/test/original/nested_blockquotes.html create mode 100644 packages/markdown/marked/test/original/nested_blockquotes.md create mode 100644 packages/markdown/marked/test/original/ordered_and_unordered_lists.html create mode 100644 packages/markdown/marked/test/original/ordered_and_unordered_lists.md create mode 100644 packages/markdown/marked/test/original/strong_and_em_together.html create mode 100644 packages/markdown/marked/test/original/strong_and_em_together.md create mode 100644 packages/markdown/marked/test/original/tabs.html create mode 100644 packages/markdown/marked/test/original/tabs.md create mode 100644 packages/markdown/marked/test/original/tidyness.html create mode 100644 packages/markdown/marked/test/original/tidyness.md create mode 100644 packages/markdown/marked/test/redos/link_redos.html create mode 100644 packages/markdown/marked/test/redos/link_redos.md create mode 100644 packages/markdown/marked/test/redos/quadratic_br.js create mode 100644 packages/markdown/marked/test/redos/quadratic_email.js create mode 100644 packages/markdown/marked/test/redos/redos_html_closing.html create mode 100644 packages/markdown/marked/test/redos/redos_html_closing.md create mode 100644 packages/markdown/marked/test/redos/redos_nolink.html create mode 100644 packages/markdown/marked/test/redos/redos_nolink.md create mode 100644 packages/markdown/marked/test/specs/commonmark/commonmark.0.29.json create mode 100644 packages/markdown/marked/test/specs/commonmark/getSpecs.js create mode 100644 packages/markdown/marked/test/specs/gfm/getSpecs.js create mode 100644 packages/markdown/marked/test/specs/gfm/gfm.0.29.json create mode 100644 packages/markdown/marked/test/specs/original/specs-spec.js create mode 100644 packages/markdown/marked/test/specs/redos-spec.js create mode 100644 packages/markdown/marked/test/specs/run-spec.js create mode 100644 packages/markdown/marked/test/unit/marked-spec.js create mode 100755 packages/markdown/package.js create mode 100755 packages/markdown/smart.json create mode 100755 packages/markdown/template-integration.js create mode 100644 packages/meteor-accounts-cas/.gitignore create mode 100644 packages/meteor-accounts-cas/LICENSE create mode 100644 packages/meteor-accounts-cas/README.md create mode 100644 packages/meteor-accounts-cas/cas_client.js create mode 100644 packages/meteor-accounts-cas/cas_client_cordova.js create mode 100644 packages/meteor-accounts-cas/cas_server.js create mode 100644 packages/meteor-accounts-cas/package.js create mode 100644 packages/meteor-useraccounts-core/.editorconfig create mode 100644 packages/meteor-useraccounts-core/.gitignore create mode 100644 packages/meteor-useraccounts-core/.jshintignore create mode 100644 packages/meteor-useraccounts-core/.jshintrc create mode 100644 packages/meteor-useraccounts-core/.travis.yml create mode 100644 packages/meteor-useraccounts-core/Guide.md create mode 100644 packages/meteor-useraccounts-core/History.md create mode 100644 packages/meteor-useraccounts-core/LICENSE.md create mode 100644 packages/meteor-useraccounts-core/README.md create mode 100644 packages/meteor-useraccounts-core/lib/client.js create mode 100644 packages/meteor-useraccounts-core/lib/core.js create mode 100644 packages/meteor-useraccounts-core/lib/field.js create mode 100644 packages/meteor-useraccounts-core/lib/methods.js create mode 100644 packages/meteor-useraccounts-core/lib/server.js create mode 100644 packages/meteor-useraccounts-core/lib/server_methods.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_error.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_form.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_input.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_message.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_nav_button.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_oauth.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form_btn.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_link.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_reCaptcha.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_resend_verification_email_link.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_result.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_sep.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_signin_link.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_signup_link.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_social.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_terms_link.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/at_title.js create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.html create mode 100644 packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.js create mode 100644 packages/meteor-useraccounts-core/lib/utils.js create mode 100644 packages/meteor-useraccounts-core/package.js create mode 100644 packages/meteor-useraccounts-core/tests/tests.js create mode 100644 packages/wekan-accounts-cas/LICENSE create mode 100644 packages/wekan-accounts-cas/README.md create mode 100644 packages/wekan-accounts-cas/cas_client.js create mode 100644 packages/wekan-accounts-cas/cas_client_cordova.js create mode 100644 packages/wekan-accounts-cas/cas_server.js create mode 100644 packages/wekan-accounts-cas/package.js create mode 100644 packages/wekan-accounts-oidc/.gitignore create mode 100644 packages/wekan-accounts-oidc/LICENSE.txt create mode 100644 packages/wekan-accounts-oidc/README.md create mode 100644 packages/wekan-accounts-oidc/oidc.js create mode 100644 packages/wekan-accounts-oidc/oidc_login_button.css create mode 100644 packages/wekan-accounts-oidc/package.js create mode 100644 packages/wekan-ldap/LICENSE create mode 100644 packages/wekan-ldap/README.md create mode 100644 packages/wekan-ldap/client/loginHelper.js create mode 100644 packages/wekan-ldap/package.js create mode 100644 packages/wekan-ldap/server/index.js create mode 100644 packages/wekan-ldap/server/ldap.js create mode 100644 packages/wekan-ldap/server/logger.js create mode 100644 packages/wekan-ldap/server/loginHandler.js create mode 100644 packages/wekan-ldap/server/sync.js create mode 100644 packages/wekan-ldap/server/syncUser.js create mode 100644 packages/wekan-ldap/server/testConnection.js create mode 100644 packages/wekan-oidc/.gitignore create mode 100644 packages/wekan-oidc/LICENSE.txt create mode 100644 packages/wekan-oidc/README.md create mode 100644 packages/wekan-oidc/oidc_client.js create mode 100644 packages/wekan-oidc/oidc_configure.html create mode 100644 packages/wekan-oidc/oidc_configure.js create mode 100644 packages/wekan-oidc/oidc_server.js create mode 100644 packages/wekan-oidc/package.js create mode 100644 packages/wekan-scrollbar/.gitignore create mode 100644 packages/wekan-scrollbar/LICENSE create mode 100644 packages/wekan-scrollbar/jquery.mCustomScrollbar.css create mode 100644 packages/wekan-scrollbar/jquery.mCustomScrollbar.js create mode 100644 packages/wekan-scrollbar/jquery.mousewheel.js create mode 100644 packages/wekan-scrollbar/package.js create mode 100644 packages/wekan-scrollbar/readme.md (limited to 'packages') diff --git a/packages/kadira-flow-router/.gitignore b/packages/kadira-flow-router/.gitignore new file mode 100644 index 00000000..22ee0cce --- /dev/null +++ b/packages/kadira-flow-router/.gitignore @@ -0,0 +1,3 @@ +.build* +*.browserify.js.cached +*.browserify.js.map diff --git a/packages/kadira-flow-router/.travis.yml b/packages/kadira-flow-router/.travis.yml new file mode 100644 index 00000000..5125066a --- /dev/null +++ b/packages/kadira-flow-router/.travis.yml @@ -0,0 +1,8 @@ +sudo: required +language: node_js +node_js: + - "0.10" +before_install: + - "curl -L http://git.io/ejPSng | /bin/sh" +env: + - TEST_COMMAND=meteor \ No newline at end of file diff --git a/packages/kadira-flow-router/CHANGELOG.md b/packages/kadira-flow-router/CHANGELOG.md new file mode 100644 index 00000000..80fd6708 --- /dev/null +++ b/packages/kadira-flow-router/CHANGELOG.md @@ -0,0 +1,155 @@ +# Changelog + +### v2.12.1 + +* Add NPM modules back. Fixes: [#602](https://github.com/kadirahq/flow-router/issues/602) + +### v2.12.0 + +* Update Fast Render to v2.14.0 + +### v2.11.0 + +* Add support for Meteor 1.3 RC-1. +* Removes browserify and get modules from Meteor 1.3. + +### v2.10.1 +* Fix the url generation for prefixed paths. See: [#508](https://github.com/kadirahq/flow-router/issues/508) + +### v2.10.0 +* Update few dependencies to the latest versions: pagejs, qs, cosmos:browserify + +### v2.9.0 +* Add FlowRouter.url() See: [#374](https://github.com/kadirahq/flow-router/pull/374) + +### v2.8.0 +* Allow to access options in groups as well. See: [#378](https://github.com/kadirahq/flow-router/pull/378) + +### v2.7.0 +* Add Path Prefix support. See: [#329](https://github.com/kadirahq/flow-router/pull/329) + +### v2.6.2 +* Now .current() sends a cloned version of the internal current object. Which prevent outside mutations to params and queryParams + +### v2.6.1 + +* Fix [#143](https://github.com/kadirahq/flow-router/issues/314). + This says that when we are doing a trigger redirect, + We won't get reactive changes like: `getRouteName()` + +### v2.6.0 +* Add hashbang support. See [#311](https://github.com/kadirahq/flow-router/pull/311) + +### v2.5.0 +* Add a stop callback on the triggers. See: [#306](https://github.com/kadirahq/flow-router/pull/306). + +### v2.4.0 + +* Add a name to the route groups. See: [#290](https://github.com/kadirahq/flow-router/pull/290) + +### v2.3.0 +* We've used `path` for both the current path and for the pathDef earlier. Now we differentiate it. See: [#272](https://github.com/kadirahq/flow-router/issues/272) and [#273](https://github.com/kadirahq/flow-router/pull/273) for more information. + +### v2.2.0 +* Add the first addOn api: FlowRouter.onRouteRegister(cb) + +### v2.1.1 +* There was an issue in IE9 support. We fix it with this version. + +### v2.1.0 +* Add IE9 Support. See this issue [#111](https://github.com/kadirahq/flow-router/issues/111) for more info. + +### v2.0.2 + +* Add missing queryParams object in the subscriptions method (with FR on the server) +* With that, [#237](https://github.com/kadirahq/flow-router/issues/237) is partially fixed. + +### v2.0.1 + +* Use pagejs.redirect() for our redirection process. +* Above fixes [#239](https://github.com/kadirahq/flow-router/issues/239) + +### v2.0.0 + +* Released 2.0 :) +* Now flow-router comes as `kadira:flow-router` +* Remove deprecated APIs + - `FlowRouter.reactiveCurrent()` + - Middlewares + - `FlowRouter.current().params.query` +* Follow the [migration guide](https://github.com/kadirahq/flow-router#migrating-into-20) for more information. + +### v1.18.0 + +* Implement idempotent routing on withReplaceState. See: [#197](https://github.com/meteorhacks/flow-router/issues/197) +* Add an [API](https://github.com/meteorhacks/flow-router#flowrouterwithtrailingslashfn) to set trailing slashes. + +### v1.17.2 +* Fix [#182](https://github.com/meteorhacks/flow-router/issues/182) - Now trigger's redirect function support `FlowRouter.go()` syntax. + +### v1.17.1 + +* Fix [#164](https://github.com/meteorhacks/flow-router/issues/164) - It's an issue when using `check` with flow router query params. +* Fix [#168](https://github.com/meteorhacks/flow-router/pull/168) - It's URL encoding issue. + +### v1.17.0 + +* Add an API called `FlowRouter.wait()` to wait the initialization and pass it back to the app. Fixes issue [180](https://github.com/meteorhacks/flow-router/issues/180). + +### v1.16.3 + +* Fix a crazy context switching issue. For more information see commit [6ca54cc](https://github.com/meteorhacks/flow-router/commit/6ca54cc7969b3a8aa71d63c98c99a20b175125a2) + +### v1.16.2 +* Fix issue [#167](https://github.com/meteorhacks/flow-router/issues/167) via [#175](https://github.com/meteorhacks/flow-router/pull/175) +* Fix [#176](https://github.com/meteorhacks/flow-router/issues/176) by the removal of `Tracker.flush` usage. + +### v1.16.1 +* Fix [issue](https://github.com/meteorhacks/flow-router/pull/173) of overwriting global triggers when written multiple times. + +### v1.16.0 + +* [Refactor](https://github.com/meteorhacks/flow-router/pull/172) triggers API for clean code +* Added [redirect](https://github.com/meteorhacks/flow-router#redirecting-with-triggers) functionality for triggers +* Now we are API complete for the 2.x release + +### v1.15.0 + +* Now all our routes are idempotent. +* If some one needs to re-run the route, he needs to use our `FlowRouter.reload()` API. + +### v1.14.1 + +* Fix regression came from v1.11.0. With that, `FlowRouter.go("/")` does not work. More information on [#147](https://github.com/meteorhacks/flow-router/issues/147). + +### v1.14.0 +* Bring browserify back with the updated version of `cosmos:browserify` which fixes some size issues. See [more info](https://github.com/meteorhacks/flow-router/issues/128#issuecomment-109799953). + +### v1.13.0 +* Remove browserified pagejs and qs dependency loading. With that we could reduce ~10kb of data size (without compression). We can look for a bower integration in the future. For now, here are the dependencies we have. + - page@1.6.3: https://github.com/visionmedia/page.js + - qs@3.1.0: https://github.com/hapijs/qs + +### v1.12.0 +* Add [`FlowRouter.withReplaceState`](https://github.com/meteorhacks/flow-router#flowrouterwithreplcaestatefn) api to use replaceState when changing routes via FlowRouter apis. + +### v1.11.0 +* Fix [#145](https://github.com/meteorhacks/flow-router/issues/145) by changing how safeToRun works. +* Add `FlowRouter.path()` to the server side +* Fix [#130](https://github.com/meteorhacks/flow-router/issues/130) + +### v1.10.0 +Add support for [triggers](https://github.com/meteorhacks/flow-router#triggers). This is something similar to middlewares but not as middlewares. Visit [here](https://github.com/meteorhacks/flow-router/pull/59) to learn about design decisions. + +_**Now, middlewares are deprecated.**_ + +### v1.9.0 +Fix [#120](https://github.com/meteorhacks/flow-router/issues/120) and added callback support for `FlowRouter.subsReady()`. + +### v1.8.0 + +This release comes with improvements to the reactive API. + +* Fixed [#77](https://github.com/meteorhacks/flow-router/issues/77), [#85](https://github.com/meteorhacks/flow-router/issues/85), [#95](https://github.com/meteorhacks/flow-router/issues/95), [#96](https://github.com/meteorhacks/flow-router/issues/96), [#103](https://github.com/meteorhacks/flow-router/issues/103) +* Add a new API called `FlowRouter.watchPathChange()` +* Deprecated `FlowRouter.reactiveCurrent()` in the favour of `FlowRouter.watchPathChange()` diff --git a/packages/kadira-flow-router/CONTRIBUTING.md b/packages/kadira-flow-router/CONTRIBUTING.md new file mode 100644 index 00000000..adb08f1b --- /dev/null +++ b/packages/kadira-flow-router/CONTRIBUTING.md @@ -0,0 +1,16 @@ +## Whether to submit an issue or not? + +We've very limited time to answer all the issues and respond them in a proper manner. +So, this repo's issue list only used to report **bugs** and **new features.** + +For any other questions, issues or asking for best practices use [Meteor Forums](https://forums.meteor.com/). +Even before you ask a question on Meteor Forums, make sure you read the [Meteor Routing Guide](https://kadira.io/academy/meteor-routing-guide). + +## Implementing Feature and Bug Fixes + +We are welcome and greedy for PRs. So, + +* If you wanna fix a bug, simply submit it. +* If you wanna implement feature or support with contributions, just drop a message to arunoda [at] kadira.io. + + diff --git a/packages/kadira-flow-router/LICENSE b/packages/kadira-flow-router/LICENSE new file mode 100644 index 00000000..6519acbf --- /dev/null +++ b/packages/kadira-flow-router/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 MeteorHacks Pvt Ltd (Sri Lanka). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/packages/kadira-flow-router/README.md b/packages/kadira-flow-router/README.md new file mode 100644 index 00000000..7e74eb10 --- /dev/null +++ b/packages/kadira-flow-router/README.md @@ -0,0 +1,777 @@ +# FlowRouter [![Build Status](https://travis-ci.org/kadirahq/flow-router.svg?branch=master)](https://travis-ci.org/kadirahq/flow-router) [![Stories in Ready](https://badge.waffle.io/kadirahq/flow-router.svg?label=doing&title=Activities)](http://waffle.io/kadirahq/flow-router) + +Forked for bug fixes + +Carefully Designed Client Side Router for Meteor. + +FlowRouter is a very simple router for Meteor. It does routing for client-side apps and does not handle rendering itself. + +It exposes a great API for changing the URL and reactively getting data from the URL. However, inside the router, it's not reactive. Most importantly, FlowRouter is designed with performance in mind and it focuses on what it does best: **routing**. + +> We've released 2.0 and follow this [migration guide](#migrating-into-20) if you are already using FlowRouter. + +## TOC + +* [Meteor Routing Guide](#meteor-routing-guide) +* [Getting Started](#getting-started) +* [Routes Definition](#routes-definition) +* [Group Routes](#group-routes) +* [Rendering and Layout Management](#rendering-and-layout-management) +* [Triggers](#triggers) +* [Not Found Routes](#not-found-routes) +* [API](#api) +* [Subscription Management](#subscription-management) +* [IE9 Support](#ie9-support) +* [Hashbang URLs](#hashbang-urls) +* [Prefixed paths](#prefixed-paths) +* [Add-ons](#add-ons) +* [Difference with Iron Router](#difference-with-iron-router) +* [Migrating into 2.0](#migrating-into-20) + +## Meteor Routing Guide + +[Meteor Routing Guide](https://kadira.io/academy/meteor-routing-guide) is a completed guide into **routing** and related topics in Meteor. It talks about how to use FlowRouter properly and use it with **Blaze and React**. It also shows how to manage **subscriptions** and implement **auth logic** in the view layer. + +[![Meteor Routing Guide](https://cldup.com/AxlPfoxXmR.png)](https://kadira.io/academy/meteor-routing-guide) + +## Getting Started + +Add FlowRouter to your app: + +~~~shell +meteor add kadira:flow-router +~~~ + +Let's write our first route (add this file to `lib/router.js`): + +~~~js +FlowRouter.route('/blog/:postId', { + action: function(params, queryParams) { + console.log("Yeah! We are on the post:", params.postId); + } +}); +~~~ + +Then visit `/blog/my-post-id` from the browser or invoke the following command from the browser console: + +~~~js +FlowRouter.go('/blog/my-post-id'); +~~~ + +Then you can see some messages printed in the console. + +## Routes Definition + +FlowRouter routes are very simple and based on the syntax of [path-to-regexp](https://github.com/pillarjs/path-to-regexp) which is used in both [Express](http://expressjs.com/) and `iron:router`. + +Here's the syntax for a simple route: + +~~~js +FlowRouter.route('/blog/:postId', { + // do some action for this route + action: function(params, queryParams) { + console.log("Params:", params); + console.log("Query Params:", queryParams); + }, + + name: "" // optional +}); +~~~ + +So, this route will be activated when you visit a url like below: + +~~~js +FlowRouter.go('/blog/my-post?comments=on&color=dark'); +~~~ + +After you've visit the route, this will be printed in the console: + +~~~ +Params: {postId: "my-post"} +Query Params: {comments: "on", color: "dark"} +~~~ + +For a single interaction, the router only runs once. That means, after you've visit a route, first it will call `triggers`, then `subscriptions` and finally `action`. After that happens, none of those methods will be called again for that route visit. + +You can define routes anywhere in the `client` directory. But, we recommend to add them in the `lib` directory. Then `fast-render` can detect subscriptions and send them for you (we'll talk about this is a moment). + +### Group Routes + +You can group routes for better route organization. Here's an example: + +~~~js +var adminRoutes = FlowRouter.group({ + prefix: '/admin', + name: 'admin', + triggersEnter: [function(context, redirect) { + console.log('running group triggers'); + }] +}); + +// handling /admin route +adminRoutes.route('/', { + action: function() { + BlazeLayout.render('componentLayout', {content: 'admin'}); + }, + triggersEnter: [function(context, redirect) { + console.log('running /admin trigger'); + }] +}); + +// handling /admin/posts +adminRoutes.route('/posts', { + action: function() { + BlazeLayout.render('componentLayout', {content: 'posts'}); + } +}); +~~~ + +**All of the options for the `FlowRouter.group()` are optional.** + +You can even have nested group routes as shown below: + +~~~js +var adminRoutes = FlowRouter.group({ + prefix: "/admin", + name: "admin" +}); + +var superAdminRoutes = adminRoutes.group({ + prefix: "/super", + name: "superadmin" +}); + +// handling /admin/super/post +superAdminRoutes.route('/post', { + action: function() { + + } +}); +~~~ + +You can determine which group the current route is in using: + +~~~js +FlowRouter.current().route.group.name +~~~ + +This can be useful for determining if the current route is in a specific group (e.g. *admin*, *public*, *loggedIn*) without needing to use prefixes if you don't want to. If it's a nested group, you can get the parent group's name with: + +~~~js +FlowRouter.current().route.group.parent.name +~~~ + +As with all current route properties, these are not reactive, but can be combined with `FlowRouter.watchPathChange()` to get group names reactively. + +## Rendering and Layout Management + +FlowRouter does not handle rendering or layout management. For that, you can use: + + * [Blaze Layout for Blaze](https://github.com/kadirahq/blaze-layout) + * [React Layout for React](https://github.com/kadirahq/meteor-react-layout) + +Then you can invoke the layout manager inside the `action` method in the router. + +~~~js +FlowRouter.route('/blog/:postId', { + action: function(params) { + BlazeLayout.render("mainLayout", {area: "blog"}); + } +}); +~~~ + +## Triggers + +Triggers are the way FlowRouter allows you to perform tasks before you **enter** into a route and after you **exit** from a route. + +#### Defining triggers for a route + +Here's how you can define triggers for a route: + +~~~js +FlowRouter.route('/home', { + // calls just before the action + triggersEnter: [trackRouteEntry], + action: function() { + // do something you like + }, + // calls when we decide to move to another route + // but calls before the next route started + triggersExit: [trackRouteClose] +}); + +function trackRouteEntry(context) { + // context is the output of `FlowRouter.current()` + Mixpanel.track("visit-to-home", context.queryParams); +} + +function trackRouteClose(context) { + Mixpanel.track("move-from-home", context.queryParams); +} +~~~ + +#### Defining triggers for a group route + +This is how you can define triggers on a group definition. + +~~~js +var adminRoutes = FlowRouter.group({ + prefix: '/admin', + triggersEnter: [trackRouteEntry], + triggersExit: [trackRouteEntry] +}); +~~~ + +> You can add triggers to individual routes in the group too. + +#### Defining Triggers Globally + +You can also define triggers globally. Here's how to do it: + +~~~js +FlowRouter.triggers.enter([cb1, cb2]); +FlowRouter.triggers.exit([cb1, cb2]); + +// filtering +FlowRouter.triggers.enter([trackRouteEntry], {only: ["home"]}); +FlowRouter.triggers.exit([trackRouteExit], {except: ["home"]}); +~~~ + +As you can see from the last two examples, you can filter routes using the `only` or `except` keywords. But, you can't use both `only` and `except` at once. + +> If you'd like to learn more about triggers and design decisions, visit [here](https://github.com/meteorhacks/flow-router/pull/59). + +#### Redirecting With Triggers + +You can redirect to a different route using triggers. You can do it from both enter and exit triggers. See how to do it: + +~~~js +FlowRouter.route('/', { + triggersEnter: [function(context, redirect) { + redirect('/some-other-path'); + }], + action: function(_params) { + throw new Error("this should not get called"); + } +}); +~~~ + +Every trigger callback comes with a second argument: a function you can use to redirect to a different route. Redirect also has few properties to make sure it's not blocking the router. + +* redirect must be called with an URL +* redirect must be called within the same event loop cycle (no async or called inside a Tracker) +* redirect cannot be called multiple times + +Check this [PR](https://github.com/meteorhacks/flow-router/pull/172) to learn more about our redirect API. + +#### Stopping the Callback With Triggers + +In some cases, you may need to stop the route callback from firing using triggers. You can do this in **before** triggers, using the third argument: the `stop` function. For example, you can check the prefix and if it fails, show the notFound layout and stop before the action fires. + +```js +var localeGroup = FlowRouter.group({ + prefix: '/:locale?', + triggersEnter: [localeCheck] +}); + +localeGroup.route('/login', { + action: function (params, queryParams) { + BlazeLayout.render('componentLayout', {content: 'login'}); + } +}); + +function localeCheck(context, redirect, stop) { + var locale = context.params.locale; + + if (locale !== undefined && locale !== 'fr') { + BlazeLayout.render('notFound'); + stop(); + } +} +``` + +> **Note**: When using the stop function, you should always pass the second **redirect** argument, even if you won't use it. + +## Not Found Routes + +You can configure Not Found routes like this: + +~~~js +FlowRouter.notFound = { + // Subscriptions registered here don't have Fast Render support. + subscriptions: function() { + + }, + action: function() { + + } +}; +~~~ + +## API + +FlowRouter has a rich API to help you to navigate the router and reactively get information from the router. + +#### FlowRouter.getParam(paramName); + +Reactive function which you can use to get a parameter from the URL. + +~~~js +// route def: /apps/:appId +// url: /apps/this-is-my-app + +var appId = FlowRouter.getParam("appId"); +console.log(appId); // prints "this-is-my-app" +~~~ + +#### FlowRouter.getQueryParam(queryStringKey); + +Reactive function which you can use to get a value from the queryString. + +~~~js +// route def: /apps/:appId +// url: /apps/this-is-my-app?show=yes&color=red + +var color = FlowRouter.getQueryParam("color"); +console.log(color); // prints "red" +~~~ + +#### FlowRouter.path(pathDef, params, queryParams) + +Generate a path from a path definition. Both `params` and `queryParams` are optional. + +Special characters in `params` and `queryParams` will be URL encoded. + +~~~js +var pathDef = "/blog/:cat/:id"; +var params = {cat: "met eor", id: "abc"}; +var queryParams = {show: "y+e=s", color: "black"}; + +var path = FlowRouter.path(pathDef, params, queryParams); +console.log(path); // prints "/blog/met%20eor/abc?show=y%2Be%3Ds&color=black" +~~~ + +If there are no params or queryParams, this will simply return the pathDef as it is. + +##### Using Route name instead of the pathDef + +You can also use the route's name instead of the pathDef. Then, FlowRouter will pick the pathDef from the given route. See the following example: + +~~~js +FlowRouter.route("/blog/:cat/:id", { + name: "blogPostRoute", + action: function(params) { + //... + } +}) + +var params = {cat: "meteor", id: "abc"}; +var queryParams = {show: "yes", color: "black"}; + +var path = FlowRouter.path("blogPostRoute", params, queryParams); +console.log(path); // prints "/blog/meteor/abc?show=yes&color=black" +~~~ + +#### FlowRouter.go(pathDef, params, queryParams); + +This will get the path via `FlowRouter.path` based on the arguments and re-route to that path. + +You can call `FlowRouter.go` like this as well: + +~~~js +FlowRouter.go("/blog"); +~~~ + + +#### FlowRouter.url(pathDef, params, queryParams) + +Just like `FlowRouter.path`, but gives the absolute url. (Uses `Meteor.absoluteUrl` behind the scenes.) + +#### FlowRouter.setParams(newParams) + +This will change the current params with the newParams and re-route to the new path. + +~~~js +// route def: /apps/:appId +// url: /apps/this-is-my-app?show=yes&color=red + +FlowRouter.setParams({appId: "new-id"}); +// Then the user will be redirected to the following path +// /apps/new-id?show=yes&color=red +~~~ + +#### FlowRouter.setQueryParams(newQueryParams) + +Just like `FlowRouter.setParams`, but for queryString params. + +To remove a query param set it to `null` like below: + +~~~js +FlowRouter.setQueryParams({paramToRemove: null}); +~~~ + +#### FlowRouter.getRouteName() + +To get the name of the route reactively. + +~~~js +Tracker.autorun(function() { + var routeName = FlowRouter.getRouteName(); + console.log("Current route name is: ", routeName); +}); +~~~ + +#### FlowRouter.current() + +Get the current state of the router. **This API is not reactive**. +If you need to watch the changes in the path simply use `FlowRouter.watchPathChange()`. + +This gives an object like this: + +~~~js +// route def: /apps/:appId +// url: /apps/this-is-my-app?show=yes&color=red + +var current = FlowRouter.current(); +console.log(current); + +// prints following object +// { +// path: "/apps/this-is-my-app?show=yes&color=red", +// params: {appId: "this-is-my-app"}, +// queryParams: {show: "yes", color: "red"} +// route: {pathDef: "/apps/:appId", name: "name-of-the-route"} +// } +~~~ + +#### FlowRouter.watchPathChange() + +Reactively watch the changes in the path. If you need to simply get the params or queryParams use dedicated APIs like `FlowRouter.getQueryParam()`. + +~~~js +Tracker.autorun(function() { + FlowRouter.watchPathChange(); + var currentContext = FlowRouter.current(); + // do anything with the current context + // or anything you wish +}); +~~~ + +#### FlowRouter.withReplaceState(fn) +Normally, all the route changes made via APIs like `FlowRouter.go` and `FlowRouter.setParams()` add a URL item to the browser history. For example, run the following code: + +~~~js +FlowRouter.setParams({id: "the-id-1"}); +FlowRouter.setParams({id: "the-id-2"}); +FlowRouter.setParams({id: "the-id-3"}); +~~~ + +Now you can hit the back button of your browser two times. This is normal behavior since users may click the back button and expect to see the previous state of the app. + +But sometimes, this is not something you want. You don't need to pollute the browser history. Then, you can use the following syntax. + +~~~js +FlowRouter.withReplaceState(function() { + FlowRouter.setParams({id: "the-id-1"}); + FlowRouter.setParams({id: "the-id-2"}); + FlowRouter.setParams({id: "the-id-3"}); +}); +~~~ + +Now, there is no item in the browser history. Just like `FlowRouter.setParams`, you can use any FlowRouter API inside `FlowRouter.withReplaceState`. + +> We named this function as `withReplaceState` because, replaceState is the underline API used for this functionality. Read more about [replace state & the history API](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history). + +#### FlowRouter.reload() + +FlowRouter routes are idempotent. That means, even if you call `FlowRouter.go()` to the same URL multiple times, it only activates in the first run. This is also true for directly clicking on paths. + +So, if you really need to reload the route, this is the API you want. + +#### FlowRouter.wait() and FlowRouter.initialize() + +By default, FlowRouter initializes the routing process in a `Meteor.startup()` callback. This works for most of the apps. But, some apps have custom initializations and FlowRouter needs to initialize after that. + +So, that's where `FlowRouter.wait()` comes to save you. You need to call it directly inside your JavaScript file. After that, whenever your app is ready call `FlowRouter.initialize()`. + +eg:- + +~~~js +// file: app.js +FlowRouter.wait(); +WhenEverYourAppIsReady(function() { + FlowRouter.initialize(); +}); +~~~ + +For more information visit [issue #180](https://github.com/meteorhacks/flow-router/issues/180). + +#### FlowRouter.onRouteRegister(cb) + +This API is specially designed for add-on developers. They can listen for any registered route and add custom functionality to FlowRouter. This works on both server and client alike. + +~~~js +FlowRouter.onRouteRegister(function(route) { + // do anything with the route object + console.log(route); +}); +~~~ + +Let's say a user defined a route like this: + +~~~js +FlowRouter.route('/blog/:post', { + name: 'postList', + triggersEnter: [function() {}], + subscriptions: function() {}, + action: function() {}, + triggersExit: [function() {}], + customField: 'customName' +}); +~~~ + +Then the route object will be something like this: + +~~~js +{ + pathDef: '/blog/:post', + name: 'postList', + options: {customField: 'customName'} +} +~~~ + +So, it's not the internal route object we are using. + +## Subscription Management + +For Subscription Management, we highly suggest you to follow [Template/Component level subscriptions](https://kadira.io/academy/meteor-routing-guide/content/subscriptions-and-data-management). Visit this [guide](https://kadira.io/academy/meteor-routing-guide/content/subscriptions-and-data-management) for that. + +FlowRouter also has it's own subscription registration mechanism. We will remove this in version 3.0. We don't remove or deprecate it in version 2.x because this is the easiest way to implement FastRender support for your app. In 3.0 we've better support for FastRender with Server Side Rendering. + +FlowRouter only deals with registration of subscriptions. It does not wait until subscription becomes ready. This is how to register a subscription. + +~~~js +FlowRouter.route('/blog/:postId', { + subscriptions: function(params, queryParams) { + this.register('myPost', Meteor.subscribe('blogPost', params.postId)); + } +}); +~~~ + +We can also register global subscriptions like this: + +~~~js +FlowRouter.subscriptions = function() { + this.register('myCourses', Meteor.subscribe('courses')); +}; +~~~ + +All these global subscriptions run on every route. So, pay special attention to names when registering subscriptions. + +After you've registered your subscriptions, you can reactively check for the status of those subscriptions like this: + +~~~js +Tracker.autorun(function() { + console.log("Is myPost ready?:", FlowRouter.subsReady("myPost")); + console.log("Are all subscriptions ready?:", FlowRouter.subsReady()); +}); +~~~ + +So, you can use `FlowRouter.subsReady` inside template helpers to show the loading status and act accordingly. + +### FlowRouter.subsReady() with a callback + +Sometimes, we need to use `FlowRouter.subsReady()` in places where an autorun is not available. One such example is inside an event handler. For such places, we can use the callback API of `FlowRouter.subsReady()`. + +~~~js +Template.myTemplate.events({ + "click #id": function(){ + FlowRouter.subsReady("myPost", function() { + // do something + }); + } +}); +~~~ + +> Arunoda has discussed more about Subscription Management in FlowRouter in [this](https://meteorhacks.com/flow-router-and-subscription-management.html#subscription-management) blog post about [FlowRouter and Subscription Management](https://meteorhacks.com/flow-router-and-subscription-management.html). + +> He's showing how to build an app like this: + +>![FlowRouter's Subscription Management](https://cldup.com/esLzM8cjEL.gif) + +#### Fast Render +FlowRouter has built in support for [Fast Render](https://github.com/meteorhacks/fast-render). + +- `meteor add meteorhacks:fast-render` +- Put `router.js` in a shared location. We suggest `lib/router.js`. + +You can exclude Fast Render support by wrapping the subscription registration in an `isClient` block: + +~~~js +FlowRouter.route('/blog/:postId', { + subscriptions: function(params, queryParams) { + // using Fast Render + this.register('myPost', Meteor.subscribe('blogPost', params.postId)); + + // not using Fast Render + if(Meteor.isClient) { + this.register('data', Meteor.subscribe('bootstrap-data'); + } + } +}); +~~~ + +#### Subscription Caching + +You can also use [Subs Manager](https://github.com/meteorhacks/subs-manager) for caching subscriptions on the client. We haven't done anything special to make it work. It should work as it works with other routers. + +## IE9 Support + +FlowRouter has IE9 support. But it does not ship the **HTML5 history polyfill** out of the box. That's because most apps do not require it. + +If you need to support IE9, add the **HTML5 history polyfill** with the following package. + +~~~shell +meteor add tomwasd:history-polyfill +~~~ + +## Hashbang URLs + +To enable hashbang urls like `mydomain.com/#!/mypath` simple set the `hashbang` option to `true` in the initialize function: + +~~~js +// file: app.js +FlowRouter.wait(); +WhenEverYourAppIsReady(function() { + FlowRouter.initialize({hashbang: true}); +}); +~~~ + +## Prefixed paths + +In cases you wish to run multiple web application on the same domain name, you’ll probably want to serve your particular meteor application under a sub-path (eg `example.com/myapp`). In this case simply include the path prefix in the meteor `ROOT_URL` environment variable and FlowRouter will handle it transparently without any additional configuration. + +## Add-ons + +Router is a base package for an app. Other projects like [useraccounts](http://useraccounts.meteor.com/) should have support for FlowRouter. Otherwise, it's hard to use FlowRouter in a real project. Now a lot of packages have [started to support FlowRouter](https://kadira.io/blog/meteor/addon-packages-for-flowrouter). + +So, you can use your your favorite package with FlowRouter as well. If not, there is an [easy process](https://kadira.io/blog/meteor/addon-packages-for-flowrouter#what-if-project-xxx-still-doesn-t-support-flowrouter-) to convert them to FlowRouter. + +**Add-on API** + +We have also released a [new API](https://github.com/kadirahq/flow-router#flowrouteronrouteregistercb) to support add-on developers. With that add-on packages can get a notification, when the user created a route in their app. + +If you've more ideas for the add-on API, [let us know](https://github.com/kadirahq/flow-router/issues). + +## Difference with Iron Router + +FlowRouter and Iron Router are two different routers. Iron Router tries to be a full featured solution. It tries to do everything including routing, subscriptions, rendering and layout management. + +FlowRouter is a minimalistic solution focused on routing with UI performance in mind. It exposes APIs for related functionality. + +Let's learn more about the differences: + +### Rendering + +FlowRouter doesn't handle rendering. By decoupling rendering from the router it's possible to use any rendering framework, such as [Blaze Layout](https://github.com/kadirahq/blaze-layout) to render with Blaze's Dynamic Templates. Rendering calls are made in the the route's action. We have a layout manager for [React](https://github.com/kadirahq/meteor-react-layout) as well. + +### Subscriptions + +With FlowRouter, we highly suggest using template/component layer subscriptions. But, if you need to do routing in the router layer, FlowRouter has [subscription registration](#subscription-management) mechanism. Even with that, FlowRouter never waits for the subscriptions and view layer to do it. + +### Reactive Content + +In Iron Router you can use reactive content inside the router, but any hook or method can re-run in an unpredictable manner. FlowRouter limits reactive data sources to a single run; when it is first called. + +We think that's the way to go. Router is just a user action. We can work with reactive content in the rendering layer. + +### router.current() is evil + +`Router.current()` is evil. Why? Let's look at following example. Imagine we have a route like this in our app: + +~~~ +/apps/:appId/:section +~~~ + +Now let's say, we need to get `appId` from the URL. Then we will do, something like this in Iron Router. + +~~~js +Templates['foo'].helpers({ + "someData": function() { + var appId = Router.current().params.appId; + return doSomething(appId); + } +}); +~~~ + +Let's say we changed `:section` in the route. Then the above helper also gets rerun. If we add a query param to the URL, it gets rerun. That's because `Router.current()` looks for changes in the route(or URL). But in any of above cases, `appId` didn't get changed. + +Because of this, a lot parts of our app get re-run and re-rendered. This creates unpredictable rendering behavior in our app. + +FlowRouter fixes this issue by providing the `Router.getParam()` API. See how to use it: + +~~~js +Templates['foo'].helpers({ + "someData": function() { + var appId = FlowRouter.getParam('appId'); + return doSomething(appId); + } +}); +~~~ + +### No data context + +FlowRouter does not have a data context. Data context has the same problem as reactive `.current()`. We believe, it'll possible to get data directly in the template (component) layer. + +### Built in Fast Render Support + +FlowRouter has built in [Fast Render](https://github.com/meteorhacks/fast-render) support. Just add Fast Render to your app and it'll work. Nothing to change in the router. + +For more information check [docs](#fast-render). + +### Server Side Routing + +FlowRouter is a client side router and it **does not** support server side routing at all. But `subscriptions` run on the server to enable Fast Render support. + +#### Reason behind that + +Meteor is not a traditional framework where you can send HTML directly from the server. Meteor needs to send a special set of HTML to the client initially. So, you can't directly send something to the client yourself. + +Also, in the server we need look for different things compared with the client. For example: + +* In the server we have to deal with headers. +* In the server we have to deal with methods like `GET`, `POST`, etc. +* In the server we have Cookies. + +So, it's better to use a dedicated server-side router like [`meteorhacks:picker`](https://github.com/meteorhacks/picker). It supports connect and express middlewares and has a very easy to use route syntax. + +### Server Side Rendering + +FlowRouter 3.0 will have server side rendering support. We've already started the initial version and check our [`ssr`](https://github.com/meteorhacks/flow-router/tree/ssr) branch for that. + +It's currently very usable and Kadira already using it for + +### Better Initial Loading Support + +In Meteor, we have to wait until all the JS and other resources send before rendering anything. This is an issue. In 3.0, with the support from Server Side Rendering we are going to fix it. + +## Migrating into 2.0 + +Migrating into version 2.0 is easy and you don't need to change any application code since you are already using 2.0 features and the APIs. In 2.0, we've changed names and removed some deprecated APIs. + +Here are the steps to migrate your app into 2.0. + +#### Use the New FlowRouter Package +* Now FlowRouter comes as `kadira:flow-router` +* So, remove `meteorhacks:flow-router` with : `meteor remove meteorhacks:flow-router` +* Then, add `kadira:flow-router` with `meteor add kadira:flow-router` + +#### Change FlowLayout into BlazeLayout +* We've also renamed FlowLayout as [BlazeLayout](https://github.com/kadirahq/blaze-layout). +* So, remove `meteorhacks:flow-layout` and add `kadira:blaze-layout` instead. +* You need to use `BlazeLayout.render()` instead of `FlowLayout.render()` + +#### Stop using deprecated Apis +* There is no middleware support. Use triggers instead. +* There is no API called `.reactiveCurrent()`, use `.watchPathChange()` instead. +* Earlier, you can access query params with `FlowRouter.current().params.query`. But, now you can't do that. Use `FlowRouter.current().queryParams` instead. diff --git a/packages/kadira-flow-router/client/_init.js b/packages/kadira-flow-router/client/_init.js new file mode 100644 index 00000000..a18fdc89 --- /dev/null +++ b/packages/kadira-flow-router/client/_init.js @@ -0,0 +1,11 @@ +// Export Router Instance +FlowRouter = new Router(); +FlowRouter.Router = Router; +FlowRouter.Route = Route; + +// Initialize FlowRouter +Meteor.startup(function () { + if(!FlowRouter._askedToWait) { + FlowRouter.initialize(); + } +}); diff --git a/packages/kadira-flow-router/client/group.js b/packages/kadira-flow-router/client/group.js new file mode 100644 index 00000000..b93296bc --- /dev/null +++ b/packages/kadira-flow-router/client/group.js @@ -0,0 +1,57 @@ +Group = function(router, options, parent) { + options = options || {}; + + if (options.prefix && !/^\/.*/.test(options.prefix)) { + var message = "group's prefix must start with '/'"; + throw new Error(message); + } + + this._router = router; + this.prefix = options.prefix || ''; + this.name = options.name; + this.options = options; + + this._triggersEnter = options.triggersEnter || []; + this._triggersExit = options.triggersExit || []; + this._subscriptions = options.subscriptions || Function.prototype; + + this.parent = parent; + if (this.parent) { + this.prefix = parent.prefix + this.prefix; + + this._triggersEnter = parent._triggersEnter.concat(this._triggersEnter); + this._triggersExit = this._triggersExit.concat(parent._triggersExit); + } +}; + +Group.prototype.route = function(pathDef, options, group) { + options = options || {}; + + if (!/^\/.*/.test(pathDef)) { + var message = "route's path must start with '/'"; + throw new Error(message); + } + + group = group || this; + pathDef = this.prefix + pathDef; + + var triggersEnter = options.triggersEnter || []; + options.triggersEnter = this._triggersEnter.concat(triggersEnter); + + var triggersExit = options.triggersExit || []; + options.triggersExit = triggersExit.concat(this._triggersExit); + + return this._router.route(pathDef, options, group); +}; + +Group.prototype.group = function(options) { + return new Group(this._router, options, this); +}; + +Group.prototype.callSubscriptions = function(current) { + if (this.parent) { + this.parent.callSubscriptions(current); + } + + this._subscriptions.call(current.route, current.params, current.queryParams); +}; diff --git a/packages/kadira-flow-router/client/modules.js b/packages/kadira-flow-router/client/modules.js new file mode 100644 index 00000000..7b734f44 --- /dev/null +++ b/packages/kadira-flow-router/client/modules.js @@ -0,0 +1,2 @@ +page = require('page'); +qs = require('qs'); diff --git a/packages/kadira-flow-router/client/route.js b/packages/kadira-flow-router/client/route.js new file mode 100644 index 00000000..b82e9721 --- /dev/null +++ b/packages/kadira-flow-router/client/route.js @@ -0,0 +1,125 @@ +Route = function(router, pathDef, options, group) { + options = options || {}; + + this.options = options; + this.pathDef = pathDef + + // Route.path is deprecated and will be removed in 3.0 + this.path = pathDef; + + if (options.name) { + this.name = options.name; + } + + this._action = options.action || Function.prototype; + this._subscriptions = options.subscriptions || Function.prototype; + this._triggersEnter = options.triggersEnter || []; + this._triggersExit = options.triggersExit || []; + this._subsMap = {}; + this._router = router; + + this._params = new ReactiveDict(); + this._queryParams = new ReactiveDict(); + this._routeCloseDep = new Tracker.Dependency(); + + // tracks the changes in the URL + this._pathChangeDep = new Tracker.Dependency(); + + this.group = group; +}; + +Route.prototype.clearSubscriptions = function() { + this._subsMap = {}; +}; + +Route.prototype.register = function(name, sub, options) { + this._subsMap[name] = sub; +}; + + +Route.prototype.getSubscription = function(name) { + return this._subsMap[name]; +}; + + +Route.prototype.getAllSubscriptions = function() { + return this._subsMap; +}; + +Route.prototype.callAction = function(current) { + var self = this; + self._action(current.params, current.queryParams); +}; + +Route.prototype.callSubscriptions = function(current) { + this.clearSubscriptions(); + if (this.group) { + this.group.callSubscriptions(current); + } + + this._subscriptions(current.params, current.queryParams); +}; + +Route.prototype.getRouteName = function() { + this._routeCloseDep.depend(); + return this.name; +}; + +Route.prototype.getParam = function(key) { + this._routeCloseDep.depend(); + return this._params.get(key); +}; + +Route.prototype.getQueryParam = function(key) { + this._routeCloseDep.depend(); + return this._queryParams.get(key); +}; + +Route.prototype.watchPathChange = function() { + this._pathChangeDep.depend(); +}; + +Route.prototype.registerRouteClose = function() { + this._params = new ReactiveDict(); + this._queryParams = new ReactiveDict(); + this._routeCloseDep.changed(); + this._pathChangeDep.changed(); +}; + +Route.prototype.registerRouteChange = function(currentContext, routeChanging) { + // register params + var params = currentContext.params; + this._updateReactiveDict(this._params, params); + + // register query params + var queryParams = currentContext.queryParams; + this._updateReactiveDict(this._queryParams, queryParams); + + // if the route is changing, we need to defer triggering path changing + // if we did this, old route's path watchers will detect this + // Real issue is, above watcher will get removed with the new route + // So, we don't need to trigger it now + // We are doing it on the route close event. So, if they exists they'll + // get notify that + if(!routeChanging) { + this._pathChangeDep.changed(); + } +}; + +Route.prototype._updateReactiveDict = function(dict, newValues) { + var currentKeys = _.keys(newValues); + var oldKeys = _.keys(dict.keyDeps); + + // set new values + // params is an array. So, _.each(params) does not works + // to iterate params + _.each(currentKeys, function(key) { + dict.set(key, newValues[key]); + }); + + // remove keys which does not exisits here + var removedKeys = _.difference(oldKeys, currentKeys); + _.each(removedKeys, function(key) { + dict.set(key, undefined); + }); +}; diff --git a/packages/kadira-flow-router/client/router.js b/packages/kadira-flow-router/client/router.js new file mode 100644 index 00000000..ae91751f --- /dev/null +++ b/packages/kadira-flow-router/client/router.js @@ -0,0 +1,587 @@ +Router = function () { + var self = this; + this.globals = []; + this.subscriptions = Function.prototype; + + this._tracker = this._buildTracker(); + this._current = {}; + + // tracks the current path change + this._onEveryPath = new Tracker.Dependency(); + + this._globalRoute = new Route(this); + + // holds onRoute callbacks + this._onRouteCallbacks = []; + + // if _askedToWait is true. We don't automatically start the router + // in Meteor.startup callback. (see client/_init.js) + // Instead user need to call `.initialize() + this._askedToWait = false; + this._initialized = false; + this._triggersEnter = []; + this._triggersExit = []; + this._routes = []; + this._routesMap = {}; + this._updateCallbacks(); + this.notFound = this.notfound = null; + // indicate it's okay (or not okay) to run the tracker + // when doing subscriptions + // using a number and increment it help us to support FlowRouter.go() + // and legitimate reruns inside tracker on the same event loop. + // this is a solution for #145 + this.safeToRun = 0; + + // Meteor exposes to the client the path prefix that was defined using the + // ROOT_URL environement variable on the server using the global runtime + // configuration. See #315. + this._basePath = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || ''; + + // this is a chain contains a list of old routes + // most of the time, there is only one old route + // but when it's the time for a trigger redirect we've a chain + this._oldRouteChain = []; + + this.env = { + replaceState: new Meteor.EnvironmentVariable(), + reload: new Meteor.EnvironmentVariable(), + trailingSlash: new Meteor.EnvironmentVariable() + }; + + // redirect function used inside triggers + this._redirectFn = function(pathDef, fields, queryParams) { + if (/^http(s)?:\/\//.test(pathDef)) { + var message = "Redirects to URLs outside of the app are not supported in this version of Flow Router. Use 'window.location = yourUrl' instead"; + throw new Error(message); + } + self.withReplaceState(function() { + var path = FlowRouter.path(pathDef, fields, queryParams); + self._page.redirect(path); + }); + }; + this._initTriggersAPI(); +}; + +Router.prototype.route = function(pathDef, options, group) { + if (!/^\/.*/.test(pathDef)) { + var message = "route's path must start with '/'"; + throw new Error(message); + } + + options = options || {}; + var self = this; + var route = new Route(this, pathDef, options, group); + + // calls when the page route being activates + route._actionHandle = function (context, next) { + var oldRoute = self._current.route; + self._oldRouteChain.push(oldRoute); + + var queryParams = self._qs.parse(context.querystring); + // _qs.parse() gives us a object without prototypes, + // created with Object.create(null) + // Meteor's check doesn't play nice with it. + // So, we need to fix it by cloning it. + // see more: https://github.com/meteorhacks/flow-router/issues/164 + queryParams = JSON.parse(JSON.stringify(queryParams)); + + self._current = { + path: context.path, + context: context, + params: context.params, + queryParams: queryParams, + route: route, + oldRoute: oldRoute + }; + + // we need to invalidate if all the triggers have been completed + // if not that means, we've been redirected to another path + // then we don't need to invalidate + var afterAllTriggersRan = function() { + self._invalidateTracker(); + }; + + var triggers = self._triggersEnter.concat(route._triggersEnter); + Triggers.runTriggers( + triggers, + self._current, + self._redirectFn, + afterAllTriggersRan + ); + }; + + // calls when you exit from the page js route + route._exitHandle = function(context, next) { + var triggers = self._triggersExit.concat(route._triggersExit); + Triggers.runTriggers( + triggers, + self._current, + self._redirectFn, + next + ); + }; + + this._routes.push(route); + if (options.name) { + this._routesMap[options.name] = route; + } + + this._updateCallbacks(); + this._triggerRouteRegister(route); + + return route; +}; + +Router.prototype.group = function(options) { + return new Group(this, options); +}; + +Router.prototype.path = function(pathDef, fields, queryParams) { + if (this._routesMap[pathDef]) { + pathDef = this._routesMap[pathDef].pathDef; + } + + var path = ""; + + // Prefix the path with the router global prefix + if (this._basePath) { + path += "/" + this._basePath + "/"; + } + + fields = fields || {}; + var regExp = /(:[\w\(\)\\\+\*\.\?]+)+/g; + path += pathDef.replace(regExp, function(key) { + var firstRegexpChar = key.indexOf("("); + // get the content behind : and (\\d+/) + key = key.substring(1, (firstRegexpChar > 0)? firstRegexpChar: undefined); + // remove +?* + key = key.replace(/[\+\*\?]+/g, ""); + + // this is to allow page js to keep the custom characters as it is + // we need to encode 2 times otherwise "/" char does not work properly + // So, in that case, when I includes "/" it will think it's a part of the + // route. encoding 2times fixes it + return encodeURIComponent(encodeURIComponent(fields[key] || "")); + }); + + // Replace multiple slashes with single slash + path = path.replace(/\/\/+/g, "/"); + + // remove trailing slash + // but keep the root slash if it's the only one + path = path.match(/^\/{1}$/) ? path: path.replace(/\/$/, ""); + + // explictly asked to add a trailing slash + if(this.env.trailingSlash.get() && _.last(path) !== "/") { + path += "/"; + } + + var strQueryParams = this._qs.stringify(queryParams || {}); + if(strQueryParams) { + path += "?" + strQueryParams; + } + + return path; +}; + +Router.prototype.go = function(pathDef, fields, queryParams) { + var path = this.path(pathDef, fields, queryParams); + + var useReplaceState = this.env.replaceState.get(); + if(useReplaceState) { + this._page.replace(path); + } else { + this._page(path); + } +}; + +Router.prototype.reload = function() { + var self = this; + + self.env.reload.withValue(true, function() { + self._page.replace(self._current.path); + }); +}; + +Router.prototype.redirect = function(path) { + this._page.redirect(path); +}; + +Router.prototype.setParams = function(newParams) { + if(!this._current.route) {return false;} + + var pathDef = this._current.route.pathDef; + var existingParams = this._current.params; + var params = {}; + _.each(_.keys(existingParams), function(key) { + params[key] = existingParams[key]; + }); + + params = _.extend(params, newParams); + var queryParams = this._current.queryParams; + + this.go(pathDef, params, queryParams); + return true; +}; + +Router.prototype.setQueryParams = function(newParams) { + if(!this._current.route) {return false;} + + var queryParams = _.clone(this._current.queryParams); + _.extend(queryParams, newParams); + + for (var k in queryParams) { + if (queryParams[k] === null || queryParams[k] === undefined) { + delete queryParams[k]; + } + } + + var pathDef = this._current.route.pathDef; + var params = this._current.params; + this.go(pathDef, params, queryParams); + return true; +}; + +// .current is not reactive +// This is by design. use .getParam() instead +// If you really need to watch the path change, use .watchPathChange() +Router.prototype.current = function() { + // We can't trust outside, that's why we clone this + // Anyway, we can't clone the whole object since it has non-jsonable values + // That's why we clone what's really needed. + var current = _.clone(this._current); + current.queryParams = EJSON.clone(current.queryParams); + current.params = EJSON.clone(current.params); + return current; +}; + +// Implementing Reactive APIs +var reactiveApis = [ + 'getParam', 'getQueryParam', + 'getRouteName', 'watchPathChange' +]; +reactiveApis.forEach(function(api) { + Router.prototype[api] = function(arg1) { + // when this is calling, there may not be any route initiated + // so we need to handle it + var currentRoute = this._current.route; + if(!currentRoute) { + this._onEveryPath.depend(); + return; + } + + // currently, there is only one argument. If we've more let's add more args + // this is not clean code, but better in performance + return currentRoute[api].call(currentRoute, arg1); + }; +}); + +Router.prototype.subsReady = function() { + var callback = null; + var args = _.toArray(arguments); + + if (typeof _.last(args) === "function") { + callback = args.pop(); + } + + var currentRoute = this.current().route; + var globalRoute = this._globalRoute; + + // we need to depend for every route change and + // rerun subscriptions to check the ready state + this._onEveryPath.depend(); + + if(!currentRoute) { + return false; + } + + var subscriptions; + if(args.length === 0) { + subscriptions = _.values(globalRoute.getAllSubscriptions()); + subscriptions = subscriptions.concat(_.values(currentRoute.getAllSubscriptions())); + } else { + subscriptions = _.map(args, function(subName) { + return globalRoute.getSubscription(subName) || currentRoute.getSubscription(subName); + }); + } + + var isReady = function() { + var ready = _.every(subscriptions, function(sub) { + return sub && sub.ready(); + }); + + return ready; + }; + + if (callback) { + Tracker.autorun(function(c) { + if (isReady()) { + callback(); + c.stop(); + } + }); + } else { + return isReady(); + } +}; + +Router.prototype.withReplaceState = function(fn) { + return this.env.replaceState.withValue(true, fn); +}; + +Router.prototype.withTrailingSlash = function(fn) { + return this.env.trailingSlash.withValue(true, fn); +}; + +Router.prototype._notfoundRoute = function(context) { + this._current = { + path: context.path, + context: context, + params: [], + queryParams: {}, + }; + + // XXX this.notfound kept for backwards compatibility + this.notFound = this.notFound || this.notfound; + if(!this.notFound) { + console.error("There is no route for the path:", context.path); + return; + } + + this._current.route = new Route(this, "*", this.notFound); + this._invalidateTracker(); +}; + +Router.prototype.initialize = function(options) { + options = options || {}; + + if(this._initialized) { + throw new Error("FlowRouter is already initialized"); + } + + var self = this; + this._updateCallbacks(); + + // Implementing idempotent routing + // by overriding page.js`s "show" method. + // Why? + // It is impossible to bypass exit triggers, + // because they execute before the handler and + // can not know what the next path is, inside exit trigger. + // + // we need override both show, replace to make this work + // since we use redirect when we are talking about withReplaceState + _.each(['show', 'replace'], function(fnName) { + var original = self._page[fnName]; + self._page[fnName] = function(path, state, dispatch, push) { + var reload = self.env.reload.get(); + if (!reload && self._current.path === path) { + return; + } + + original.call(this, path, state, dispatch, push); + }; + }); + + // this is very ugly part of pagejs and it does decoding few times + // in unpredicatable manner. See #168 + // this is the default behaviour and we need keep it like that + // we are doing a hack. see .path() + this._page.base(this._basePath); + this._page({ + decodeURLComponents: true, + hashbang: !!options.hashbang + }); + + this._initialized = true; +}; + +Router.prototype._buildTracker = function() { + var self = this; + + // main autorun function + var tracker = Tracker.autorun(function () { + if(!self._current || !self._current.route) { + return; + } + + // see the definition of `this._processingContexts` + var currentContext = self._current; + var route = currentContext.route; + var path = currentContext.path; + + if(self.safeToRun === 0) { + var message = + "You can't use reactive data sources like Session" + + " inside the `.subscriptions` method!"; + throw new Error(message); + } + + // We need to run subscriptions inside a Tracker + // to stop subs when switching between routes + // But we don't need to run this tracker with + // other reactive changes inside the .subscription method + // We tackle this with the `safeToRun` variable + self._globalRoute.clearSubscriptions(); + self.subscriptions.call(self._globalRoute, path); + route.callSubscriptions(currentContext); + + // otherwise, computations inside action will trigger to re-run + // this computation. which we do not need. + Tracker.nonreactive(function() { + var isRouteChange = currentContext.oldRoute !== currentContext.route; + var isFirstRoute = !currentContext.oldRoute; + // first route is not a route change + if(isFirstRoute) { + isRouteChange = false; + } + + // Clear oldRouteChain just before calling the action + // We still need to get a copy of the oldestRoute first + // It's very important to get the oldest route and registerRouteClose() it + // See: https://github.com/kadirahq/flow-router/issues/314 + var oldestRoute = self._oldRouteChain[0]; + self._oldRouteChain = []; + + currentContext.route.registerRouteChange(currentContext, isRouteChange); + route.callAction(currentContext); + + Tracker.afterFlush(function() { + self._onEveryPath.changed(); + if(isRouteChange) { + // We need to trigger that route (definition itself) has changed. + // So, we need to re-run all the register callbacks to current route + // This is pretty important, otherwise tracker + // can't identify new route's items + + // We also need to afterFlush, otherwise this will re-run + // helpers on templates which are marked for destroying + if(oldestRoute) { + oldestRoute.registerRouteClose(); + } + } + }); + }); + + self.safeToRun--; + }); + + return tracker; +}; + +Router.prototype._invalidateTracker = function() { + var self = this; + this.safeToRun++; + this._tracker.invalidate(); + // After the invalidation we need to flush to make changes imediately + // otherwise, we have face some issues context mix-maches and so on. + // But there are some cases we can't flush. So we need to ready for that. + + // we clearly know, we can't flush inside an autorun + // this may leads some issues on flow-routing + // we may need to do some warning + if(!Tracker.currentComputation) { + // Still there are some cases where we can't flush + // eg:- when there is a flush currently + // But we've no public API or hacks to get that state + // So, this is the only solution + try { + Tracker.flush(); + } catch(ex) { + // only handling "while flushing" errors + if(!/Tracker\.flush while flushing/.test(ex.message)) { + return; + } + + // XXX: fix this with a proper solution by removing subscription mgt. + // from the router. Then we don't need to run invalidate using a tracker + + // this happens when we are trying to invoke a route change + // with inside a route chnage. (eg:- Template.onCreated) + // Since we use page.js and tracker, we don't have much control + // over this process. + // only solution is to defer route execution. + + // It's possible to have more than one path want to defer + // But, we only need to pick the last one. + // self._nextPath = self._current.path; + Meteor.defer(function() { + var path = self._nextPath; + if(!path) { + return; + } + + delete self._nextPath; + self.env.reload.withValue(true, function() { + self.go(path); + }); + }); + } + } +}; + +Router.prototype._updateCallbacks = function () { + var self = this; + + self._page.callbacks = []; + self._page.exits = []; + + _.each(self._routes, function(route) { + self._page(route.pathDef, route._actionHandle); + self._page.exit(route.pathDef, route._exitHandle); + }); + + self._page("*", function(context) { + self._notfoundRoute(context); + }); +}; + +Router.prototype._initTriggersAPI = function() { + var self = this; + this.triggers = { + enter: function(triggers, filter) { + triggers = Triggers.applyFilters(triggers, filter); + if(triggers.length) { + self._triggersEnter = self._triggersEnter.concat(triggers); + } + }, + + exit: function(triggers, filter) { + triggers = Triggers.applyFilters(triggers, filter); + if(triggers.length) { + self._triggersExit = self._triggersExit.concat(triggers); + } + } + }; +}; + +Router.prototype.wait = function() { + if(this._initialized) { + throw new Error("can't wait after FlowRouter has been initialized"); + } + + this._askedToWait = true; +}; + +Router.prototype.onRouteRegister = function(cb) { + this._onRouteCallbacks.push(cb); +}; + +Router.prototype._triggerRouteRegister = function(currentRoute) { + // We should only need to send a safe set of fields on the route + // object. + // This is not to hide what's inside the route object, but to show + // these are the public APIs + var routePublicApi = _.pick(currentRoute, 'name', 'pathDef', 'path'); + var omittingOptionFields = [ + 'triggersEnter', 'triggersExit', 'action', 'subscriptions', 'name' + ]; + routePublicApi.options = _.omit(currentRoute.options, omittingOptionFields); + + _.each(this._onRouteCallbacks, function(cb) { + cb(routePublicApi); + }); +}; + +Router.prototype._page = page; +Router.prototype._qs = qs; diff --git a/packages/kadira-flow-router/client/triggers.js b/packages/kadira-flow-router/client/triggers.js new file mode 100644 index 00000000..7733332c --- /dev/null +++ b/packages/kadira-flow-router/client/triggers.js @@ -0,0 +1,112 @@ +// a set of utility functions for triggers + +Triggers = {}; + +// Apply filters for a set of triggers +// @triggers - a set of triggers +// @filter - filter with array fileds with `only` and `except` +// support only either `only` or `except`, but not both +Triggers.applyFilters = function(triggers, filter) { + if(!(triggers instanceof Array)) { + triggers = [triggers]; + } + + if(!filter) { + return triggers; + } + + if(filter.only && filter.except) { + throw new Error("Triggers don't support only and except filters at once"); + } + + if(filter.only && !(filter.only instanceof Array)) { + throw new Error("only filters needs to be an array"); + } + + if(filter.except && !(filter.except instanceof Array)) { + throw new Error("except filters needs to be an array"); + } + + if(filter.only) { + return Triggers.createRouteBoundTriggers(triggers, filter.only); + } + + if(filter.except) { + return Triggers.createRouteBoundTriggers(triggers, filter.except, true); + } + + throw new Error("Provided a filter but not supported"); +}; + +// create triggers by bounding them to a set of route names +// @triggers - a set of triggers +// @names - list of route names to be bound (trigger runs only for these names) +// @negate - negate the result (triggers won't run for above names) +Triggers.createRouteBoundTriggers = function(triggers, names, negate) { + var namesMap = {}; + _.each(names, function(name) { + namesMap[name] = true; + }); + + var filteredTriggers = _.map(triggers, function(originalTrigger) { + var modifiedTrigger = function(context, next) { + var routeName = context.route.name; + var matched = (namesMap[routeName])? 1: -1; + matched = (negate)? matched * -1 : matched; + + if(matched === 1) { + originalTrigger(context, next); + } + }; + return modifiedTrigger; + }); + + return filteredTriggers; +}; + +// run triggers and abort if redirected or callback stopped +// @triggers - a set of triggers +// @context - context we need to pass (it must have the route) +// @redirectFn - function which used to redirect +// @after - called after if only all the triggers runs +Triggers.runTriggers = function(triggers, context, redirectFn, after) { + var abort = false; + var inCurrentLoop = true; + var alreadyRedirected = false; + + for(var lc=0; lc 0)? firstRegexpChar: undefined); + // remove +?* + key = key.replace(/[\+\*\?]+/g, ""); + + return fields[key] || ""; + }); + + path = path.replace(/\/\/+/g, "/"); // Replace multiple slashes with single slash + + // remove trailing slash + // but keep the root slash if it's the only one + path = path.match(/^\/{1}$/) ? path: path.replace(/\/$/, ""); + + var strQueryParams = Qs.stringify(queryParams || {}); + if(strQueryParams) { + path += "?" + strQueryParams; + } + + return path; +}; + +Router.prototype.onRouteRegister = function(cb) { + this._onRouteCallbacks.push(cb); +}; + +Router.prototype._triggerRouteRegister = function(currentRoute) { + // We should only need to send a safe set of fields on the route + // object. + // This is not to hide what's inside the route object, but to show + // these are the public APIs + var routePublicApi = _.pick(currentRoute, 'name', 'pathDef', 'path'); + var omittingOptionFields = [ + 'triggersEnter', 'triggersExit', 'action', 'subscriptions', 'name' + ]; + routePublicApi.options = _.omit(currentRoute.options, omittingOptionFields); + + _.each(this._onRouteCallbacks, function(cb) { + cb(routePublicApi); + }); +}; + + +Router.prototype.go = function() { + // client only +}; + + +Router.prototype.current = function() { + // client only +}; + + +Router.prototype.triggers = { + enter: function() { + // client only + }, + exit: function() { + // client only + } +}; + +Router.prototype.middleware = function() { + // client only +}; + + +Router.prototype.getState = function() { + // client only +}; + + +Router.prototype.getAllStates = function() { + // client only +}; + + +Router.prototype.setState = function() { + // client only +}; + + +Router.prototype.removeState = function() { + // client only +}; + + +Router.prototype.clearStates = function() { + // client only +}; + + +Router.prototype.ready = function() { + // client only +}; + + +Router.prototype.initialize = function() { + // client only +}; + +Router.prototype.wait = function() { + // client only +}; diff --git a/packages/kadira-flow-router/test/client/_helpers.js b/packages/kadira-flow-router/test/client/_helpers.js new file mode 100644 index 00000000..94376f00 --- /dev/null +++ b/packages/kadira-flow-router/test/client/_helpers.js @@ -0,0 +1,10 @@ +GetSub = function (name) { + for(var id in Meteor.connection._subscriptions) { + var sub = Meteor.connection._subscriptions[id]; + if(name === sub.name) { + return sub; + } + } +}; + +FlowRouter.route('/'); diff --git a/packages/kadira-flow-router/test/client/group.spec.js b/packages/kadira-flow-router/test/client/group.spec.js new file mode 100644 index 00000000..06e793ba --- /dev/null +++ b/packages/kadira-flow-router/test/client/group.spec.js @@ -0,0 +1,113 @@ +Tinytest.add('Client - Group - validate path definition', function (test, next) { + // path & prefix must start with '/' + test.throws(function() { + new Group(null, {prefix: Random.id()}); + }); + + var group = FlowRouter.group({prefix: '/' + Random.id()}); + + test.throws(function() { + group.route(Random.id()); + }); +}); + +Tinytest.addAsync('Client - Group - define and go to route with prefix', function (test, next) { + var prefix = Random.id(); + var rand = Random.id(); + var rendered = 0; + + var group = FlowRouter.group({prefix: '/' + prefix}); + + group.route('/' + rand, { + action: function(_params) { + rendered++; + } + }); + + FlowRouter.go('/' + prefix + '/' + rand); + + setTimeout(function() { + test.equal(rendered, 1); + setTimeout(next, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Group - define and go to route without prefix', function (test, next) { + var rand = Random.id(); + var rendered = 0; + + var group = FlowRouter.group(); + + group.route('/' + rand, { + action: function(_params) { + rendered++; + } + }); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(rendered, 1); + setTimeout(next, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Group - subscribe', function (test, next) { + var rand = Random.id(); + + var group = FlowRouter.group({ + subscriptions: function (params) { + this.register('baz', Meteor.subscribe('baz')); + } + }); + + group.route('/' + rand); + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!!GetSub('baz')); + next(); + }, 100); +}); + + +Tinytest.addAsync('Client - Group - set and retrieve group name', function (test, next) { + var rand = Random.id(); + var name = Random.id(); + + var group = FlowRouter.group({ + name: name + }); + + group.route('/' + rand); + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(FlowRouter.current().route.group.name === name); + next(); + }, 100); +}); + +Tinytest.add('Client - Group - expose group options on a route', function (test) { + var pathDef = "/" + Random.id(); + var name = Random.id(); + var groupName = Random.id(); + var data = {aa: 10}; + var layout = 'blah'; + + var group = FlowRouter.group({ + name: groupName, + prefix: '/admin', + layout: layout, + someData: data + }); + + group.route(pathDef, { + name: name + }); + + var route = FlowRouter._routesMap[name]; + + test.equal(route.group.options.someData, data); + test.equal(route.group.options.layout, layout); +}); diff --git a/packages/kadira-flow-router/test/client/loader.spec.js b/packages/kadira-flow-router/test/client/loader.spec.js new file mode 100644 index 00000000..091c2e02 --- /dev/null +++ b/packages/kadira-flow-router/test/client/loader.spec.js @@ -0,0 +1,17 @@ +Router = FlowRouter.Router; + + +Tinytest.add('Client - import page.js', function (test) { + test.isTrue(!!Router.prototype._page); + test.isFalse(!!window.page); +}); + + +Tinytest.add('Client - import query.js', function (test) { + test.isTrue(!!Router.prototype._qs); +}); + + +Tinytest.add('Client - create FlowRouter', function (test) { + test.isTrue(!!FlowRouter); +}); diff --git a/packages/kadira-flow-router/test/client/route.reactivity.spec.js b/packages/kadira-flow-router/test/client/route.reactivity.spec.js new file mode 100644 index 00000000..c6c44183 --- /dev/null +++ b/packages/kadira-flow-router/test/client/route.reactivity.spec.js @@ -0,0 +1,158 @@ +Route = FlowRouter.Route; + + +Tinytest.addAsync('Client - Route - Reactivity - getParam', function (test, done) { + var r = new Route(); + Tracker.autorun(function(c) { + var param = r.getParam("id"); + if(param) { + test.equal(param, "hello"); + c.stop(); + Meteor.defer(done); + } + }); + + setTimeout(function() { + var context = { + params: {id: "hello"}, + queryParams: {} + }; + r.registerRouteChange(context); + }, 10); +}); + +Tinytest.addAsync('Client - Route - Reactivity - getParam on route close', function (test, done) { + var r = new Route(); + var closeTriggered = false; + Tracker.autorun(function(c) { + var param = r.getParam("id"); + if(closeTriggered) { + test.equal(param, undefined); + c.stop(); + Meteor.defer(done); + } + }); + + setTimeout(function() { + closeTriggered = true; + r.registerRouteClose(); + }, 10); +}); + +Tinytest.addAsync('Client - Route - Reactivity - getQueryParam', function (test, done) { + var r = new Route(); + Tracker.autorun(function(c) { + var param = r.getQueryParam("id"); + if(param) { + test.equal(param, "hello"); + c.stop(); + Meteor.defer(done); + } + }); + + setTimeout(function() { + var context = { + params: {}, + queryParams: {id: "hello"} + }; + r.registerRouteChange(context); + }, 10); +}); + +Tinytest.addAsync('Client - Route - Reactivity - getQueryParam on route close', function (test, done) { + var r = new Route(); + var closeTriggered = false; + Tracker.autorun(function(c) { + var param = r.getQueryParam("id"); + if(closeTriggered) { + test.equal(param, undefined); + c.stop(); + Meteor.defer(done); + } + }); + + setTimeout(function() { + closeTriggered = true; + r.registerRouteClose(); + }, 10); +}); + +Tinytest.addAsync('Client - Route - Reactivity - getRouteName rerun when route closed', function (test, done) { + var r = new Route(); + r.name = "my-route"; + var closeTriggered = false; + + Tracker.autorun(function(c) { + var name = r.getRouteName(); + test.equal(name, r.name); + + if(closeTriggered) { + c.stop(); + Meteor.defer(done); + } + }); + + setTimeout(function() { + closeTriggered = true; + r.registerRouteClose(); + }, 10); +}); + +Tinytest.addAsync('Client - Route - Reactivity - watchPathChange when routeChange', function (test, done) { + var r = new Route(); + var pathChangeCounts = 0; + + var c = Tracker.autorun(function() { + r.watchPathChange(); + pathChangeCounts++; + }); + + var context = { + params: {}, + queryParams: {} + }; + + setTimeout(function() { + r.registerRouteChange(context); + setTimeout(checkAfterNormalRouteChange, 50); + }, 10); + + function checkAfterNormalRouteChange() { + test.equal(pathChangeCounts, 2); + var lastRouteChange = true; + r.registerRouteChange(context, lastRouteChange); + setTimeout(checkAfterLastRouteChange, 10); + } + + function checkAfterLastRouteChange() { + test.equal(pathChangeCounts, 2); + c.stop(); + Meteor.defer(done); + } +}); + +Tinytest.addAsync('Client - Route - Reactivity - watchPathChange when routeClose', function (test, done) { + var r = new Route(); + var pathChangeCounts = 0; + + var c = Tracker.autorun(function() { + r.watchPathChange(); + pathChangeCounts++; + }); + + var context = { + params: {}, + queryParams: {} + }; + + setTimeout(function() { + r.registerRouteClose(); + setTimeout(checkAfterRouteClose, 10); + }, 10); + + function checkAfterRouteClose() { + test.equal(pathChangeCounts, 2); + c.stop(); + Meteor.defer(done); + } +}); \ No newline at end of file diff --git a/packages/kadira-flow-router/test/client/router.core.spec.js b/packages/kadira-flow-router/test/client/router.core.spec.js new file mode 100644 index 00000000..160c9112 --- /dev/null +++ b/packages/kadira-flow-router/test/client/router.core.spec.js @@ -0,0 +1,632 @@ +Router = FlowRouter.Router; + +Tinytest.addAsync('Client - Router - define and go to route', function (test, next) { + var rand = Random.id(); + var rendered = 0; + + FlowRouter.route('/' + rand, { + action: function(_params) { + rendered++; + } + }); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(rendered, 1); + setTimeout(next, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Router - define and go to route with fields', +function (test, next) { + var rand = Random.id(); + var pathDef = "/" + rand + "/:key"; + var rendered = 0; + + FlowRouter.route(pathDef, { + action: function(params) { + test.equal(params.key, "abc +@%"); + rendered++; + } + }); + + FlowRouter.go(pathDef, {key: "abc +@%"}); + + setTimeout(function() { + test.equal(rendered, 1); + setTimeout(next, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Router - parse params and query', function (test, next) { + var rand = Random.id(); + var rendered = 0; + var params = null; + + FlowRouter.route('/' + rand + '/:foo', { + action: function(_params) { + rendered++; + params = _params; + } + }); + + FlowRouter.go('/' + rand + '/bar'); + + setTimeout(function() { + test.equal(rendered, 1); + test.equal(params.foo, 'bar'); + setTimeout(next, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Router - redirect using FlowRouter.go', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var paths = ['/' + rand2, '/' + rand]; + var done = false; + + FlowRouter.route(paths[0], { + action: function(_params) { + log.push(1); + FlowRouter.go(paths[1]); + } + }); + + FlowRouter.route(paths[1], { + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.go(paths[0]); + + setTimeout(function() { + test.equal(log, [1, 2]); + done = true; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - get current route path', function (test, next) { + var value = Random.id(); + var randomValue = Random.id(); + var pathDef = "/" + randomValue + '/:_id'; + var path = "/" + randomValue + "/" + value; + + var detectedValue = null; + + FlowRouter.route(pathDef, { + action: function(params) { + detectedValue = params._id; + } + }); + + FlowRouter.go(path); + + Meteor.setTimeout(function() { + test.equal(detectedValue, value); + test.equal(FlowRouter.current().path, path); + next(); + }, 50); +}); + +Tinytest.addAsync('Client - Router - subscribe to global subs', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand); + + FlowRouter.subscriptions = function (path) { + test.equal(path, '/' + rand); + this.register('baz', Meteor.subscribe('baz')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!!GetSub('baz')); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - setParams - generic', function (test, done) { + var randomKey = Random.id(); + var pathDef = "/" + randomKey + "/:cat/:id"; + var paramsList = []; + FlowRouter.route(pathDef, { + action: function(params) { + paramsList.push(params); + } + }); + + FlowRouter.go(pathDef, {cat: "meteor", id: "200"}); + setTimeout(function() { + // return done(); + var success = FlowRouter.setParams({id: "700"}); + test.isTrue(success); + setTimeout(validate, 50); + }, 50); + + function validate() { + test.equal(paramsList.length, 2); + test.equal(_.pick(paramsList[0], "id", "cat"), {cat: "meteor", id: "200"}); + test.equal(_.pick(paramsList[1], "id", "cat"), {cat: "meteor", id: "700"}); + done(); + } +}); + +Tinytest.addAsync('Client - Router - setParams - preserve query strings', function (test, done) { + var randomKey = Random.id(); + var pathDef = "/" + randomKey + "/:cat/:id"; + var paramsList = []; + var queryParamsList = []; + + FlowRouter.route(pathDef, { + action: function(params, queryParams) { + paramsList.push(params); + queryParamsList.push(queryParams); + } + }); + + FlowRouter.go(pathDef, {cat: "meteor", id: "200 +% / ad"}, {aa: "20 +%"}); + setTimeout(function() { + // return done(); + var success = FlowRouter.setParams({id: "700 +% / ad"}); + test.isTrue(success); + setTimeout(validate, 50); + }, 50); + + function validate() { + test.equal(paramsList.length, 2); + test.equal(queryParamsList.length, 2); + + test.equal(_.pick(paramsList[0], "id", "cat"), {cat: "meteor", id: "200 +% / ad"}); + test.equal(_.pick(paramsList[1], "id", "cat"), {cat: "meteor", id: "700 +% / ad"}); + test.equal(queryParamsList, [{aa: "20 +%"}, {aa: "20 +%"}]); + done(); + } +}); + +Tinytest.add('Client - Router - setParams - no route selected', function (test) { + var originalRoute = FlowRouter._current.route; + FlowRouter._current.route = undefined; + var success = FlowRouter.setParams({id: "800"}); + test.isFalse(success); + FlowRouter._current.route = originalRoute; +}); + +Tinytest.addAsync('Client - Router - setQueryParams - using check', function (test, done) { + var randomKey = Random.id(); + var pathDef = "/" + randomKey + ""; + var queryParamsList = []; + FlowRouter.route(pathDef, { + action: function(params, queryParams) { + queryParamsList.push(queryParams); + } + }); + + FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"}); + setTimeout(function() { + check(FlowRouter.current().queryParams, {cat: String, id: String}); + done(); + }, 50); +}); + +Tinytest.addAsync('Client - Router - setQueryParams - generic', function (test, done) { + var randomKey = Random.id(); + var pathDef = "/" + randomKey + ""; + var queryParamsList = []; + FlowRouter.route(pathDef, { + action: function(params, queryParams) { + queryParamsList.push(queryParams); + } + }); + + FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"}); + setTimeout(function() { + // return done(); + var success = FlowRouter.setQueryParams({id: "700"}); + test.isTrue(success); + setTimeout(validate, 50); + }, 50); + + function validate() { + test.equal(queryParamsList.length, 2); + test.equal(_.pick(queryParamsList[0], "id", "cat"), {cat: "meteor", id: "200"}); + test.equal(_.pick(queryParamsList[1], "id", "cat"), {cat: "meteor", id: "700"}); + done(); + } +}); + +Tinytest.addAsync('Client - Router - setQueryParams - remove query param null', function (test, done) { + var randomKey = Random.id(); + var pathDef = "/" + randomKey + ""; + var queryParamsList = []; + FlowRouter.route(pathDef, { + action: function(params, queryParams) { + queryParamsList.push(queryParams); + } + }); + + FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"}); + setTimeout(function() { + var success = FlowRouter.setQueryParams({id: "700", cat: null}); + test.isTrue(success); + setTimeout(validate, 50); + }, 50); + + function validate() { + test.equal(queryParamsList.length, 2); + test.equal(_.pick(queryParamsList[0], "id", "cat"), {cat: "meteor", id: "200"}); + test.equal(queryParamsList[1], {id: "700"}); + done(); + } +}); + +Tinytest.addAsync('Client - Router - setQueryParams - remove query param undefined', function (test, done) { + var randomKey = Random.id(); + var pathDef = "/" + randomKey + ""; + var queryParamsList = []; + FlowRouter.route(pathDef, { + action: function(params, queryParams) { + queryParamsList.push(queryParams); + } + }); + + FlowRouter.go(pathDef, {}, {cat: "meteor", id: "200"}); + setTimeout(function() { + var success = FlowRouter.setQueryParams({id: "700", cat: undefined}); + test.isTrue(success); + setTimeout(validate, 50); + }, 50); + + function validate() { + test.equal(queryParamsList.length, 2); + test.equal(_.pick(queryParamsList[0], "id", "cat"), {cat: "meteor", id: "200"}); + test.equal(queryParamsList[1], {id: "700"}); + done(); + } +}); + +Tinytest.addAsync('Client - Router - setQueryParams - preserve params', function (test, done) { + var randomKey = Random.id(); + var pathDef = "/" + randomKey + "/:abc"; + var queryParamsList = []; + var paramsList = []; + FlowRouter.route(pathDef, { + action: function(params, queryParams) { + paramsList.push(params); + queryParamsList.push(queryParams); + } + }); + + FlowRouter.go(pathDef, {abc: "20"}, {cat: "meteor", id: "200"}); + setTimeout(function() { + // return done(); + var success = FlowRouter.setQueryParams({id: "700"}); + test.isTrue(success); + setTimeout(validate, 50); + }, 50); + + function validate() { + test.equal(queryParamsList.length, 2); + test.equal(queryParamsList, [ + {cat: "meteor", id: "200"}, {cat: "meteor", id: "700"} + ]); + + test.equal(paramsList.length, 2); + test.equal(_.pick(paramsList[0], "abc"), {abc: "20"}); + test.equal(_.pick(paramsList[1], "abc"), {abc: "20"}); + done(); + } +}); + +Tinytest.add('Client - Router - setQueryParams - no route selected', function (test) { + var originalRoute = FlowRouter._current.route; + FlowRouter._current.route = undefined; + var success = FlowRouter.setQueryParams({id: "800"}); + test.isFalse(success); + FlowRouter._current.route = originalRoute; +}); + +Tinytest.addAsync('Client - Router - notFound', function (test, done) { + var data = []; + FlowRouter.notFound = { + subscriptions: function() { + data.push("subscriptions"); + }, + action: function() { + data.push("action"); + } + }; + + FlowRouter.go("/" + Random.id()); + setTimeout(function() { + test.equal(data, ["subscriptions", "action"]); + done(); + }, 50); +}); + +Tinytest.addAsync('Client - Router - withReplaceState - enabled', +function (test, done) { + var pathDef = "/" + Random.id() + "/:id"; + var originalRedirect = FlowRouter._page.replace; + var callCount = 0; + FlowRouter._page.replace = function(path) { + callCount++; + originalRedirect.call(FlowRouter._page, path); + }; + + FlowRouter.route(pathDef, { + name: name, + action: function(params) { + test.equal(params.id, "awesome"); + test.equal(callCount, 1); + FlowRouter._page.replace = originalRedirect; + // We don't use Meteor.defer here since it carries + // Meteor.Environment vars too + // Which breaks our test below + setTimeout(done, 0); + } + }); + + FlowRouter.withReplaceState(function() { + FlowRouter.go(pathDef, {id: "awesome"}); + }); +}); + +Tinytest.addAsync('Client - Router - withReplaceState - disabled', +function (test, done) { + var pathDef = "/" + Random.id() + "/:id"; + var originalRedirect = FlowRouter._page.replace; + var callCount = 0; + FlowRouter._page.replace = function(path) { + callCount++; + originalRedirect.call(FlowRouter._page, path); + }; + + FlowRouter.route(pathDef, { + name: name, + action: function(params) { + test.equal(params.id, "awesome"); + test.equal(callCount, 0); + FlowRouter._page.replace = originalRedirect; + Meteor.defer(done); + } + }); + + FlowRouter.go(pathDef, {id: "awesome"}); +}); + +Tinytest.addAsync('Client - Router - withTrailingSlash - enabled', function (test, next) { + var rand = Random.id(); + var rendered = 0; + + FlowRouter.route('/' + rand, { + action: function(_params) { + rendered++; + } + }); + + FlowRouter.withTrailingSlash(function() { + FlowRouter.go('/' + rand); + }); + + setTimeout(function() { + test.equal(rendered, 1); + test.equal(_.last(location.href), '/'); + setTimeout(next, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Router - idempotent routing - action', +function (test, done) { + var rand = Random.id(); + var pathDef = "/" + rand; + var rendered = 0; + + FlowRouter.route(pathDef, { + action: function(params) { + rendered++; + } + }); + + FlowRouter.go(pathDef); + + Meteor.defer(function() { + FlowRouter.go(pathDef); + + Meteor.defer(function() { + test.equal(rendered, 1); + done(); + }); + }); +}); + +Tinytest.addAsync('Client - Router - idempotent routing - triggers', +function (test, next) { + var rand = Random.id(); + var pathDef = "/" + rand; + var runnedTriggers = 0; + var done = false; + + var triggerFns = [function(params) { + if (done) return; + + runnedTriggers++; + }]; + + FlowRouter.triggers.enter(triggerFns); + + FlowRouter.route(pathDef, { + triggersEnter: triggerFns, + triggersExit: triggerFns + }); + + FlowRouter.go(pathDef); + + FlowRouter.triggers.exit(triggerFns); + + Meteor.defer(function() { + FlowRouter.go(pathDef); + + Meteor.defer(function() { + test.equal(runnedTriggers, 2); + done = true; + next(); + }); + }); +}); + +Tinytest.addAsync('Client - Router - reload - action', +function (test, done) { + var rand = Random.id(); + var pathDef = "/" + rand; + var rendered = 0; + + FlowRouter.route(pathDef, { + action: function(params) { + rendered++; + } + }); + + FlowRouter.go(pathDef); + + Meteor.defer(function() { + FlowRouter.reload(); + + Meteor.defer(function() { + test.equal(rendered, 2); + done(); + }); + }); +}); + +Tinytest.addAsync('Client - Router - reload - triggers', +function (test, next) { + var rand = Random.id(); + var pathDef = "/" + rand; + var runnedTriggers = 0; + var done = false; + + var triggerFns = [function(params) { + if (done) return; + + runnedTriggers++; + }]; + + FlowRouter.triggers.enter(triggerFns); + + FlowRouter.route(pathDef, { + triggersEnter: triggerFns, + triggersExit: triggerFns + }); + + FlowRouter.go(pathDef); + + FlowRouter.triggers.exit(triggerFns); + + Meteor.defer(function() { + FlowRouter.reload(); + + Meteor.defer(function() { + test.equal(runnedTriggers, 6); + done = true; + next(); + }); + }); +}); + +Tinytest.addAsync( +'Client - Router - wait - before initialize', +function(test, done) { + FlowRouter._initialized = false; + FlowRouter.wait(); + test.equal(FlowRouter._askedToWait, true); + + FlowRouter._initialized = true; + FlowRouter._askedToWait = false; + done(); +}); + +Tinytest.addAsync( +'Client - Router - wait - after initialized', +function(test, done) { + try { + FlowRouter.wait(); + } catch(ex) { + test.isTrue(/can't wait/.test(ex.message)); + done(); + } +}); + +Tinytest.addAsync( +'Client - Router - initialize - after initialized', +function(test, done) { + try { + FlowRouter.initialize(); + } catch(ex) { + test.isTrue(/already initialized/.test(ex.message)); + done(); + } +}); + +Tinytest.addAsync( +'Client - Router - base path - url updated', +function(test, done) { + var simulatedBasePath = '/flow'; + var rand = Random.id(); + FlowRouter.route('/' + rand, { action: function() {} }); + + setBasePath(simulatedBasePath); + FlowRouter.go('/' + rand); + setTimeout(function() { + test.equal(location.pathname, simulatedBasePath + '/' + rand); + resetBasePath(); + done(); + }, 100); +}); + +Tinytest.addAsync( +'Client - Router - base path - route action called', +function(test, done) { + var simulatedBasePath = '/flow'; + var rand = Random.id(); + FlowRouter.route('/' + rand, { + action: function() { + resetBasePath(); + done(); + } + }); + + setBasePath(simulatedBasePath); + FlowRouter.go('/' + rand); +}); + +Tinytest.add( +'Client - Router - base path - path generation', +function(test, done) { + _.each(['/flow', '/flow/', 'flow/', 'flow'], function(simulatedBasePath) { + var rand = Random.id(); + setBasePath(simulatedBasePath); + test.equal(FlowRouter.path('/' + rand), '/flow/' + rand); + }); + resetBasePath(); +}); + + +function setBasePath(path) { + FlowRouter._initialized = false; + FlowRouter._basePath = path; + FlowRouter.initialize(); +} + +var defaultBasePath = FlowRouter._basePath; +function resetBasePath() { + setBasePath(defaultBasePath); +} + +function bind(obj, method) { + return function() { + obj[method].apply(obj, arguments); + }; +} diff --git a/packages/kadira-flow-router/test/client/router.reactivity.spec.js b/packages/kadira-flow-router/test/client/router.reactivity.spec.js new file mode 100644 index 00000000..b06deeda --- /dev/null +++ b/packages/kadira-flow-router/test/client/router.reactivity.spec.js @@ -0,0 +1,208 @@ +Tinytest.addAsync( +'Client - Router - Reactivity - detectChange only once', +function (test, done) { + var route = "/" + Random.id(); + var name = Random.id(); + FlowRouter.route(route, {name: name}); + + var ranCount = 0; + var pickedId = null; + var c = Tracker.autorun(function() { + ranCount++; + pickedId = FlowRouter.getQueryParam("id"); + if(pickedId) { + test.equal(pickedId, "hello"); + test.equal(ranCount, 2); + c.stop(); + Meteor.defer(done); + } + }); + + setTimeout(function() { + FlowRouter.go(name, {}, {id: "hello"}); + }, 2); +}); + +Tinytest.addAsync( +'Client - Router - Reactivity - detectChange in the action', +function (test, done) { + var route = "/" + Random.id(); + var name = Random.id(); + FlowRouter.route(route, { + name: name, + action: function() { + var id = FlowRouter.getQueryParam("id"); + test.equal(id, "hello"); + Meteor.defer(done); + } + }); + + setTimeout(function() { + FlowRouter.go(name, {}, {id: "hello"}); + }, 2); +}); + +Tinytest.addAsync( +'Client - Router - Reactivity - detect prev routeChange after new action', +function (test, done) { + var route1 = "/" + Random.id(); + var name1 = Random.id(); + var pickedName1 = null; + + var route2 = "/" + Random.id(); + var name2 = Random.id(); + var pickedName2 = Random.id(); + + FlowRouter.route(route1, { + name: name1, + action: function() { + Tracker.autorun(function(c) { + pickedName1 = FlowRouter.getRouteName(); + if(pickedName1 == name2) { + test.equal(pickedName1, pickedName2); + c.stop(); + Meteor.defer(done); + } + }); + } + }); + + FlowRouter.route(route2, { + name: name2, + action: function() { + pickedName2 = FlowRouter.getRouteName(); + test.equal(pickedName1, name1); + test.equal(pickedName2, name2); + } + }); + + FlowRouter.go(name1); + Meteor.setTimeout(function() { + FlowRouter.go(name2); + }, 10); +}); + +Tinytest.addAsync( +'Client - Router - Reactivity - defer watchPathChange until new route rendered', +function(test, done) { + var route1 = "/" + Random.id(); + var name1 = Random.id(); + var pickedName1 = null; + + var route2 = "/" + Random.id(); + var name2 = Random.id(); + var pickedName2 = Random.id(); + + FlowRouter.route(route1, { + name: name1, + action: function() { + Tracker.autorun(function(c) { + FlowRouter.watchPathChange(); + pickedName1 = FlowRouter.current().route.name; + if(pickedName1 == name2) { + test.equal(pickedName1, pickedName2); + c.stop(); + Meteor.defer(done); + } + }); + } + }); + + FlowRouter.route(route2, { + name: name2, + action: function() { + pickedName2 = FlowRouter.current().route.name; + test.equal(pickedName1, name1); + test.equal(pickedName2, name2); + } + }); + + FlowRouter.go(name1); + Meteor.setTimeout(function() { + FlowRouter.go(name2); + }, 10); +}); + +Tinytest.addAsync( +'Client - Router - Reactivity - reactive changes and trigger redirects', +function(test, done) { + var name1 = Random.id(); + var route1 = "/" + name1; + FlowRouter.route(route1, { + name: name1 + }); + + var name2 = Random.id(); + var route2 = "/" + name2; + FlowRouter.route(route2, { + name: name2, + triggersEnter: [function(context, redirect) { + redirect(name3); + }] + }); + + + var name3 = Random.id(); + var route3 = "/" + name3; + FlowRouter.route(route3, { + name: name3 + }); + + var routeNamesFired = []; + FlowRouter.go(name1); + + var c = null; + setTimeout(function() { + c = Tracker.autorun(function(c) { + routeNamesFired.push(FlowRouter.getRouteName()); + }); + FlowRouter.go(name2); + }, 50); + + setTimeout(function() { + c.stop(); + test.equal(routeNamesFired, [name1, name3]); + Meteor.defer(done); + }, 250); +}); + +Tinytest.addAsync( +'Client - Router - Reactivity - watchPathChange for every route change', +function(test, done) { + var route1 = "/" + Random.id(); + var name1 = Random.id(); + var pickedName1 = null; + + var route2 = "/" + Random.id(); + var name2 = Random.id(); + var pickedName2 = Random.id(); + + FlowRouter.route(route1, { + name: name1 + }); + + FlowRouter.route(route2, { + name: name2 + }); + + var ids = []; + var c = Tracker.autorun(function() { + FlowRouter.watchPathChange(); + ids.push(FlowRouter.current().queryParams['id']); + }); + + FlowRouter.go(name1, {}, {id: "one"}); + Meteor.setTimeout(function() { + FlowRouter.go(name1, {}, {id: "two"}); + }, 10); + + Meteor.setTimeout(function() { + FlowRouter.go(name2, {}, {id: "three"}); + }, 20); + + Meteor.setTimeout(function() { + test.equal(ids, [undefined, "one", "two", "three"]); + c.stop(); + done(); + }, 40); +}); \ No newline at end of file diff --git a/packages/kadira-flow-router/test/client/router.subs_ready.spec.js b/packages/kadira-flow-router/test/client/router.subs_ready.spec.js new file mode 100644 index 00000000..8a20077a --- /dev/null +++ b/packages/kadira-flow-router/test/client/router.subs_ready.spec.js @@ -0,0 +1,225 @@ +Tinytest.addAsync('Client - Router - subsReady - with no args - all subscriptions ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('bar', Meteor.subscribe('bar')); + this.register('foo', Meteor.subscribe('foo')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('baz', Meteor.subscribe('baz')); + }; + + FlowRouter.go('/' + rand); + + Tracker.autorun(function(c) { + if(FlowRouter.subsReady()) { + FlowRouter.subscriptions = Function.prototype; + next(); + c.stop(); + } + }); +}); + +Tinytest.addAsync('Client - Router - subsReady - with no args - all subscriptions does not ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('fooNotReady', Meteor.subscribe('fooNotReady')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('bazNotReady', Meteor.subscribe('bazNotReady')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!FlowRouter.subsReady()); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - with no args - global subscriptions does not ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('bar', Meteor.subscribe('bar')); + this.register('foo', Meteor.subscribe('foo')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('bazNotReady', Meteor.subscribe('bazNotReady')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!FlowRouter.subsReady()); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - with no args - current subscriptions does not ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('bar', Meteor.subscribe('bar')); + this.register('fooNotReady', Meteor.subscribe('fooNotReady')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('baz', Meteor.subscribe('baz')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!FlowRouter.subsReady()); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - with args - all subscriptions ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('bar', Meteor.subscribe('bar')); + this.register('foo', Meteor.subscribe('foo')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('baz', Meteor.subscribe('baz')); + }; + + FlowRouter.go('/' + rand); + Tracker.autorun(function(c) { + if(FlowRouter.subsReady('foo', 'baz')) { + FlowRouter.subscriptions = Function.prototype; + next(); + c.stop(); + } + }); +}); + +Tinytest.addAsync('Client - Router - subsReady - with args - all subscriptions does not ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('fooNotReady', Meteor.subscribe('fooNotReady')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('bazNotReady', Meteor.subscribe('bazNotReady')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!FlowRouter.subsReady('fooNotReady', 'bazNotReady')); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - with args - global subscriptions does not ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('bar', Meteor.subscribe('bar')); + this.register('foo', Meteor.subscribe('foo')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('bazNotReady', Meteor.subscribe('bazNotReady')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!FlowRouter.subsReady('foo', 'bazNotReady')); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - with args - current subscriptions does not ready', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('bar', Meteor.subscribe('bar')); + this.register('fooNotReady', Meteor.subscribe('fooNotReady')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('baz', Meteor.subscribe('baz')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!FlowRouter.subsReady('fooNotReady', 'baz')); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - with args - subscribe with wrong name', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + this.register('bar', Meteor.subscribe('bar')); + } + }); + + FlowRouter.subscriptions = function () { + this.register('baz', Meteor.subscribe('baz')); + }; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(!FlowRouter.subsReady('baz', 'xxx', 'baz')); + FlowRouter.subscriptions = Function.prototype; + next(); + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - with args - same route two different subs', function (test, next) { + var rand = Random.id(); + var count = 0; + FlowRouter.route('/' + rand, { + subscriptions: function(params) { + if(++count == 1) { + this.register('not-exisitng', Meteor.subscribe('not-exisitng')); + } + } + }); + + FlowRouter.subscriptions = Function.prototype; + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isFalse(FlowRouter.subsReady()); + FlowRouter.go('/' + rand, {}, {param: "111"}); + setTimeout(function() { + test.isTrue(FlowRouter.subsReady()); + next(); + }, 100) + }, 100); +}); + +Tinytest.addAsync('Client - Router - subsReady - no subscriptions - simple', function (test, next) { + var rand = Random.id(); + FlowRouter.route('/' + rand, {}); + FlowRouter.subscriptions = Function.prototype; + + FlowRouter.go('/' + rand); + setTimeout(function() { + test.isTrue(FlowRouter.subsReady()); + next(); + }, 100); +}); \ No newline at end of file diff --git a/packages/kadira-flow-router/test/client/trigger.spec.js b/packages/kadira-flow-router/test/client/trigger.spec.js new file mode 100644 index 00000000..319c6bd2 --- /dev/null +++ b/packages/kadira-flow-router/test/client/trigger.spec.js @@ -0,0 +1,570 @@ +Tinytest.addAsync('Client - Triggers - global enter triggers', function(test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var paths = ['/' + rand2, '/' + rand]; + var done = false; + + FlowRouter.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.route('/' + rand2, { + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.triggers.enter([function(context) { + if(done) return; + test.equal(context.path, paths.pop()); + log.push(0); + }]); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [0, 1, 0, 2]); + done = true; + setTimeout(next, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - global enter triggers with "only"', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var done = false; + + FlowRouter.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.route('/' + rand2, { + name: 'foo', + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.triggers.enter([function(context) { + if(done) return; + test.equal(context.path, '/' + rand2); + log.push(8); + }], {only: ['foo']}); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [1, 8, 2]); + done = true; + setTimeout(next, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - global enter triggers with "except"', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var done = false; + + FlowRouter.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.route('/' + rand2, { + name: 'foo', + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.triggers.enter([function(context) { + if(done) return; + test.equal(context.path, '/' + rand); + log.push(8); + }], {except: ['foo']}); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [8, 1, 2]); + done = true; + setTimeout(next, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - global exit triggers', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var done =false; + + FlowRouter.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.route('/' + rand2, { + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.go('/' + rand); + + FlowRouter.triggers.exit([function(context) { + if(done) return; + test.equal(context.path, '/' + rand); + log.push(0); + }]); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [1, 0, 2]); + done = true; + setTimeout(next, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - global exit triggers with "only"', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var done = false; + + FlowRouter.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.route('/' + rand2, { + name: 'foo', + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.triggers.exit([function(context) { + if(done) return; + test.equal(context.path, '/' + rand2); + log.push(8); + }], {only: ['foo']}); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(log, [1, 2, 8, 1]); + done = true; + setTimeout(next, 100); + }, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - global exit triggers with "except"', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var done = false; + + FlowRouter.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.route('/' + rand2, { + name: 'foo', + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.go('/' + rand); + + FlowRouter.triggers.exit([function(context) { + if(done) return; + test.equal(context.path, '/' + rand); + log.push(9); + }], {except: ['foo']}); + + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(log, [1, 9, 2, 1]); + done = true; + setTimeout(next, 100); + }, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - route enter triggers', function (test, next) { + var rand = Random.id(); + var log = []; + + var triggerFn = function (context) { + test.equal(context.path, '/' + rand); + log.push(5); + }; + + FlowRouter.route('/' + rand, { + triggersEnter: [triggerFn], + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(log, [5, 1]); + setTimeout(next, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - router exit triggers', function (test, next) { + var rand = Random.id(); + var log = []; + + var triggerFn = function (context) { + test.equal(context.path, '/' + rand); + log.push(6); + }; + + FlowRouter.route('/' + rand, { + triggersExit: [triggerFn], + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + Random.id()); + + setTimeout(function() { + test.equal(log, [1, 6]); + setTimeout(next, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - group enter triggers', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var paths = ['/' + rand2, '/' + rand]; + + var triggerFn = function (context) { + test.equal(context.path, paths.pop()); + log.push(3); + }; + + var group = FlowRouter.group({ + triggersEnter: [triggerFn] + }); + + group.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + group.route('/' + rand2, { + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [3, 1, 3, 2]); + setTimeout(next, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - group exit triggers', function (test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + + var triggerFn = function (context) { + log.push(4); + }; + + var group = FlowRouter.group({ + triggersExit: [triggerFn] + }); + + group.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + group.route('/' + rand2, { + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [1, 4, 2]); + setTimeout(next, 100); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - redirect from enter', function(test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + + FlowRouter.route('/' + rand, { + triggersEnter: [function(context, redirect) { + redirect("/" + rand2); + }, function() { + throw new Error("should not execute this trigger"); + }], + action: function(_params) { + log.push(1); + }, + name: rand + }); + + FlowRouter.route('/' + rand2, { + action: function(_params) { + log.push(2); + }, + name: rand2 + }); + + FlowRouter.go('/'); + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(log, [2]); + next(); + }, 300); +}); + +Tinytest.addAsync('Client - Triggers - redirect by routeName', function(test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + + FlowRouter.route('/' + rand, { + name: rand, + triggersEnter: [function(context, redirect) { + redirect(rand2, null, {aa: "bb"}); + }, function() { + throw new Error("should not execute this trigger"); + }], + action: function(_params) { + log.push(1); + }, + name: rand + }); + + FlowRouter.route('/' + rand2, { + name: rand2, + action: function(_params, queryParams) { + log.push(2); + test.equal(queryParams, {aa: "bb"}); + }, + name: rand2 + }); + + FlowRouter.go('/'); + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(log, [2]); + next(); + }, 300); +}); + +Tinytest.addAsync('Client - Triggers - redirect from exit', function(test, next) { + var rand = Random.id(), rand2 = Random.id(), rand3 = Random.id(); + var log = []; + + FlowRouter.route('/' + rand, { + action: function() { + log.push(1); + }, + triggersExit: [ + function(context, redirect) { + redirect('/' + rand3); + }, + function() { + throw new Error("should not call this trigger"); + } + ] + }); + + FlowRouter.route('/' + rand2, { + action: function() { + log.push(2); + } + }); + + FlowRouter.route('/' + rand3, { + action: function() { + log.push(3); + } + }); + + FlowRouter.go('/' + rand); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [1, 3]); + next(); + }, 100); + }, 100); +}); + +Tinytest.addAsync('Client - Triggers - redirect to external URL fails', function(test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + + // testing "http://" URLs + FlowRouter.route('/' + rand, { + triggersEnter: [function(context, redirect) { + test.throws(function() { + redirect("http://example.com/") + }, "Redirects to URLs outside of the app are not supported") + }], + action: function(_params) { + log.push(1); + }, + name: rand + }); + + // testing "https://" URLs + FlowRouter.route('/' + rand2, { + triggersEnter: [function(context, redirect) { + test.throws(function() { + redirect("https://example.com/") + }) + }], + action: function(_params) { + log.push(2); + }, + name: rand2 + }); + + FlowRouter.go('/'); + FlowRouter.go('/' + rand); + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, []); + next(); + }, 300); +}); + +Tinytest.addAsync('Client - Triggers - stop callback from enter', function(test, next) { + var rand = Random.id(); + var log = []; + + FlowRouter.route('/' + rand, { + triggersEnter: [function(context, redirect, stop) { + log.push(10); + stop(); + }, function() { + throw new Error("should not execute this trigger"); + }], + action: function(_params) { + throw new Error("should not execute the action"); + } + }); + + FlowRouter.go('/'); + FlowRouter.go('/' + rand); + + setTimeout(function() { + test.equal(log, [10]); + next(); + }, 100); +}); + +Tinytest.addAsync( +'Client - Triggers - invalidate inside an autorun', +function(test, next) { + var rand = Random.id(), rand2 = Random.id(); + var log = []; + var paths = ['/' + rand2, '/' + rand]; + var done = false; + + FlowRouter.route('/' + rand, { + action: function(_params) { + log.push(1); + } + }); + + FlowRouter.route('/' + rand2, { + action: function(_params) { + log.push(2); + } + }); + + FlowRouter.triggers.enter([function(context) { + if(done) return; + test.equal(context.path, paths.pop()); + log.push(0); + }]); + + Tracker.autorun(function(c) { + FlowRouter.go('/' + rand); + }); + + setTimeout(function() { + FlowRouter.go('/' + rand2); + + setTimeout(function() { + test.equal(log, [0, 1, 0, 2]); + done = true; + setTimeout(next, 100); + }, 100); + }, 100); +}); diff --git a/packages/kadira-flow-router/test/client/triggers.js b/packages/kadira-flow-router/test/client/triggers.js new file mode 100644 index 00000000..7eb9a99c --- /dev/null +++ b/packages/kadira-flow-router/test/client/triggers.js @@ -0,0 +1,297 @@ +Tinytest.addAsync( +'Triggers - runTriggers - run all and after', +function(test, done) { + var store = []; + var triggers = MakeTriggers(2, store); + Triggers.runTriggers(triggers, null, null, function() { + test.equal(store, [0, 1]); + done(); + }); +}); + +Tinytest.addAsync( +'Triggers - runTriggers - redirect with url', +function(test, done) { + var store = []; + var url = "http://google.com"; + var triggers = MakeTriggers(2, store); + triggers.splice(1, 0, function(context, redirect) { + redirect(url); + }); + + Triggers.runTriggers(triggers, null, function(u) { + test.equal(store, [0]); + test.equal(u, url); + done(); + }, null); +}); + +Tinytest.addAsync( +'Triggers - runTriggers - redirect without url', +function(test, done) { + var store = []; + var url = "http://google.com"; + var triggers = MakeTriggers(2, store); + triggers.splice(1, 0, function(context, redirect) { + try { + redirect(); + } catch(ex) { + test.isTrue(/requires an URL/.test(ex.message)); + test.equal(store, [0]); + done(); + } + }); + + Triggers.runTriggers(triggers, null, null, null); +}); + +Tinytest.addAsync( +'Triggers - runTriggers - redirect in a different event loop', +function(test, done) { + var store = []; + var url = "http://google.com"; + var triggers = MakeTriggers(2, store); + var doneCalled = false; + + triggers.splice(1, 0, function(context, redirect) { + setTimeout(function() { + try { + redirect(url); + } catch(ex) { + test.isTrue(/sync/.test(ex.message)); + test.equal(store, [0, 1]); + test.isTrue(doneCalled); + done(); + } + }, 0); + }); + + Triggers.runTriggers(triggers, null, null, function() { + doneCalled = true; + }); +}); + +Tinytest.addAsync( +'Triggers - runTriggers - redirect called multiple times', +function(test, done) { + var store = []; + var url = "http://google.com"; + var triggers = MakeTriggers(2, store); + var redirectCalled = false; + + triggers.splice(1, 0, function(context, redirect) { + redirect(url); + try { + redirect(url); + } catch(ex) { + test.isTrue(/already redirected/.test(ex.message)); + test.equal(store, [0]); + test.isTrue(redirectCalled); + done(); + } + }); + + Triggers.runTriggers(triggers, null, function() { + redirectCalled = true; + }, null); +}); + +Tinytest.addAsync( +'Triggers - runTriggers - stop callback', +function(test, done) { + var store = []; + var triggers = MakeTriggers(2, store); + triggers.splice(1, 0, function(context, redirect, stop) { + stop(); + }); + + Triggers.runTriggers(triggers, null, null, function() { + store.push(2); + }); + + test.equal(store, [0]); + done(); +}); + + +Tinytest.addAsync( +'Triggers - runTriggers - get context', +function(test, done) { + var context = {}; + var trigger = function(c) { + test.equal(c, context); + done(); + }; + + Triggers.runTriggers([trigger], context, function() {}, function() {}); +}); + +Tinytest.addAsync( +'Triggers - createRouteBoundTriggers - matching trigger', +function(test, done) { + var context = {route: {name: "abc"}}; + var redirect = function() {}; + + var trigger = function(c, r) { + test.equal(c, context); + test.equal(r, redirect); + done(); + }; + + var triggers = Triggers.createRouteBoundTriggers([trigger], ["abc"]); + triggers[0](context, redirect); +}); + +Tinytest.addAsync( +'Triggers - createRouteBoundTriggers - multiple matching triggers', +function(test, done) { + var context = {route: {name: "abc"}}; + var redirect = function() {}; + var doneCount = 0; + + var trigger = function(c, r) { + test.equal(c, context); + test.equal(r, redirect); + doneCount++; + }; + + var triggers = Triggers.createRouteBoundTriggers([trigger, trigger], ["abc"]); + triggers[0](context, redirect); + triggers[1](context, redirect); + + test.equal(doneCount, 2); + done(); +}); + +Tinytest.addAsync( +'Triggers - createRouteBoundTriggers - no matching trigger', +function(test, done) { + var context = {route: {name: "some-other-route"}}; + var redirect = function() {}; + var doneCount = 0; + + var trigger = function(c, r) { + test.equal(c, context); + test.equal(r, redirect); + doneCount++; + }; + + var triggers = Triggers.createRouteBoundTriggers([trigger], ["abc"]); + triggers[0](context, redirect); + + test.equal(doneCount, 0); + done(); +}); + +Tinytest.addAsync( +'Triggers - createRouteBoundTriggers - negate logic', +function(test, done) { + var context = {route: {name: "some-other-route"}}; + var redirect = function() {}; + var doneCount = 0; + + var trigger = function(c, r) { + test.equal(c, context); + test.equal(r, redirect); + doneCount++; + }; + + var triggers = Triggers.createRouteBoundTriggers([trigger], ["abc"], true); + triggers[0](context, redirect); + + test.equal(doneCount, 1); + done(); +}); + +Tinytest.addAsync( +'Triggers - applyFilters - no filters', +function(test, done) { + var original = []; + test.equal(Triggers.applyFilters(original), original); + done(); +}); + +Tinytest.addAsync( +'Triggers - applyFilters - single trigger to array', +function(test, done) { + var original = function() {}; + test.equal(Triggers.applyFilters(original)[0], original); + done(); +}); + +Tinytest.addAsync( +'Triggers - applyFilters - only and except both', +function(test, done) { + var original = []; + try { + Triggers.applyFilters(original, {only: [], except: []}); + } catch(ex) { + test.isTrue(/only and except/.test(ex.message)); + done(); + } +}); + +Tinytest.addAsync( +'Triggers - applyFilters - only is not an array', +function(test, done) { + var original = []; + try { + Triggers.applyFilters(original, {only: "name"}); + } catch(ex) { + test.isTrue(/to be an array/.test(ex.message)); + done(); + } +}); + +Tinytest.addAsync( +'Triggers - applyFilters - except is not an array', +function(test, done) { + var original = []; + try { + Triggers.applyFilters(original, {except: "name"}); + } catch(ex) { + test.isTrue(/to be an array/.test(ex.message)); + done(); + } +}); + +Tinytest.addAsync( +'Triggers - applyFilters - unsupported filter', +function(test, done) { + var original = []; + try { + Triggers.applyFilters(original, {wowFilter: []}); + } catch(ex) { + test.isTrue(/not supported/.test(ex.message)); + done(); + } +}); + +Tinytest.addAsync( +'Triggers - applyFilters - just only filter', +function(test, done) { + var bounded = Triggers.applyFilters(done, {only: ["abc"]}); + bounded[0]({route: {name: "abc"}}); +}); + +Tinytest.addAsync( +'Triggers - applyFilters - just except filter', +function(test, done) { + var bounded = Triggers.applyFilters(done, {except: ["abc"]}); + bounded[0]({route: {name: "some-other"}}); +}); + +function MakeTriggers(count, store) { + var triggers = []; + + function addTrigger(no) { + triggers.push(function() { + store.push(no); + }); + } + + for(var lc=0; lc(.*)<\/script/)[1]; + return InjectData._decode(encodedData)['fast-render-data']; +} \ No newline at end of file diff --git a/packages/kadira-flow-router/test/server/plugins/fast_render.js b/packages/kadira-flow-router/test/server/plugins/fast_render.js new file mode 100644 index 00000000..1ec77866 --- /dev/null +++ b/packages/kadira-flow-router/test/server/plugins/fast_render.js @@ -0,0 +1,35 @@ +Tinytest.add('Server - Fast Render - fast render supported route', function (test) { + var expectedFastRenderCollData = [ + [{_id: "two", aa: 20}, {_id: "one", aa: 10}] + ]; + + var data = GetFRData('/the-fast-render-route'); + test.equal(data.collectionData['fast-render-coll'], expectedFastRenderCollData); +}); + +Tinytest.add('Server - Fast Render - fast render supported route with params', function (test) { + var expectedFastRenderCollData = [ + [{ + _id: "one", + params: {id: 'the-id'}, + queryParams: {aa: "20"} + }] + ]; + + var data = GetFRData('/the-fast-render-route-params/the-id?aa=20'); + test.equal(data.collectionData['fast-render-coll'], expectedFastRenderCollData); +}); + +Tinytest.add('Server - Fast Render - no fast render supported route', function (test) { + var data = GetFRData('/no-fast-render'); + test.equal(data.collectionData, {}); +}); + +Tinytest.add('Server - Fast Render - with group routes', function (test) { + var expectedFastRenderCollData = [ + [{_id: "two", aa: 20}, {_id: "one", aa: 10}] + ]; + + var data = GetFRData('/fr/have-fr'); + test.equal(data.collectionData['fast-render-coll'], expectedFastRenderCollData); +}); \ No newline at end of file diff --git a/packages/markdown/.gitignore b/packages/markdown/.gitignore new file mode 100755 index 00000000..677a6fc2 --- /dev/null +++ b/packages/markdown/.gitignore @@ -0,0 +1 @@ +.build* diff --git a/packages/markdown/README.md b/packages/markdown/README.md new file mode 100755 index 00000000..96c5725e --- /dev/null +++ b/packages/markdown/README.md @@ -0,0 +1,40 @@ +markdown +======== + +GitHub flavored markdown parser for Meteor based on marked.js newest version, updated by xet7. + +GFM tables and linebreaks are enabled by default. + + +Usage +----- + +Anywhere inside your template add markdown block and write markdown inside. + +Example: + +``` +{{#markdown}} + +...markdown text here... + +{{/markdown}} +``` + +That's it! + + +Thanks to: +---------- + +- Christopher Jeffrey for marked.js + +- Bozhao Yu for original meteor-markdown package (I just made this package compatible with Meteor 0.9+) + +- Bernhard Millauer - for contributions to this package + +- xet7 for updating to newest GFM package. + +License +------- +MIT diff --git a/packages/markdown/markdown.js b/packages/markdown/markdown.js new file mode 100755 index 00000000..bb015cc4 --- /dev/null +++ b/packages/markdown/markdown.js @@ -0,0 +1,9 @@ +var mark = marked; + +mark.setOptions({ + gfm: true, + tables: true, + breaks: true +}); + +Markdown = mark; diff --git a/packages/markdown/marked/.editorconfig b/packages/markdown/marked/.editorconfig new file mode 100644 index 00000000..97ff4e8a --- /dev/null +++ b/packages/markdown/marked/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*.{json,js}] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 + +[*.md, !test/*.md] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = tab +indent_size = 4 \ No newline at end of file diff --git a/packages/markdown/marked/.eslintignore b/packages/markdown/marked/.eslintignore new file mode 100644 index 00000000..121531af --- /dev/null +++ b/packages/markdown/marked/.eslintignore @@ -0,0 +1 @@ +*.min.js diff --git a/packages/markdown/marked/.eslintrc.json b/packages/markdown/marked/.eslintrc.json new file mode 100644 index 00000000..1800cb72 --- /dev/null +++ b/packages/markdown/marked/.eslintrc.json @@ -0,0 +1,29 @@ +{ + "extends": "standard", + "plugins": [ + "standard" + ], + "parserOptions": { "ecmaVersion": 5 }, + "rules": { + "semi": ["error", "always"], + "indent": ["warn", 2, { + "VariableDeclarator": { "var": 2 }, + "SwitchCase": 1, + "outerIIFEBody": 0 + }], + "space-before-function-paren": "off", + "object-curly-spacing": "off", + "operator-linebreak": ["error", "before", { "overrides": { "=": "after" } }], + "no-cond-assign": "off", + "no-useless-escape": "off", + "no-return-assign": "off", + "one-var": "off", + "no-control-regex": "off" + }, + "env": { + "node": true, + "browser": true, + "amd": true, + "jasmine": true + } +} diff --git a/packages/markdown/marked/.gitattributes b/packages/markdown/marked/.gitattributes new file mode 100644 index 00000000..8f2d8c35 --- /dev/null +++ b/packages/markdown/marked/.gitattributes @@ -0,0 +1,2 @@ +test/* linguist-vendored + diff --git a/packages/markdown/marked/.github/ISSUE_TEMPLATE.md b/packages/markdown/marked/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..9df84eaf --- /dev/null +++ b/packages/markdown/marked/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,42 @@ +**Marked version:** + +**Markdown flavor:** Markdown.pl|CommonMark|GitHub Flavored Markdown|n/a + + + + + +## Expectation + +**CommonMark Demo:** [demo](https://spec.commonmark.org/dingus/) + + + + +## Result + +**Marked Demo:** [demo](https://marked.js.org/demo/) + + + + +## What was attempted + + + + diff --git a/packages/markdown/marked/.github/ISSUE_TEMPLATE/Bug_report.md b/packages/markdown/marked/.github/ISSUE_TEMPLATE/Bug_report.md new file mode 100644 index 00000000..d8042b4d --- /dev/null +++ b/packages/markdown/marked/.github/ISSUE_TEMPLATE/Bug_report.md @@ -0,0 +1,27 @@ +--- +name: Bug report +about: Marked says it does this thing but does not + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: + + + + + + + +**Expected behavior** +A clear and concise description of what you expected to happen. diff --git a/packages/markdown/marked/.github/ISSUE_TEMPLATE/Feature_request.md b/packages/markdown/marked/.github/ISSUE_TEMPLATE/Feature_request.md new file mode 100644 index 00000000..745d4b43 --- /dev/null +++ b/packages/markdown/marked/.github/ISSUE_TEMPLATE/Feature_request.md @@ -0,0 +1,14 @@ +--- +name: Feature request +about: Marked doesn't do this thing and I think it should + +--- + +**Describe the feature** +A clear and concise description of what you would like. + +**Why is this feature necessary?** +A clear and concise description of why. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. diff --git a/packages/markdown/marked/.github/ISSUE_TEMPLATE/Proposal.md b/packages/markdown/marked/.github/ISSUE_TEMPLATE/Proposal.md new file mode 100644 index 00000000..aa94da3a --- /dev/null +++ b/packages/markdown/marked/.github/ISSUE_TEMPLATE/Proposal.md @@ -0,0 +1,11 @@ +--- +name: Proposal +about: Marked doesn't do this thing and I think it should + +--- + +**What pain point are you perceiving?.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. diff --git a/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE.md b/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..8274e607 --- /dev/null +++ b/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,53 @@ + + + +**Marked version:** + + + +**Markdown flavor:** Markdown.pl|CommonMark|GitHub Flavored Markdown|n/a + +## Description + +- Fixes #### (if fixing a known issue; otherwise, describe issue using the following format) + + + +## Contributor + +- [ ] Test(s) exist to ensure functionality and minimize regression (if no tests added, list tests covering this PR); or, +- [ ] no tests required for this PR. +- [ ] If submitting new feature, it has been documented in the appropriate places. + +## Committer + +In most cases, this should be a different person than the contributor. + +- [ ] Draft GitHub release notes have been updated. +- [ ] CI is green (no forced merge required). +- [ ] Merge PR diff --git a/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/badges.md b/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/badges.md new file mode 100644 index 00000000..2078243d --- /dev/null +++ b/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/badges.md @@ -0,0 +1,50 @@ +**@mention the contributor:** + +## Recommendation to: + +- [ ] Change user group +- [ ] Add a badge +- [ ] Remove a badge + + + +## As the one mentioned, I would like to: + +- [ ] accept the recommendation; or, +- [ ] graciously decline; or, +- [ ] dispute the recommendation + +within 30 days, if you have not indicated which option you are taking one of the following will happen: + +1. If adding a badge, we will assume you are graciously declining. +2. If removing a badge, we will assume you do not want to dispute the recommendation; therefore, the badge will be removed. + + + +Note: All committers must approve via review before merging, the disapproving committer can simply close the PR. \ No newline at end of file diff --git a/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/release.md b/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/release.md new file mode 100644 index 00000000..29cd7f2e --- /dev/null +++ b/packages/markdown/marked/.github/PULL_REQUEST_TEMPLATE/release.md @@ -0,0 +1,25 @@ +## Publisher + +- [ ] `$ npm version` has been run. +- [ ] Release notes in [draft GitHub release](https://github.com/markedjs/marked/releases) are up to date +- [ ] Release notes include which flavors and versions of Markdown are supported by this release +- [ ] Committer checklist is complete. +- [ ] Merge PR. +- [ ] Publish GitHub release using `master` with correct version number. +- [ ] `$ npm publish` has been run. +- [ ] Create draft GitHub release to prepare next release. + +Note: If merges to `master` occur after submitting this PR and before running `$ npm pubish` you should be able to + +1. pull from `upstream/master` (`git pull upstream master`) into the branch holding this version, +2. run `$ npm run build` to regenerate the `min` file, and +3. commit and push the updated changes. + +## Committer + +In most cases, this should be someone different than the publisher. + +- [ ] Version in `package.json` has been updated (see [PUBLISHING.md](https://github.com/markedjs/marked/blob/master/docs/PUBLISHING.md)). +- [ ] The `marked.min.js` has been updated; or, +- [ ] release does not change library. +- [ ] CI is green (no forced merge required). diff --git a/packages/markdown/marked/.gitignore b/packages/markdown/marked/.gitignore new file mode 100644 index 00000000..68ccf75d --- /dev/null +++ b/packages/markdown/marked/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +node_modules/ +test/compiled_tests diff --git a/packages/markdown/marked/.travis.yml b/packages/markdown/marked/.travis.yml new file mode 100644 index 00000000..8ff71da4 --- /dev/null +++ b/packages/markdown/marked/.travis.yml @@ -0,0 +1,46 @@ +language: node_js + +jobs: + fast_finish: true + allow_failures: + - stage: security scan 🔐 + + include: + - stage: unit tests 👩🏽‍💻 + script: npm run test:unit + node_js: lts/* + + - stage: spec tests 👩🏽‍💻 + script: npm run test:specs + node_js: v4 + - node_js: lts/* + - node_js: node + + - stage: lint ✨ + script: npm run test:lint + node_js: lts/* + + - stage: minify 🗜️ + script: | + npm run build + if ! git diff --quiet; then + git config --global user.email "travis@travis-ci.org" + git config --global user.name "Travis-CI" + git config credential.helper "store --file=.git/credentials" + echo "https://${GITHUB_TOKEN}:@github.com" > .git/credentials + git commit -am '🗜️ minify [skip ci]' + git push origin HEAD:${TRAVIS_BRANCH} + fi + node_js: lts/* + if: branch = master AND type = push + + - stage: security scan 🔐 + script: npm run test:redos + node_js: lts/* + +cache: + directories: + - node_modules + +git: + depth: 3 diff --git a/packages/markdown/marked/LICENSE.md b/packages/markdown/marked/LICENSE.md new file mode 100644 index 00000000..64b41a0e --- /dev/null +++ b/packages/markdown/marked/LICENSE.md @@ -0,0 +1,43 @@ +# License information + +## Contribution License Agreement + +If you contribute code to this project, you are implicitly allowing your code +to be distributed under the MIT license. You are also implicitly verifying that +all code is your original work. `` + +## Marked + +Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +## Markdown + +Copyright © 2004, John Gruber +http://daringfireball.net/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. diff --git a/packages/markdown/marked/Makefile b/packages/markdown/marked/Makefile new file mode 100644 index 00000000..7deead54 --- /dev/null +++ b/packages/markdown/marked/Makefile @@ -0,0 +1,15 @@ +all: + @cp lib/marked.js marked.js + @uglifyjs --comments '/\*[^\0]+?Copyright[^\0]+?\*/' -o marked.min.js lib/marked.js + +clean: + @rm marked.js + @rm marked.min.js + +bench: + @node test --bench + +man/marked.1.txt: + groff -man -Tascii man/marked.1 | col -b > man/marked.1.txt + +.PHONY: clean all diff --git a/packages/markdown/marked/README.md b/packages/markdown/marked/README.md new file mode 100644 index 00000000..2dfd5cd1 --- /dev/null +++ b/packages/markdown/marked/README.md @@ -0,0 +1,76 @@ + + + + +# Marked + +[![npm](https://badgen.net/npm/v/marked)](https://www.npmjs.com/package/marked) +[![gzip size](https://badgen.net/badgesize/gzip/https://cdn.jsdelivr.net/npm/marked/marked.min.js)](https://cdn.jsdelivr.net/npm/marked/marked.min.js) +[![install size](https://badgen.net/packagephobia/install/marked)](https://packagephobia.now.sh/result?p=marked) +[![downloads](https://badgen.net/npm/dt/marked)](https://www.npmjs.com/package/marked) +[![dep](https://badgen.net/david/dep/markedjs/marked?label=deps)](https://david-dm.org/markedjs/marked) +[![dev dep](https://badgen.net/david/dev/markedjs/marked?label=devDeps)](https://david-dm.org/markedjs/marked?type=dev) +[![travis](https://badgen.net/travis/markedjs/marked)](https://travis-ci.org/markedjs/marked) +[![snyk](https://snyk.io/test/npm/marked/badge.svg)](https://snyk.io/test/npm/marked) + +- ⚡ built for speed +- ⬇️ low-level compiler for parsing markdown without caching or blocking for long periods of time +- ⚖️ light-weight while implementing all markdown features from the supported flavors & specifications +- 🌐 works in a browser, on a server, or from a command line interface (CLI) + +## Demo + +Checkout the [demo page](https://marked.js.org/demo/) to see marked in action ⛹️ + +## Docs + +Our [documentation pages](https://marked.js.org) are also rendered using marked 💯 + +Also read about: + +* [Options](https://marked.js.org/#/USING_ADVANCED.md) +* [Extensibility](https://marked.js.org/#/USING_PRO.md) + +## Installation + +**CLI:** `npm install -g marked` + +**In-browser:** `npm install marked` + +## Usage + +### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/#/USING_ADVANCED.md#options) the output HTML by default 🚨 + +**CLI** + +``` bash +$ marked -o hello.html +hello world +^D +$ cat hello.html +

hello world

+``` + +**Browser** + +```html + + + + + Marked in the browser + + +
+ + + + +``` + +## License + +Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) diff --git a/packages/markdown/marked/bin/marked b/packages/markdown/marked/bin/marked new file mode 100755 index 00000000..0ea63c54 --- /dev/null +++ b/packages/markdown/marked/bin/marked @@ -0,0 +1,215 @@ +#!/usr/bin/env node + +/** + * Marked CLI + * Copyright (c) 2011-2013, Christopher Jeffrey (MIT License) + */ + +var fs = require('fs'), + path = require('path'), + marked = require('../'); + +/** + * Man Page + */ + +function help() { + var spawn = require('child_process').spawn; + + var options = { + cwd: process.cwd(), + env: process.env, + setsid: false, + stdio: 'inherit' + }; + + spawn('man', [path.resolve(__dirname, '/../man/marked.1')], options) + .on('error', function() { + fs.readFile(path.resolve(__dirname, '/../man/marked.1.txt'), 'utf8', function(err, data) { + if (err) throw err; + console.log(data); + }); + }); +} + +function version() { + var pkg = require('../package.json'); + console.log(pkg.version); +} + +/** + * Main + */ + +function main(argv, callback) { + var files = [], + options = {}, + input, + output, + string, + arg, + tokens, + opt; + + function getarg() { + var arg = argv.shift(); + + if (arg.indexOf('--') === 0) { + // e.g. --opt + arg = arg.split('='); + if (arg.length > 1) { + // e.g. --opt=val + argv.unshift(arg.slice(1).join('=')); + } + arg = arg[0]; + } else if (arg[0] === '-') { + if (arg.length > 2) { + // e.g. -abc + argv = arg.substring(1).split('').map(function(ch) { + return '-' + ch; + }).concat(argv); + arg = argv.shift(); + } else { + // e.g. -a + } + } else { + // e.g. foo + } + + return arg; + } + + while (argv.length) { + arg = getarg(); + switch (arg) { + case '--test': + return require('../test').main(process.argv.slice()); + case '-o': + case '--output': + output = argv.shift(); + break; + case '-i': + case '--input': + input = argv.shift(); + break; + case '-s': + case '--string': + string = argv.shift(); + break; + case '-t': + case '--tokens': + tokens = true; + break; + case '-h': + case '--help': + return help(); + case '-v': + case '--version': + return version(); + default: + if (arg.indexOf('--') === 0) { + opt = camelize(arg.replace(/^--(no-)?/, '')); + if (!marked.defaults.hasOwnProperty(opt)) { + continue; + } + if (arg.indexOf('--no-') === 0) { + options[opt] = typeof marked.defaults[opt] !== 'boolean' + ? null + : false; + } else { + options[opt] = typeof marked.defaults[opt] !== 'boolean' + ? argv.shift() + : true; + } + } else { + files.push(arg); + } + break; + } + } + + function getData(callback) { + if (!input) { + if (files.length <= 2) { + if (string) { + return callback(null, string); + } + return getStdin(callback); + } + input = files.pop(); + } + return fs.readFile(input, 'utf8', callback); + } + + return getData(function(err, data) { + if (err) return callback(err); + + data = tokens + ? JSON.stringify(marked.lexer(data, options), null, 2) + : marked(data, options); + + if (!output) { + process.stdout.write(data + '\n'); + return callback(); + } + + return fs.writeFile(output, data, callback); + }); +} + +/** + * Helpers + */ + +function getStdin(callback) { + var stdin = process.stdin, + buff = ''; + + stdin.setEncoding('utf8'); + + stdin.on('data', function(data) { + buff += data; + }); + + stdin.on('error', function(err) { + return callback(err); + }); + + stdin.on('end', function() { + return callback(null, buff); + }); + + try { + stdin.resume(); + } catch (e) { + callback(e); + } +} + +function camelize(text) { + return text.replace(/(\w)-(\w)/g, function(_, a, b) { + return a + b.toUpperCase(); + }); +} + +function handleError(err) { + if (err.code === 'ENOENT') { + console.error(`marked: output to ${err.path}: No such directory`); + return process.exit(1); + } + throw err; +} + +/** + * Expose / Entry Point + */ + +if (!module.parent) { + process.title = 'marked'; + main(process.argv.slice(), function(err, code) { + if (err) return handleError(err); + return process.exit(code || 0); + }); +} else { + module.exports = main; +} diff --git a/packages/markdown/marked/bower.json b/packages/markdown/marked/bower.json new file mode 100644 index 00000000..57c91f03 --- /dev/null +++ b/packages/markdown/marked/bower.json @@ -0,0 +1,23 @@ +{ + "name": "marked", + "homepage": "https://github.com/markedjs/marked", + "authors": [ + "Christopher Jeffrey " + ], + "description": "A markdown parser built for speed", + "keywords": [ + "markdown", + "markup", + "html" + ], + "main": "lib/marked.js", + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "app/bower_components", + "test", + "tests" + ] +} diff --git a/packages/markdown/marked/component.json b/packages/markdown/marked/component.json new file mode 100644 index 00000000..7ebd0356 --- /dev/null +++ b/packages/markdown/marked/component.json @@ -0,0 +1,10 @@ +{ + "name": "marked", + "version": "0.3.4", + "repo": "markedjs/marked", + "description": "A markdown parser built for speed", + "keywords": ["markdown", "markup", "html"], + "scripts": ["lib/marked.js"], + "main": "lib/marked.js", + "license": "MIT" +} diff --git a/packages/markdown/marked/docs/AUTHORS.md b/packages/markdown/marked/docs/AUTHORS.md new file mode 100644 index 00000000..dd914095 --- /dev/null +++ b/packages/markdown/marked/docs/AUTHORS.md @@ -0,0 +1,269 @@ +# Authors + +Marked takes an encompassing approach to its community. As such, you can think of these as [concentric circles](https://medium.com/the-node-js-collection/healthy-open-source-967fa8be7951), where each group encompases the following groups. + + + + + + + + + + + + + + +
+ + + +
+ Christopher Jeffrey +
Original Author
+ Started the fire +
+ + + +
+ Josh Bruce +
Publisher
+ Release Wrangler; Humaning Helper; Heckler of Hypertext +
+ + + +
+ Steven +
Publisher
+ Release Wrangler; Dr. Docs; Open source, of course; GitHub Guru; Humaning Helper +
+ + + +
+ Jamie Davis +
Committer
+ Seeker of Security +
+ + + +
+ Tony Brix +
Publisher
+ Release Wrangler; Titan of the test harness; Dr. DevOps +
+   +
+ + + + + + + + + + + + + + + + +
+ + + +
+ Brandon der Blätter +
Contributor
+ Curious Contributor +
+ + + +
+ Carlos Valle +
Contributor
+ Maker of the Marked mark from 2018 to present +
+ + + +
+ Federico Soave +
Contributor
+ Regent of the Regex; Master of Marked +
+ + + +
+ Karen Yavine +
Contributor
+ Snyk's Security Saint +
+ + + +
+ Костя Третяк +
Contributor
+ +
+ + + +
+ Tom Theisen +
Contributor
+ Defibrillator +
+ + + +
+ Mateus Craveiro +
Contributor
+ Defibrillator +
+
+ +## Publishers + +Publishers are admins who also have the responsibility, privilege, and burden of publishing the new releases to NPM and performing outreach and external stakeholder communications. Further, when things go pear-shaped, they're the ones taking most of the heat. Finally, when things go well, they're the primary ones praising the contributors who made it possible. + +(In other words, while Admins are focused primarily on the internal workings of the project, Publishers are focused on internal *and* external concerns.) + +**Should not exceed 2:** Having more people with the authority to publish a release can quickly turn into a consensus seeking nightmare (design by committee). Having only one is preferred (Directly Responsible Individual); however, given the nature of the project and its history, having an immediate fallback, and a potential deep fallback (Original author) is probably a good idea. + +[Details on badges](#badges) + +## Admins + +Admins are committers who also have the responsibility, privilege, and burden of selecting committers and making sure the project itself runs smoothly, which includes community maintenance, governance, dispute resolution, and so on. (Letting the contributors easily enter into, and work within, the project to begin contributing, with as little friction as possible.) + +**Should not exceed 3:** When there are too many people with the ability to resolve disputes, the dispute itself can quickly turn into a dispute amongst the admins themselves; therefore, we want this group to be small enough to commit to action and large enough to not put too much burden on one person. (Should ensure faster resolution and responsiveness.) + +To be listed: Admins are usually selected from the pool of committers (or they volunteer, using the same process) who demonstrate good understanding of the marked culture, operations, and do their best to help new contributors get up to speed on how to contribute effectively to the project. + +To be removed: You can remove yourself through the [GitHub UI](https://help.github.com/articles/removing-yourself-from-a-collaborator-s-repository/). + +[Details on badges](#badges) + +## Committers + +Committers are contributors who also have the responsibility, privilege, some might even say burden of being able to review and merge contributions (just usually not their own). + +A note on "decision making authority". This is related to submitting PRs and the [advice process](http://www.reinventingorganizationswiki.com/Decision_Making). The person marked as having decision making authority over a certain area should be sought for advice in that area before committing to a course of action. + +**Should not exceed 5:** For larger PRs affecting more of the codebase and, most likely, review by more people, we try to keep this pool small and responsive and let those with decision making authority have final say without negative repercussions from the other committers. + +To be listed: Committers are usually selected (or they volunteer, using the same process) from contributors who enter the discussions regarding the future direction of Marked (maybe even doing informal reviews of contributions despite not being able to merge them yourself). + +To be removed: You can remove yourself through the [GitHub UI](https://help.github.com/articles/removing-yourself-from-a-collaborator-s-repository/). + +A note on volunteering: + +1. Please do not volunteer unless you believe you can demonstrate to your peers you can do the work required. +2. Please do not overcommit yourself; we count on those committed to the project to be responsive. Really consider, with all you have going on, wehther you able to really commit to it. +3. Don't let the previous frighten you away, it can always be changed later by you or your peers. + +[Details on badges](#badges) + +## Contributors + +Contributors are users who submit a [PR](https://github.com/markedjs/marked/pulls), [Issue](https://github.com/markedjs/marked/issues), or collaborate in making Marked a better product and experience for all the users. + +To be listed: make a contribution and, if it has significant impact, the committers may be able to add you here. + +To be removed: please let us know or submit a PR. + +[Details on badges](#badges) + +## Users + +Users are anyone using Marked in some fashion, without them, there's no reason for us to exist. + +|Individual or Organization |Website |Project |Submitted by | +|:--------------------------|:-----------------------|:------------------------------------|:---------------------------------------------------| +|MarkedJS |https://marked.js.org |https://github.com/markedjs/marked |The marked committers | + +To be listed: All fields are optional. Contact any of the committers or, more timely, submit a pull request with the following (using the first row as an example): + +- **Individual or Organization:** The name you would like associated with the record. +- **Website:** A URL to a standalone website for the project. +- **Project:** A URL for the repository of the project using marked. +- **Submitted by:** The name and optional honorifics for the person adding the listing. + +To be removed: Same as above. Only instead of requesting addition request deletion or delete the row yourself. + +

Badges

+ +Badges? You don't *need* no stinkin' badges. + +Movie references aside. (It was either that or, "Let's play a game", but that would have been creepy…that's why it will most likely come later.) + +Badges? If you *want* 'em, we got 'em, and here's how you get 'em (and…dramatic pause…why not two dramatic pauses for emphasis?… how they can be taken away). + +- [ ] Add the appropriate badge to the desired contributor in the desired column of this page, even if they're not listed here yet. +- [ ] Submit a PR (we're big on PRs around here, if you haven't noticed, help us help you). +- [ ] Follow the instructions for submitting a badge PR. (There are more details to find within. Come on. Everybody likes surprises, right? No? Actually, we just try to put documentation where it belongs, closer to the code and part of the sequence of events.) + +### Badges at play: + +
+
Curious Contributor
+
A contributor with less than one year on this page who is actively engaged in submitting PRs, Issues, making recommendations, sharing thoughts…without being too annoying about it (let's be clear, submitting 100 Issues recommending the Marked Committers send everyone candy is trying for the badge, not honestly earning it).
+
Dr. DevOps
+
+

Someone who understands and contributes to improving the developer experience and flow of Marked into the world.

+
+ "The main characteristic of the DevOps movement is to strongly advocate automation and monitoring at all steps of software construction, from integration, testing, releasing to deployment and infrastructure management. DevOps aims at shorter development cycles, increased deployment frequency, more dependable releases, in close alignment with business objectives." ~ Wikipedia +
+
+
Dr. Docs
+
Someone who has contributed a great deal to the creation and maintainance of the non-code areas of marked.
+
Eye for the CLI
+
At this point? Pretty much anyone who can update that `man` file to the current Marked version without regression in the CLI tool itself.
+
GitHub Guru
+
Someone who always seems to be able to tell you easier ways to do things with GitHub.
+
Humaning Helper
+
Someone who goes out of their way to help contributors feel welcomed and valued. Further, someone who takes the extra steps(s) necessary to help new contributors get up to speed. Finally, they maintain composure even in times of disagreement and dispute resolution.
+
Heckler of Hypertext
+
Someone who demonstrates an esoteric level of knowledge when it comes to HTML. In other words, someone who says things like, "Did you know most Markdown flavors don't have a way to render a description list (`dl`)? All the more reason Markdown `!==` HTML."
+
Markdown Maestro
+
You know that person who knows about way too many different flavors of Markdown? The one who maybe seems a little too obsessed with the possibilities of Markdown beyond HTML? Come on. You know who they are. Or, at least you could, if you give them this badge.
+
Master of Marked
+
Someone who demonstrates they know the ins and outs of the codebase for Marked.
+
Open source, of course
+
Someone who advocates for and has a proven understanding of how to operate within open source communities.
+
Regent of the Regex
+

Can you demonstrate you understand the following without Google and Stackoverflow?

+

/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/

+

Because this author can't yet. That's who gets these.

+
+
Seeker of Security
+
Someone who has demonstrated a high degree of expertise or authority when it comes to software security.
+
Titan of the Test Harness
+
Someone who demonstrates high-levels of understanding regarding Marked's test harness.
+
Totally Tron
+
Someone who demonstrates they are willing and able to "fight for the users", both developers dependent on marked to do their jobs as well as end-users interacting with the output (particularly in the realm of those with the disabilities).
+
+ +### Special badges that come with the job: + +
+
Defibrillator
+
A contributor who stepped up to help bring Marked back to life by contriuting solutions to help Marked pass when compared against the CommonMark and GitHub Flavored Markdown specifications.
+
Maker of the Marked mark
+
This badge is given to the person or oganization credited with creating the logo (or logotype) used in Marked communications for a given period of time. **Maker of the Marked mark from 2017 to present**, for example.
+
Release Wrangler
+
This is a badge given to all Publishers.
+
Snyk's Security Saint
+
This is a badge given to whomever primarily reaches out from Snyk to let us know about security issues.
+
diff --git a/packages/markdown/marked/docs/CNAME b/packages/markdown/marked/docs/CNAME new file mode 100644 index 00000000..c92fdfcb --- /dev/null +++ b/packages/markdown/marked/docs/CNAME @@ -0,0 +1 @@ +marked.js.org diff --git a/packages/markdown/marked/docs/CODE_OF_CONDUCT.md b/packages/markdown/marked/docs/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..5335399b --- /dev/null +++ b/packages/markdown/marked/docs/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to block temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team by submitting a PR with changes to the [AUTHORS](#/AUTHORS.md) page (or emailing josh@8fold.com). All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version [1.4][version]. + +[homepage]: https://www.contributor-covenant.org/ +[version]: https://www.contributor-covenant.org/version/1/4/code-of-conduct.html diff --git a/packages/markdown/marked/docs/CONTRIBUTING.md b/packages/markdown/marked/docs/CONTRIBUTING.md new file mode 100644 index 00000000..ac88ba15 --- /dev/null +++ b/packages/markdown/marked/docs/CONTRIBUTING.md @@ -0,0 +1,92 @@ +# Contributing to Marked + +- [ ] Fork `markedjs/marked`. +- [ ] Clone the library locally using GitHub Desktop or the command line. +- [ ] Make sure you are on the `master` branch. +- [ ] Be sure to run `npm install` or `npm update`. +- [ ] Create a branch. +- [ ] Make as small a change as possible. +- [ ] Run `npm test`, fix any broken things (for linting, you can run `npm run lint` to have the linter fix them for you). +- [ ] Submit a PR. + +## Design principles + +Marked tends to favor following the SOLID set of software design and development principles; mainly the [single responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle) and [open/closed principles](https://en.wikipedia.org/wiki/Open/closed_principle): + +- **Single responsibility:** Marked, and the components of Marked, have the single responsibility of converting Markdown strings into HTML. +- **Open/closed:** Marked favors giving developers the means to easily extend the library and its components over changing Marked's behavior through configuration options. + +## Priorities + +We think we have our priorities sorted to build quality in. + +The following table lists the ticket type labels we use when there is work to be done on the code either through an Issue or a PR; in priority order. + +|Ticket type label |Description | +|:----------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +|L0 - security |A security vulnerability within the Marked library is discovered. | +|L1 - broken |Valid usage results in incorrect output compared to [supported specifications](#/README.md#specifications) OR causes marked to crash AND there is no known workaround for the issue. | +|L2 - annoying |Similar to L1 - broken only there is a known workaround available for the issue. | +|RR - refactor and re-engineer |Results in an improvement to developers using Marked (improved readability) or end-users (faster performance) or both. | +|NFS - new feature (spec related) |A capability Marked does not currently provide but is in one of the [supported specifications](#/README.md#specifications) | +|NFU - new feature (user requested) |A capability Marked does not currently provide but has been requested by users of Marked. | + +## Test early, often, and everything + +We try to write test cases to validate output (writing tests based on the [supported specifications](#/README.md#specifications)) and minimize regression (writing tests for issues fixed). Therefore, if you would like to contribute, some things you should know regarding the test harness. + +|Location |Description | +|:-------------|:---------------------------------------------------| +|/test/browser |For testing Marked in a client-side implementation. | +|/test/new |Tests not related to the original `markdown.pl`. | +|/test/original|Tests validating against the original `markdown.pl`.| + +If your test uses features or options, assuming `gfm` is set to `false`, for example, you can add [front-matter](https://www.npmjs.com/package/front-matter) to the top of +your `.md` file + +``` yml +--- +gfm: false +--- +``` + +## Submitting PRs and Issues + +Marked provides templates for submitting both pull requests and issues. When you begin creating a new PR or issue, you will see instructions on using the template. + +The PR templates include checklists for both the submitter and the reviewer, which, in most cases, will not be the same person. + +## Scripts + +When it comes to NPM commands, we try to use the native scripts provided by the NPM framework. + +To run the tests: + +``` bash +npm test +``` + +To test whether you are using the standard syntax rules for the project: + +```bash +npm run test:lint +``` + +To see time comparisons between Marked and other popular Markdown libraries: + +```bash +npm run bench +``` + +To check for (and fix) standardized syntax (lint): + +```bash +npm run lint +``` + +To build your own minified version of Marked: + +```bash +npm run build +``` + diff --git a/packages/markdown/marked/docs/PUBLISHING.md b/packages/markdown/marked/docs/PUBLISHING.md new file mode 100644 index 00000000..27937c2f --- /dev/null +++ b/packages/markdown/marked/docs/PUBLISHING.md @@ -0,0 +1,24 @@ +# Releasing Marked + +- [ ] See [contributing](#/CONTRIBUTING.md) +- [ ] Create release branch from `master` (`release-x.y.z`) +- [ ] Submit PR with minimal name: Release x.y.z +- [ ] Complete PR checklists + +## Overall strategy + +**Master is always shippable:** We try to merge PRs in such a way that `master` is the only branch to really be concerned about *and* `master` can always be released. This allows smoother flow between new fetures, bug fixes, and so on. (Almost a continuous deployment setup, without automation.) + +## Versioning + +We follow [semantic versioning](https://semver.org) where the following sequence is true `[major].[minor].[patch]`; therefore, consider the following implications of the release you are preparing: + +1. **Major:** There is at least one change not deemed backward compatible. +2. **Minor:** There is at least one new feature added to the release. +3. **Patch:** No breaking changes, no new features. + +What to expect while Marked is a zero-major (0.x.y): + +1. The major will remain at zero; thereby, alerting consumers to the potentially volatile nature of the package. +2. The minor will tend to be more analagous to a `major` release. +3. The patch will tend to be more analagous to a `minor` release or a collection of bug fixes (patches). diff --git a/packages/markdown/marked/docs/README.md b/packages/markdown/marked/docs/README.md new file mode 100644 index 00000000..261e4f3b --- /dev/null +++ b/packages/markdown/marked/docs/README.md @@ -0,0 +1,85 @@ +Marked is + +1. built for speed.* +2. a low-level markdown compiler for parsing markdown without caching or blocking for long periods of time.** +3. light-weight while implementing all markdown features from the supported flavors & specifications.*** +4. available as a command line interface (CLI) and running in client- or server-side JavaScript projects. + +

* Still working on metrics for comparative analysis and definition.
+** As few dependencies as possible.
+*** Strict compliance could result in slower processing when running comparative benchmarking.

+ + +

Demo

+ +Checkout the [demo page](./demo/) to see marked in action ⛹️ + +These documentation pages are also rendered using marked 💯 + + +

Installation

+ +**CLI:** `npm install -g marked` + +**In-browser:** `npm install marked` + +

Usage

+ +### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/#/USING_ADVANCED.md#options) the output HTML by default 🚨 + +**CLI** + +``` bash +$ marked -o hello.html +hello world +^D +$ cat hello.html +

hello world

+``` + +``` bash +$ marked -s "*hello world*" +

hello world

+``` + +**Browser** + +```html + + + + + Marked in the browser + + +
+ + + + +``` + + +Marked offers [advanced configurations](#/USING_ADVANCED.md) and [extensibility](#/USING_PRO.md) as well. + +

Supported Markdown specifications

+ +We actively support the features of the following [Markdown flavors](https://github.com/commonmark/CommonMark/wiki/Markdown-Flavors). + +|Flavor |Version | +|:----------------------------------------------------------|:----------| +|The original markdown.pl |-- | +|[CommonMark](http://spec.commonmark.org/0.28/) |0.28 | +|[GitHub Flavored Markdown](https://github.github.com/gfm/) |0.28 | + +By supporting the above Markdown flavors, it's possible that Marked can help you use other flavors as well; however, these are not actively supported by the community. + +

Security

+ +The only completely secure system is the one that doesn't exist in the first place. Having said that, we take the security of Marked very seriously. + +Therefore, please disclose potential security issues by email to the project [committers](#/AUTHORS.md) as well as the [listed owners within NPM](https://docs.npmjs.com/cli/owner). We will provide an initial assessment of security reports within 48 hours and should apply patches within 2 weeks (also, feel free to contribute a fix for the issue). + diff --git a/packages/markdown/marked/docs/USING_ADVANCED.md b/packages/markdown/marked/docs/USING_ADVANCED.md new file mode 100644 index 00000000..6490caa7 --- /dev/null +++ b/packages/markdown/marked/docs/USING_ADVANCED.md @@ -0,0 +1,78 @@ +## The `marked` function + +```js +marked(markdownString [,options] [,callback]) +``` + +|Argument |Type |Notes | +|:---------------------|:------------|:----------------------------------------------------------------------------------------------------| +|markdownString |`string` |String of markdown source to be compiled. | +|options|`object`|Hash of options. Can also use `marked.setOptions`. | +|callback |`function` |Called when `markdownString` has been parsed. Can be used as second argument if no `options` present.| + +### Alternative using reference + +```js +// Create reference instance +var myMarked = require('marked'); + +// Set options +// `highlight` example uses `highlight.js` +myMarked.setOptions({ + renderer: new myMarked.Renderer(), + highlight: function(code) { + return require('highlight.js').highlightAuto(code).value; + }, + pedantic: false, + gfm: true, + tables: true, + breaks: false, + sanitize: false, + smartLists: true, + smartypants: false, + xhtml: false +}); + +// Compile +console.log(myMarked('I am using __markdown__.')); +``` + +

Options

+ +|Member |Type |Default |Since |Notes | +|:-----------|:---------|:--------|:--------|:-------------| +|baseUrl |`string` |`null` |0.3.9 |A prefix url for any relative link. | +|breaks |`boolean` |`false` |v0.2.7 |If true, add `
` on a single line break (copies GitHub). Requires `gfm` be `true`.| +|gfm |`boolean` |`true` |v0.2.1 |If true, use approved [GitHub Flavored Markdown (GFM) specification](https://github.github.com/gfm/).| +|headerIds |`boolean` |`true` |v0.4.0 |If true, include an `id` attribute when emitting headings (h1, h2, h3, etc).| +|headerPrefix|`string` |`''` |v0.3.0 |A string to prefix the `id` attribute when emitting headings (h1, h2, h3, etc).| +|highlight |`function`|`null` |v0.3.0 |A function to highlight code blocks, see Asynchronous highlighting.| +|langPrefix |`string` |`'language-'`|v0.3.0|A string to prefix the className in a `` block. Useful for syntax highlighting.| +|mangle |`boolean` |`true` |v0.3.4 |If true, autolinked email address is escaped with HTML character references.| +|pedantic |`boolean` |`false` |v0.2.1 |If true, conform to the original `markdown.pl` as much as possible. Don't fix original markdown bugs or behavior. Turns off and overrides `gfm`.| +|renderer |`object` |`new Renderer()`|v0.3.0|An object containing functions to render tokens to HTML. See [extensibility](USING_PRO.md) for more details.| +|sanitize |`boolean` |`false` |v0.2.1 |If true, sanitize the HTML passed into `markdownString` with the `sanitizer` function.| +|sanitizer |`function`|`null` |v0.3.4 |A function to sanitize the HTML passed into `markdownString`.| +|silent |`boolean` |`false` |v0.2.7 |If true, the parser does not throw any exception.| +|smartLists |`boolean` |`false` |v0.2.8 |If true, use smarter list behavior than those found in `markdown.pl`.| +|smartypants |`boolean` |`false` |v0.2.9 |If true, use "smart" typographic punctuation for things like quotes and dashes.| +|tables |`boolean` |`true` |v0.2.7 |If true and `gfm` is true, use [GFM Tables extension](https://github.github.com/gfm/#tables-extension-).| +|xhtml |`boolean` |`false` |v0.3.2 |If true, emit self-closing HTML tags for void elements (<br/>, <img/>, etc.) with a "/" as required by XHTML.| + +

Asynchronous highlighting

+ +Unlike `highlight.js` the `pygmentize.js` library uses asynchronous highlighting. This example demonstrates that marked is agnostic when it comes to the highlighter you use. + +```js +myMarked.setOptions({ + highlight: function(code, lang, callback) { + require('pygmentize-bundled') ({ lang: lang, format: 'html' }, code, function (err, result) { + callback(err, result.toString()); + }); + } +}); + +console.log(myMarked(markdownString)); +``` + +In both examples, `code` is a `string` representing the section of code to pass to the highlighter. In this example, `lang` is a `string` informing the highlighter what programming lnaguage to use for the `code` and `callback` is the `function` the asynchronous highlighter will call once complete. diff --git a/packages/markdown/marked/docs/USING_PRO.md b/packages/markdown/marked/docs/USING_PRO.md new file mode 100644 index 00000000..861caa2d --- /dev/null +++ b/packages/markdown/marked/docs/USING_PRO.md @@ -0,0 +1,163 @@ +## Extending Marked + +To champion the single-responsibility and open/closed prinicples, we have tried to make it relatively painless to extend marked. If you are looking to add custom functionality, this is the place to start. + +

The renderer

+ +The renderer is... + +**Example:** Overriding default heading token by adding an embedded anchor tag like on GitHub. + +```js +// Create reference instance +var myMarked = require('marked'); + +// Get reference +var renderer = new myMarked.Renderer(); + +// Override function +renderer.heading = function (text, level) { + var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-'); + + return ` + + + + + ${text} + `; +}; + +// Run marked +console.log(myMarked('# heading+', { renderer: renderer })); +``` + +**Output:** + +```html +

+ + + + heading+ +

+``` + +### Block level renderer methods + +- code(*string* code, *string* infostring, *boolean* escaped) +- blockquote(*string* quote) +- html(*string* html) +- heading(*string* text, *number* level, *string* raw, *Slugger* slugger) +- hr() +- list(*string* body, *boolean* ordered, *number* start) +- listitem(*string* text, *boolean* task, *boolean* checked) +- checkbox(*boolean* checked) +- paragraph(*string* text) +- table(*string* header, *string* body) +- tablerow(*string* content) +- tablecell(*string* content, *object* flags) + +`slugger` has the `slug` method to create an unique id from value: + +```js +slugger.slug('foo') // foo +slugger.slug('foo') // foo-1 +slugger.slug('foo') // foo-2 +slugger.slug('foo 1') // foo-1-1 +slugger.slug('foo-1') // foo-1-2 +... +``` + +`flags` has the following properties: + +```js +{ + header: true || false, + align: 'center' || 'left' || 'right' +} +``` + +### Inline level renderer methods + +- strong(*string* text) +- em(*string* text) +- codespan(*string* code) +- br() +- del(*string* text) +- link(*string* href, *string* title, *string* text) +- image(*string* href, *string* title, *string* text) +- text(*string* text) + +

The lexer

+ +The lexer is... + + +

The parser

+ +The parser is... + +*** + +

Access to lexer and parser

+ +You also have direct access to the lexer and parser if you so desire. + +``` js +var tokens = marked.lexer(text, options); +console.log(marked.parser(tokens)); +``` + +``` js +var lexer = new marked.Lexer(options); +var tokens = lexer.lex(text); +console.log(tokens); +console.log(lexer.rules); +``` + +``` bash +$ node +> require('marked').lexer('> i am using marked.') +[ { type: 'blockquote_start' }, + { type: 'paragraph', + text: 'i am using marked.' }, + { type: 'blockquote_end' }, + links: {} ] +``` + +The Lexers build an array of tokens, which will be passed to their respective +Parsers. The Parsers process each token in the token arrays, +which are removed from the array of tokens: + +``` js +const marked = require('marked'); + +const md = ` + # heading + + [link][1] + + [1]: #heading "heading" +`; + +const tokens = marked.lexer(md); +console.log(tokens); + +const html = marked.parser(tokens); +console.log(html); + +console.log(tokens); +``` + +``` bash +[ { type: 'heading', depth: 1, text: 'heading' }, + { type: 'paragraph', text: ' [link][1]' }, + { type: 'space' }, + links: { '1': { href: '#heading', title: 'heading' } } ] + +

heading

+

link

+ +[ links: { '1': { href: '#heading', title: 'heading' } } ] +``` diff --git a/packages/markdown/marked/docs/broken.md b/packages/markdown/marked/docs/broken.md new file mode 100644 index 00000000..7bfa49e8 --- /dev/null +++ b/packages/markdown/marked/docs/broken.md @@ -0,0 +1,426 @@ +# Markdown is broken + +I have a lot of scraps of markdown engine oddities that I've collected over the +years. What you see below is slightly messy, but it's what I've managed to +cobble together to illustrate the differences between markdown engines, and +why, if there ever is a markdown specification, it has to be absolutely +thorough. There are a lot more of these little differences I have documented +elsewhere. I know I will find them lingering on my disk one day, but until +then, I'll continue to add whatever strange nonsensical things I find. + +Some of these examples may only mention a particular engine compared to marked. +However, the examples with markdown.pl could easily be swapped out for +discount, upskirt, or markdown.js, and you would very easily see even more +inconsistencies. + +A lot of this was written when I was very unsatisfied with the inconsistencies +between markdown engines. Please excuse the frustration noticeable in my +writing. + +## Examples of markdown's "stupid" list parsing + +``` +$ markdown.pl + + * item1 + + * item2 + + text +^D +
    +
  • item1

    + +
      +
    • item2
    • +
    + +

    text

  • +

+``` + + +``` +$ marked + * item1 + + * item2 + + text +^D +
    +
  • item1

    +
      +
    • item2
    • +
    +

    text

    +
  • +
+``` + +Which looks correct to you? + +- - - + +``` +$ markdown.pl +* hello + > world +^D +

    +
  • hello

    + +
    +

    world

  • +

+ +``` + +``` +$ marked +* hello + > world +^D +
    +
  • hello
    +

    world

    +
    +
  • +
+``` + +Again, which looks correct to you? + +- - - + +EXAMPLE: + +``` +$ markdown.pl +* hello + * world + * hi + code +^D +
    +
  • hello +
      +
    • world
    • +
    • hi + code
    • +
  • +
+``` + +The code isn't a code block even though it's after the bullet margin. I know, +lets give it two more spaces, effectively making it 8 spaces past the bullet. + +``` +$ markdown.pl +* hello + * world + * hi + code +^D +
    +
  • hello +
      +
    • world
    • +
    • hi + code
    • +
  • +
+``` + +And, it's still not a code block. Did you also notice that the 3rd item isn't +even its own list? Markdown screws that up too because of its indentation +unaware parsing. + +- - - + +Let's look at some more examples of markdown's list parsing: + +``` +$ markdown.pl + + * item1 + + * item2 + + text +^D +
    +
  • item1

    + +
      +
    • item2
    • +
    + +

    text

  • +

+``` + +Misnested tags. + + +``` +$ marked + * item1 + + * item2 + + text +^D +
    +
  • item1

    +
      +
    • item2
    • +
    +

    text

    +
  • +
+``` + +Which looks correct to you? + +- - - + +``` +$ markdown.pl +* hello + > world +^D +

    +
  • hello

    + +
    +

    world

  • +

+ +``` + +More misnested tags. + + +``` +$ marked +* hello + > world +^D +
    +
  • hello
    +

    world

    +
    +
  • +
+``` + +Again, which looks correct to you? + +- - - + +# Why quality matters - Part 2 + +``` bash +$ markdown.pl +* hello + > world +^D +

    +
  • hello

    + +
    +

    world

  • +

+ +``` + +``` bash +$ sundown # upskirt +* hello + > world +^D +
    +
  • hello +> world
  • +
+``` + +``` bash +$ marked +* hello + > world +^D +
  • hello

    world

+``` + +Which looks correct to you? + +- - - + +See: https://github.com/evilstreak/markdown-js/issues/23 + +``` bash +$ markdown.pl # upskirt/markdown.js/discount +* hello + var a = 1; +* world +^D +
    +
  • hello +var a = 1;
  • +
  • world
  • +
+``` + +``` bash +$ marked +* hello + var a = 1; +* world +^D +
  • hello +
    code>var a = 1;
  • +
  • world
+``` + +Which looks more reasonable? Why shouldn't code blocks be able to appear in +list items in a sane way? + +- - - + +``` bash +$ markdown.js +
hello
+ +hello +^D +

<div>hello</div>

+ +

<span>hello</span>

+``` + +``` bash +$ marked +
hello
+ +hello +^D +
hello
+ + +

hello +

+``` + +- - - + +See: https://github.com/evilstreak/markdown-js/issues/27 + +``` bash +$ markdown.js +[![an image](/image)](/link) +^D +

![an image

+``` + +``` bash +$ marked +[![an image](/image)](/link) +^D +

an image +

+``` + +- - - + +See: https://github.com/evilstreak/markdown-js/issues/24 + +``` bash +$ markdown.js +> a + +> b + +> c +^D +

a

bundefined> c

+``` + +``` bash +$ marked +> a + +> b + +> c +^D +

a + +

+

b + +

+

c +

+``` + +- - - + +``` bash +$ markdown.pl +* hello + * world + how + + are + you + + * today +* hi +^D +
    +
  • hello

    + +
      +
    • world +how
    • +
    + +

    are +you

    + +
      +
    • today
    • +
  • +
  • hi
  • +
+``` + +``` bash +$ marked +* hello + * world + how + + are + you + + * today +* hi +^D +
    +
  • hello

    +
      +
    • world +how

      +

      are +you

      +
    • +
    • today

      +
    • +
    +
  • +
  • hi
  • +
+``` diff --git a/packages/markdown/marked/docs/demo/demo.css b/packages/markdown/marked/docs/demo/demo.css new file mode 100644 index 00000000..398c663a --- /dev/null +++ b/packages/markdown/marked/docs/demo/demo.css @@ -0,0 +1,72 @@ +html, body { + margin: 0; + padding: 0; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + color: #333; + background-color: #fbfbfb; + height: 100%; +} + +textarea { + font-family: Menlo, Monaco, Consolas, "Courier New", monospace; + font-size: 12px; + resize: none; +} + +header { + padding-top: 10px; + display: flex; + height: 58px; +} + +header h1 { + margin: 0; +} + +.github-ribbon { + position: absolute; + top: 0; + right: 0; + border: 0; + z-index: 1000; +} + +.containers { + display: flex; + height: calc(100vh - 68px); +} + +.container { + flex-basis: 50%; + padding: 5px; + display: flex; + flex-direction: column; + height: 100%; + box-sizing: border-box; +} + +.pane, .inputPane { + margin-top: 5px; + padding: 0.6em; + border: 1px solid #ccc; + overflow: auto; + flex-grow: 1; + flex-shrink: 1; +} + +#preview { + display: flex; +} + +#preview iframe { + flex-grow: 1; +} + +#main { + display: none; +} + +.error { + border-color: red; + background-color: #FEE +} diff --git a/packages/markdown/marked/docs/demo/demo.js b/packages/markdown/marked/docs/demo/demo.js new file mode 100644 index 00000000..e7d97c59 --- /dev/null +++ b/packages/markdown/marked/docs/demo/demo.js @@ -0,0 +1,534 @@ +/* globals marked, unfetch, ES6Promise */ + +if (!window.Promise) { + window.Promise = ES6Promise; +} +if (!window.fetch) { + window.fetch = unfetch; +} + +onunhandledrejection = function (e) { + throw e.reason; +}; + +var $loadingElem = document.querySelector('#loading'); +var $mainElem = document.querySelector('#main'); +var $markdownElem = document.querySelector('#markdown'); +var $markedVerElem = document.querySelector('#markedVersion'); +var $commitVerElem = document.querySelector('#commitVersion'); +var $markedVer = document.querySelector('#markedCdn'); +var $optionsElem = document.querySelector('#options'); +var $outputTypeElem = document.querySelector('#outputType'); +var $inputTypeElem = document.querySelector('#inputType'); +var $responseTimeElem = document.querySelector('#responseTime'); +var $previewElem = document.querySelector('#preview'); +var $previewIframe = document.querySelector('#preview iframe'); +var $permalinkElem = document.querySelector('#permalink'); +var $clearElem = document.querySelector('#clear'); +var $htmlElem = document.querySelector('#html'); +var $lexerElem = document.querySelector('#lexer'); +var $panes = document.querySelectorAll('.pane'); +var $inputPanes = document.querySelectorAll('.inputPane'); +var lastInput = ''; +var inputDirty = true; +var $activeOutputElem = null; +var search = searchToObject(); +var markedVersions = { + master: 'https://cdn.jsdelivr.net/gh/markedjs/marked/lib/marked.js' +}; +var markedVersionCache = {}; +var delayTime = 1; +var checkChangeTimeout = null; +var markedWorker; + +$previewIframe.addEventListener('load', handleIframeLoad); + +$outputTypeElem.addEventListener('change', handleOutputChange, false); + +$inputTypeElem.addEventListener('change', handleInputChange, false); + +$markedVerElem.addEventListener('change', handleVersionChange, false); + +$markdownElem.addEventListener('change', handleInput, false); +$markdownElem.addEventListener('keyup', handleInput, false); +$markdownElem.addEventListener('keypress', handleInput, false); +$markdownElem.addEventListener('keydown', handleInput, false); + +$optionsElem.addEventListener('change', handleInput, false); +$optionsElem.addEventListener('keyup', handleInput, false); +$optionsElem.addEventListener('keypress', handleInput, false); +$optionsElem.addEventListener('keydown', handleInput, false); + +$commitVerElem.style.display = 'none'; +$commitVerElem.addEventListener('keypress', handleAddVersion, false); + +$clearElem.addEventListener('click', handleClearClick, false); + +Promise.all([ + setInitialQuickref(), + setInitialOutputType(), + setInitialText(), + setInitialVersion() + .then(setInitialOptions) +]).then(function () { + handleInputChange(); + handleOutputChange(); + checkForChanges(); + setScrollPercent(0); + $loadingElem.style.display = 'none'; + $mainElem.style.display = 'block'; +}); + +function setInitialText() { + if ('text' in search) { + $markdownElem.value = search.text; + } else { + return fetch('./initial.md') + .then(function (res) { return res.text(); }) + .then(function (text) { + if ($markdownElem.value === '') { + $markdownElem.value = text; + } + }); + } +} + +function setInitialQuickref() { + return fetch('./quickref.md') + .then(function (res) { return res.text(); }) + .then(function (text) { + document.querySelector('#quickref').value = text; + }); +} + +function setInitialVersion() { + return fetch('https://data.jsdelivr.com/v1/package/npm/marked') + .then(function (res) { + return res.json(); + }) + .then(function (json) { + for (var i = 0; i < json.versions.length; i++) { + var ver = json.versions[i]; + markedVersions[ver] = 'https://cdn.jsdelivr.net/npm/marked@' + ver + '/lib/marked.js'; + var opt = document.createElement('option'); + opt.textContent = ver; + opt.value = ver; + $markedVerElem.appendChild(opt); + } + }) + .then(function () { + return fetch('https://api.github.com/repos/markedjs/marked/commits') + .then(function (res) { + return res.json(); + }) + .then(function (json) { + markedVersions['master'] = 'https://cdn.jsdelivr.net/gh/markedjs/marked@' + json[0].sha + '/lib/marked.js'; + }) + .catch(function () { + // do nothing + // uses url without commit + }); + }) + .then(function () { + if (search.version) { + if (markedVersions[search.version]) { + return search.version; + } else { + var match = search.version.match(/^(\w+):(.+)$/); + if (match) { + switch (match[1]) { + case 'commit': + addCommitVersion(search.version, match[2].substring(0, 7), match[2]); + return search.version; + case 'pr': + return getPrCommit(match[2]) + .then(function (commit) { + if (!commit) { + return 'master'; + } + addCommitVersion(search.version, 'PR #' + match[2], commit); + return search.version; + }); + } + } + } + } + + return 'master'; + }) + .then(function (version) { + $markedVerElem.value = version; + }) + .then(updateVersion); +} + +function setInitialOptions() { + if ('options' in search) { + $optionsElem.value = search.options; + } else { + setDefaultOptions(); + } +} + +function setInitialOutputType() { + if (search.outputType) { + $outputTypeElem.value = search.outputType; + } +} + +function handleIframeLoad() { + lastInput = ''; + inputDirty = true; +} + +function handleInput() { + inputDirty = true; +}; + +function handleVersionChange() { + if ($markedVerElem.value === 'commit' || $markedVerElem.value === 'pr') { + $commitVerElem.style.display = ''; + } else { + $commitVerElem.style.display = 'none'; + updateVersion(); + } +} + +function handleClearClick() { + $markdownElem.value = ''; + $markedVerElem.value = 'master'; + $commitVerElem.style.display = 'none'; + updateVersion().then(setDefaultOptions); +} + +function handleAddVersion(e) { + if (e.which === 13) { + switch ($markedVerElem.value) { + case 'commit': + var commit = $commitVerElem.value.toLowerCase(); + if (!commit.match(/^[0-9a-f]{40}$/)) { + alert('That is not a valid commit'); + return; + } + addCommitVersion('commit:' + commit, commit.substring(0, 7), commit); + $markedVerElem.value = 'commit:' + commit; + $commitVerElem.style.display = 'none'; + $commitVerElem.value = ''; + updateVersion(); + break; + case 'pr': + $commitVerElem.disabled = true; + var pr = $commitVerElem.value.replace(/\D/g, ''); + getPrCommit(pr) + .then(function (commit) { + $commitVerElem.disabled = false; + if (!commit) { + alert('That is not a valid PR'); + return; + } + addCommitVersion('pr:' + pr, 'PR #' + pr, commit); + $markedVerElem.value = 'pr:' + pr; + $commitVerElem.style.display = 'none'; + $commitVerElem.value = ''; + updateVersion(); + }); + } + } +} + +function handleInputChange() { + handleChange($inputPanes, $inputTypeElem.value); +} + +function handleOutputChange() { + $activeOutputElem = handleChange($panes, $outputTypeElem.value); + updateLink(); +} + +function handleChange(panes, visiblePane) { + var active = null; + for (var i = 0; i < panes.length; i++) { + if (panes[i].id === visiblePane) { + panes[i].style.display = ''; + active = panes[i]; + } else { + panes[i].style.display = 'none'; + } + } + return active; +}; + +function addCommitVersion(value, text, commit) { + if (markedVersions[value]) { + return; + } + markedVersions[value] = 'https://cdn.jsdelivr.net/gh/markedjs/marked@' + commit + '/lib/marked.js'; + var opt = document.createElement('option'); + opt.textContent = text; + opt.value = value; + $markedVerElem.insertBefore(opt, $markedVerElem.firstChild); +} + +function getPrCommit(pr) { + return fetch('https://api.github.com/repos/markedjs/marked/pulls/' + pr + '/commits') + .then(function (res) { + return res.json(); + }) + .then(function (json) { + return json[json.length - 1].sha; + }).catch(function () { + // return undefined + }); +} + +function setDefaultOptions() { + if (window.Worker) { + messageWorker({ + task: 'defaults', + version: markedVersions[$markedVerElem.value] + }); + } else { + var defaults = marked.getDefaults(); + setOptions(defaults); + } +} + +function setOptions(opts) { + $optionsElem.value = JSON.stringify( + opts, + function (key, value) { + if (value && typeof value === 'object' && Object.getPrototypeOf(value) !== Object.prototype) { + return undefined; + } + return value; + }, ' '); +} + +function searchToObject() { + // modified from https://stackoverflow.com/a/7090123/806777 + var pairs = location.search.slice(1).split('&'); + var obj = {}; + + for (var i = 0; i < pairs.length; i++) { + if (pairs[i] === '') { + continue; + } + + var pair = pairs[i].split('='); + + obj[decodeURIComponent(pair.shift())] = decodeURIComponent(pair.join('=')); + } + + return obj; +} + +function jsonString(input) { + var output = (input + '') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\t/g, '\\t') + .replace(/\f/g, '\\f') + .replace(/[\\"']/g, '\\$&') + .replace(/\u0000/g, '\\0'); + return '"' + output + '"'; +}; + +function getScrollSize() { + var e = $activeOutputElem; + + return e.scrollHeight - e.clientHeight; +}; + +function getScrollPercent() { + var size = getScrollSize(); + + if (size <= 0) { + return 1; + } + + return $activeOutputElem.scrollTop / size; +}; + +function setScrollPercent(percent) { + $activeOutputElem.scrollTop = percent * getScrollSize(); +}; + +function updateLink() { + var outputType = ''; + if ($outputTypeElem.value !== 'preview') { + outputType = 'outputType=' + $outputTypeElem.value + '&'; + } + + $permalinkElem.href = '?' + outputType + 'text=' + encodeURIComponent($markdownElem.value) + + '&options=' + encodeURIComponent($optionsElem.value) + + '&version=' + encodeURIComponent($markedVerElem.value); + history.replaceState('', document.title, $permalinkElem.href); +} + +function updateVersion() { + if (window.Worker) { + handleInput(); + return Promise.resolve(); + } + var promise; + if (markedVersionCache[$markedVerElem.value]) { + promise = Promise.resolve(markedVersionCache[$markedVerElem.value]); + } else { + promise = fetch(markedVersions[$markedVerElem.value]) + .then(function (res) { return res.text(); }) + .then(function (text) { + markedVersionCache[$markedVerElem.value] = text; + return text; + }); + } + return promise.then(function (text) { + var script = document.createElement('script'); + script.textContent = text; + + $markedVer.parentNode.replaceChild(script, $markedVer); + $markedVer = script; + }).then(handleInput); +} + +function checkForChanges() { + if (inputDirty && $markedVerElem.value !== 'commit' && $markedVerElem.value !== 'pr' && (typeof marked !== 'undefined' || window.Worker)) { + inputDirty = false; + + updateLink(); + + var options = {}; + var optionsString = $optionsElem.value || '{}'; + try { + var newOptions = JSON.parse(optionsString); + options = newOptions; + $optionsElem.classList.remove('error'); + } catch (err) { + $optionsElem.classList.add('error'); + } + + var version = markedVersions[$markedVerElem.value]; + var markdown = $markdownElem.value; + var hash = version + markdown + optionsString; + if (lastInput !== hash) { + lastInput = hash; + if (window.Worker) { + delayTime = 100; + messageWorker({ + task: 'parse', + version: version, + markdown: markdown, + options: options + }); + } else { + var startTime = new Date(); + var lexed = marked.lexer(markdown, options); + var lexedList = []; + for (var i = 0; i < lexed.length; i++) { + var lexedLine = []; + for (var j in lexed[i]) { + lexedLine.push(j + ':' + jsonString(lexed[i][j])); + } + lexedList.push('{' + lexedLine.join(', ') + '}'); + } + var parsed = marked.parser(lexed, options); + var scrollPercent = getScrollPercent(); + setParsed(parsed, lexedList.join('\n')); + setScrollPercent(scrollPercent); + var endTime = new Date(); + delayTime = endTime - startTime; + setResponseTime(delayTime); + if (delayTime < 50) { + delayTime = 50; + } else if (delayTime > 500) { + delayTime = 1000; + } + } + } + } + checkChangeTimeout = window.setTimeout(checkForChanges, delayTime); +}; + +function setResponseTime(ms) { + var amount = ms; + var suffix = 'ms'; + if (ms > 1000 * 60 * 60) { + amount = 'Too Long'; + suffix = ''; + } else if (ms > 1000 * 60) { + amount = '>' + Math.floor(ms / (1000 * 60)); + suffix = 'm'; + } else if (ms > 1000) { + amount = '>' + Math.floor(ms / 1000); + suffix = 's'; + } + $responseTimeElem.textContent = amount + suffix; +} + +function setParsed(parsed, lexed) { + try { + $previewIframe.contentDocument.body.innerHTML = parsed; + } catch (ex) {} + $htmlElem.value = parsed; + $lexerElem.value = lexed; +} + +function messageWorker(message) { + if (!markedWorker || markedWorker.working) { + if (markedWorker) { + clearTimeout(markedWorker.timeout); + markedWorker.terminate(); + } + markedWorker = new Worker('worker.js'); + markedWorker.onmessage = function (e) { + clearTimeout(markedWorker.timeout); + markedWorker.working = false; + switch (e.data.task) { + case 'defaults': + setOptions(e.data.defaults); + break; + case 'parse': + $previewElem.classList.remove('error'); + $htmlElem.classList.remove('error'); + $lexerElem.classList.remove('error'); + var scrollPercent = getScrollPercent(); + setParsed(e.data.parsed, e.data.lexed); + setScrollPercent(scrollPercent); + setResponseTime(e.data.time); + break; + } + clearTimeout(checkChangeTimeout); + delayTime = 10; + checkForChanges(); + }; + markedWorker.onerror = markedWorker.onmessageerror = function (err) { + clearTimeout(markedWorker.timeout); + var error = 'There was an error in the Worker'; + if (err) { + if (err.message) { + error = err.message; + } else { + error = err; + } + } + error = error.replace(/^Uncaught Error: /, ''); + $previewElem.classList.add('error'); + $htmlElem.classList.add('error'); + $lexerElem.classList.add('error'); + setParsed(error, error); + setScrollPercent(0); + }; + } + if (message.task !== 'defaults') { + markedWorker.working = true; + workerTimeout(0); + } + markedWorker.postMessage(message); +} + +function workerTimeout(seconds) { + markedWorker.timeout = setTimeout(function () { + seconds++; + markedWorker.onerror('Marked has taken longer than ' + seconds + ' second' + (seconds > 1 ? 's' : '') + ' to respond...'); + workerTimeout(seconds); + }, 1000); +} diff --git a/packages/markdown/marked/docs/demo/index.html b/packages/markdown/marked/docs/demo/index.html new file mode 100644 index 00000000..96a8ec14 --- /dev/null +++ b/packages/markdown/marked/docs/demo/index.html @@ -0,0 +1,78 @@ + + + + + Marked Demo + + + + + + Fork me on GitHub + + +
+ + + +

Marked Demo

+
+ +
Loading...
+
+
+
+
+ Input · + · + Version: + + · + + +
+ + +
+ +
+
+ · + Response Time: + +
+ +
+ + +
+ + + + + + +
+
+
+ + + + + + + diff --git a/packages/markdown/marked/docs/demo/initial.md b/packages/markdown/marked/docs/demo/initial.md new file mode 100644 index 00000000..d2b7d77c --- /dev/null +++ b/packages/markdown/marked/docs/demo/initial.md @@ -0,0 +1,36 @@ +Marked - Markdown Parser +======================== + +[Marked] lets you convert [Markdown] into HTML. Markdown is a simple text format whose goal is to be very easy to read and write, even when not converted to HTML. This demo page will let you type anything you like and see how it gets converted. Live. No more waiting around. + +How To Use The Demo +------------------- + +1. Type in stuff on the left. +2. See the live updates on the right. + +That's it. Pretty simple. There's also a drop-down option in the upper right to switch between various views: + +- **Preview:** A live display of the generated HTML as it would render in a browser. +- **HTML Source:** The generated HTML before your browser makes it pretty. +- **Lexer Data:** What [marked] uses internally, in case you like gory stuff like this. +- **Quick Reference:** A brief run-down of how to format things using markdown. + +Why Markdown? +------------- + +It's easy. It's not overly bloated, unlike HTML. Also, as the creator of [markdown] says, + +> The overriding design goal for Markdown's +> formatting syntax is to make it as readable +> as possible. The idea is that a +> Markdown-formatted document should be +> publishable as-is, as plain text, without +> looking like it's been marked up with tags +> or formatting instructions. + +Ready to start writing? Either start changing stuff on the left or +[clear everything](/demo/?text=) with a simple click. + +[Marked]: https://github.com/markedjs/marked/ +[Markdown]: http://daringfireball.net/projects/markdown/ diff --git a/packages/markdown/marked/docs/demo/preview.html b/packages/markdown/marked/docs/demo/preview.html new file mode 100644 index 00000000..7e8c89fe --- /dev/null +++ b/packages/markdown/marked/docs/demo/preview.html @@ -0,0 +1,12 @@ + + + + + + marked.js preview + + + + + + diff --git a/packages/markdown/marked/docs/demo/quickref.md b/packages/markdown/marked/docs/demo/quickref.md new file mode 100644 index 00000000..10f09bda --- /dev/null +++ b/packages/markdown/marked/docs/demo/quickref.md @@ -0,0 +1,167 @@ +Markdown Quick Reference +======================== + +This guide is a very brief overview, with examples, of the syntax that [Markdown] supports. It is itself written in Markdown and you can copy the samples over to the left-hand pane for experimentation. It's shown as *text* and not *rendered HTML*. + +[Markdown]: http://daringfireball.net/projects/markdown/ + + +Simple Text Formatting +====================== + +First thing is first. You can use *stars* or _underscores_ for italics. **Double stars** and __double underscores__ do bold. ***Three together*** do ___both___. + +Paragraphs are pretty easy too. Just have a blank line between chunks of text. + +> This chunk of text is in a block quote. Its multiple lines will all be +> indended a bit from the rest of the text. +> +> > Multiple levels of block quotes also work. + +Sometimes you want to include some code, such as when you are explaining how `

` HTML tags work, or maybe you are a programmer and you are discussing `someMethod()`. + +If you want to include some code and have +newlines preserved, indent the line with a tab +or at least four spaces. + Extra spaces work here too. +This is also called preformatted text and it is useful for showing examples. +The text will stay as text, so any *markdown* or HTML you add will +not show up formatted. This way you can show markdown examples in a +markdown document. + +> You can also use preformatted text with your blockquotes +> as long as you add at least five spaces. + + +Headings +======== + +There are a couple of ways to make headings. Using three or more equals signs on a line under a heading makes it into an "h1" style. Three or more hyphens under a line makes it "h2" (slightly smaller). You can also use multiple pound symbols before and after a heading. Pounds after the title are ignored. Here's some examples: + +This is H1 +========== + +This is H2 +---------- + +# This is H1 +## This is H2 +### This is H3 with some extra pounds ### +#### You get the idea #### +##### I don't need extra pounds at the end +###### H6 is the max + + +Links +===== + +Let's link to a few sites. First, let's use the bare URL, like . Great for text, but ugly for HTML. +Next is an inline link to [Google](http://www.google.com). A little nicer. +This is a reference-style link to [Wikipedia] [1]. +Lastly, here's a pretty link to [Yahoo]. The reference-style and pretty links both automatically use the links defined below, but they could be defined *anywhere* in the markdown and are removed from the HTML. The names are also case insensitive, so you can use [YaHoO] and have it link properly. + +[1]: http://www.wikipedia.org/ +[Yahoo]: http://www.yahoo.com/ + +Title attributes may be added to links by adding text after a link. +This is the [inline link](http://www.bing.com "Bing") with a "Bing" title. +You can also go to [W3C] [2] and maybe visit a [friend]. + +[2]: http://w3c.org (The W3C puts out specs for web-based things) +[Friend]: http://facebook.com/ "Facebook!" + +Email addresses in plain text are not linked: test@example.com. +Email addresses wrapped in angle brackets are linked: . +They are also obfuscated so that email harvesting spam robots hopefully won't get them. + + +Lists +===== + +* This is a bulleted list +* Great for shopping lists +- You can also use hyphens ++ Or plus symbols + +The above is an "unordered" list. Now, on for a bit of order. + +1. Numbered lists are also easy +2. Just start with a number +3738762. However, the actual number doesn't matter when converted to HTML. +1. This will still show up as 4. + +You might want a few advanced lists: + +- This top-level list is wrapped in paragraph tags +- This generates an extra space between each top-level item. + +- You do it by adding a blank line + +- This nested list also has blank lines between the list items. + +- How to create nested lists +1. Start your regular list +2. Indent nested lists with four spaces +3. Further nesting means you should indent with four more spaces + * This line is indented with eight spaces. + +- List items can be quite lengthy. You can keep typing and either continue +them on the next line with no indentation. + +- Alternately, if that looks ugly, you can also +indent the next line a bit for a prettier look. + +- You can put large blocks of text in your list by just indenting with four spaces. + +This is formatted the same as code, but you can inspect the HTML +and find that it's just wrapped in a `

` tag and *won't* be shown +as preformatted text. + +You can keep adding more and more paragraphs to a single +list item by adding the traditional blank line and then keep +on indenting the paragraphs with four spaces. You really need +to only indent the first line, but that looks ugly. + +- Lists support blockquotes + +> Just like this example here. By the way, you can +> nest lists inside blockquotes! +> - Fantastic! + +- Lists support preformatted text + + You just need to indent eight spaces. + + +Even More +========= + +Horizontal Rule +--------------- + +If you need a horizontal rule you just need to put at least three hyphens, asterisks, or underscores on a line by themselves. You can also even put spaces between the characters. + +--- +**************************** +_ _ _ _ _ _ _ + +Those three all produced horizontal lines. Keep in mind that three hyphens under any text turns that text into a heading, so add a blank like if you use hyphens. + +Images +------ + +Images work exactly like links, but they have exclamation points in front. They work with references and titles too. + +![Google Logo](http://www.google.com/images/errors/logo_sm.gif) and ![Happy]. + +[Happy]: http://www.wpclipart.com/smiley/simple_smiley/smiley_face_simple_green_small.png ("Smiley face") + + +Inline HTML +----------- + +If markdown is too limiting, you can just insert your own crazy HTML. Span-level HTML can *still* use markdown. Block level elements must be separated from text by a blank line and must not have any spaces before the opening and closing HTML. + +

+It is a pity, but markdown does **not** work in here for most markdown parsers. [Marked] handles it pretty well. +
diff --git a/packages/markdown/marked/docs/demo/worker.js b/packages/markdown/marked/docs/demo/worker.js new file mode 100644 index 00000000..06b8befe --- /dev/null +++ b/packages/markdown/marked/docs/demo/worker.js @@ -0,0 +1,105 @@ +/* globals marked, unfetch, ES6Promise */ +if (!self.Promise) { + self.importScripts('https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.js'); + self.Promise = ES6Promise; +} +if (!self.fetch) { + self.importScripts('https://cdn.jsdelivr.net/npm/unfetch/dist/unfetch.umd.js'); + self.fetch = unfetch; +} + +var versionCache = {}; +var currentVersion; + +onunhandledrejection = function (e) { + throw e.reason; +}; + +onmessage = function (e) { + if (e.data.version === currentVersion) { + parse(e); + } else { + loadVersion(e.data.version).then(function () { + parse(e); + }); + } +}; + +function parse(e) { + switch (e.data.task) { + case 'defaults': + + var defaults = {}; + if (typeof marked.getDefaults === 'function') { + defaults = marked.getDefaults(); + delete defaults.renderer; + } else if ('defaults' in marked) { + for (var prop in marked.defaults) { + if (prop !== 'renderer') { + defaults[prop] = marked.defaults[prop]; + } + } + } + postMessage({ + task: e.data.task, + defaults: defaults + }); + break; + case 'parse': + var startTime = new Date(); + var lexed = marked.lexer(e.data.markdown, e.data.options); + var lexedList = []; + for (var i = 0; i < lexed.length; i++) { + var lexedLine = []; + for (var j in lexed[i]) { + lexedLine.push(j + ':' + jsonString(lexed[i][j])); + } + lexedList.push('{' + lexedLine.join(', ') + '}'); + } + var parsed = marked.parser(lexed, e.data.options); + var endTime = new Date(); + // setTimeout(function () { + postMessage({ + task: e.data.task, + lexed: lexedList.join('\n'), + parsed: parsed, + time: endTime - startTime + }); + // }, 10000); + break; + } +} + +function jsonString(input) { + var output = (input + '') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\t/g, '\\t') + .replace(/\f/g, '\\f') + .replace(/[\\"']/g, '\\$&') + .replace(/\u0000/g, '\\0'); + return '"' + output + '"'; +}; + +function loadVersion(ver) { + var promise; + if (versionCache[ver]) { + promise = Promise.resolve(versionCache[ver]); + } else { + promise = fetch(ver) + .then(function (res) { return res.text(); }) + .then(function (text) { + versionCache[ver] = text; + return text; + }); + } + return promise.then(function (text) { + try { + // eslint-disable-next-line no-new-func + Function(text)(); + } catch (err) { + throw new Error('Cannot load that version of marked'); + } + currentVersion = ver; + }); +} diff --git a/packages/markdown/marked/docs/img/logo-black-and-white.svg b/packages/markdown/marked/docs/img/logo-black-and-white.svg new file mode 100644 index 00000000..5f6c0b78 --- /dev/null +++ b/packages/markdown/marked/docs/img/logo-black-and-white.svg @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/markdown/marked/docs/img/logo-black.svg b/packages/markdown/marked/docs/img/logo-black.svg new file mode 100644 index 00000000..a67fb80e --- /dev/null +++ b/packages/markdown/marked/docs/img/logo-black.svg @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/markdown/marked/docs/index.html b/packages/markdown/marked/docs/index.html new file mode 100644 index 00000000..07a4d5ee --- /dev/null +++ b/packages/markdown/marked/docs/index.html @@ -0,0 +1,269 @@ + + + + + Marked.js Documentation + + + + + + +
+
+ + + +

Marked.js Documentation

+
+ +
+ + + + + + diff --git a/packages/markdown/marked/index.js b/packages/markdown/marked/index.js new file mode 100644 index 00000000..a12f9056 --- /dev/null +++ b/packages/markdown/marked/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/marked'); diff --git a/packages/markdown/marked/jasmine.json b/packages/markdown/marked/jasmine.json new file mode 100644 index 00000000..bec42542 --- /dev/null +++ b/packages/markdown/marked/jasmine.json @@ -0,0 +1,11 @@ +{ + "spec_dir": "test", + "spec_files": [ + "**/*-spec.js" + ], + "helpers": [ + "helpers/helpers.js" + ], + "stopSpecOnExpectationFailure": false, + "random": true +} diff --git a/packages/markdown/marked/lib/marked.js b/packages/markdown/marked/lib/marked.js new file mode 100644 index 00000000..39c25f26 --- /dev/null +++ b/packages/markdown/marked/lib/marked.js @@ -0,0 +1,1689 @@ +/** + * marked - a markdown parser + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ + +;(function(root) { +'use strict'; + +/** + * Block-Level Grammar + */ + +var block = { + newline: /^\n+/, + code: /^( {4}[^\n]+\n*)+/, + fences: noop, + hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/, + heading: /^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/, + nptable: noop, + blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/, + list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, + html: '^ {0,3}(?:' // optional indentation + + '<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)' // (1) + + '|comment[^\\n]*(\\n+|$)' // (2) + + '|<\\?[\\s\\S]*?\\?>\\n*' // (3) + + '|\\n*' // (4) + + '|\\n*' // (5) + + '|)[\\s\\S]*?(?:\\n{2,}|$)' // (6) + + '|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) open tag + + '|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)' // (7) closing tag + + ')', + def: /^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/, + table: noop, + lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, + paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/, + text: /^[^\n]+/ +}; + +block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/; +block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/; +block.def = edit(block.def) + .replace('label', block._label) + .replace('title', block._title) + .getRegex(); + +block.bullet = /(?:[*+-]|\d{1,9}\.)/; +block.item = /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/; +block.item = edit(block.item, 'gm') + .replace(/bull/g, block.bullet) + .getRegex(); + +block.list = edit(block.list) + .replace(/bull/g, block.bullet) + .replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))') + .replace('def', '\\n+(?=' + block.def.source + ')') + .getRegex(); + +block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' + + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' + + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' + + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' + + '|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' + + '|track|ul'; +block._comment = //; +block.html = edit(block.html, 'i') + .replace('comment', block._comment) + .replace('tag', block._tag) + .replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/) + .getRegex(); + +block.paragraph = edit(block.paragraph) + .replace('hr', block.hr) + .replace('heading', block.heading) + .replace('lheading', block.lheading) + .replace('tag', block._tag) // pars can be interrupted by type (6) html blocks + .getRegex(); + +block.blockquote = edit(block.blockquote) + .replace('paragraph', block.paragraph) + .getRegex(); + +/** + * Normal Block Grammar + */ + +block.normal = merge({}, block); + +/** + * GFM Block Grammar + */ + +block.gfm = merge({}, block.normal, { + fences: /^ {0,3}(`{3,}|~{3,})([^`\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/, + paragraph: /^/, + heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ +}); + +block.gfm.paragraph = edit(block.paragraph) + .replace('(?!', '(?!' + + block.gfm.fences.source.replace('\\1', '\\2') + '|' + + block.list.source.replace('\\1', '\\3') + '|') + .getRegex(); + +/** + * GFM + Tables Block Grammar + */ + +block.tables = merge({}, block.gfm, { + nptable: /^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/, + table: /^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/ +}); + +/** + * Pedantic grammar + */ + +block.pedantic = merge({}, block.normal, { + html: edit( + '^ *(?:comment *(?:\\n|\\s*$)' + + '|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)' // closed tag + + '|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))') + .replace('comment', block._comment) + .replace(/tag/g, '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' + + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' + + '\\b)\\w+(?!:|[^\\w\\s@]*@)\\b') + .getRegex(), + def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/ +}); + +/** + * Block Lexer + */ + +function Lexer(options) { + this.tokens = []; + this.tokens.links = Object.create(null); + this.options = options || marked.defaults; + this.rules = block.normal; + + if (this.options.pedantic) { + this.rules = block.pedantic; + } else if (this.options.gfm) { + if (this.options.tables) { + this.rules = block.tables; + } else { + this.rules = block.gfm; + } + } +} + +/** + * Expose Block Rules + */ + +Lexer.rules = block; + +/** + * Static Lex Method + */ + +Lexer.lex = function(src, options) { + var lexer = new Lexer(options); + return lexer.lex(src); +}; + +/** + * Preprocessing + */ + +Lexer.prototype.lex = function(src) { + src = src + .replace(/\r\n|\r/g, '\n') + .replace(/\t/g, ' ') + .replace(/\u00a0/g, ' ') + .replace(/\u2424/g, '\n'); + + return this.token(src, true); +}; + +/** + * Lexing + */ + +Lexer.prototype.token = function(src, top) { + src = src.replace(/^ +$/gm, ''); + var next, + loose, + cap, + bull, + b, + item, + listStart, + listItems, + t, + space, + i, + tag, + l, + isordered, + istask, + ischecked; + + while (src) { + // newline + if (cap = this.rules.newline.exec(src)) { + src = src.substring(cap[0].length); + if (cap[0].length > 1) { + this.tokens.push({ + type: 'space' + }); + } + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + cap = cap[0].replace(/^ {4}/gm, ''); + this.tokens.push({ + type: 'code', + text: !this.options.pedantic + ? rtrim(cap, '\n') + : cap + }); + continue; + } + + // fences (gfm) + if (cap = this.rules.fences.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'code', + lang: cap[2] ? cap[2].trim() : cap[2], + text: cap[3] || '' + }); + continue; + } + + // heading + if (cap = this.rules.heading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[1].length, + text: cap[2] + }); + continue; + } + + // table no leading pipe (gfm) + if (cap = this.rules.nptable.exec(src)) { + item = { + type: 'table', + header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [] + }; + + if (item.header.length === item.align.length) { + src = src.substring(cap[0].length); + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = splitCells(item.cells[i], item.header.length); + } + + this.tokens.push(item); + + continue; + } + } + + // hr + if (cap = this.rules.hr.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'hr' + }); + continue; + } + + // blockquote + if (cap = this.rules.blockquote.exec(src)) { + src = src.substring(cap[0].length); + + this.tokens.push({ + type: 'blockquote_start' + }); + + cap = cap[0].replace(/^ *> ?/gm, ''); + + // Pass `top` to keep the current + // "toplevel" state. This is exactly + // how markdown.pl works. + this.token(cap, top); + + this.tokens.push({ + type: 'blockquote_end' + }); + + continue; + } + + // list + if (cap = this.rules.list.exec(src)) { + src = src.substring(cap[0].length); + bull = cap[2]; + isordered = bull.length > 1; + + listStart = { + type: 'list_start', + ordered: isordered, + start: isordered ? +bull : '', + loose: false + }; + + this.tokens.push(listStart); + + // Get each top-level item. + cap = cap[0].match(this.rules.item); + + listItems = []; + next = false; + l = cap.length; + i = 0; + + for (; i < l; i++) { + item = cap[i]; + + // Remove the list item's bullet + // so it is seen as the next token. + space = item.length; + item = item.replace(/^ *([*+-]|\d+\.) */, ''); + + // Outdent whatever the + // list item contains. Hacky. + if (~item.indexOf('\n ')) { + space -= item.length; + item = !this.options.pedantic + ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') + : item.replace(/^ {1,4}/gm, ''); + } + + // Determine whether the next list item belongs here. + // Backpedal if it does not belong in this list. + if (i !== l - 1) { + b = block.bullet.exec(cap[i + 1])[0]; + if (bull.length > 1 ? b.length === 1 + : (b.length > 1 || (this.options.smartLists && b !== bull))) { + src = cap.slice(i + 1).join('\n') + src; + i = l - 1; + } + } + + // Determine whether item is loose or not. + // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ + // for discount behavior. + loose = next || /\n\n(?!\s*$)/.test(item); + if (i !== l - 1) { + next = item.charAt(item.length - 1) === '\n'; + if (!loose) loose = next; + } + + if (loose) { + listStart.loose = true; + } + + // Check for task list items + istask = /^\[[ xX]\] /.test(item); + ischecked = undefined; + if (istask) { + ischecked = item[1] !== ' '; + item = item.replace(/^\[[ xX]\] +/, ''); + } + + t = { + type: 'list_item_start', + task: istask, + checked: ischecked, + loose: loose + }; + + listItems.push(t); + this.tokens.push(t); + + // Recurse. + this.token(item, false); + + this.tokens.push({ + type: 'list_item_end' + }); + } + + if (listStart.loose) { + l = listItems.length; + i = 0; + for (; i < l; i++) { + listItems[i].loose = true; + } + } + + this.tokens.push({ + type: 'list_end' + }); + + continue; + } + + // html + if (cap = this.rules.html.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: this.options.sanitize + ? 'paragraph' + : 'html', + pre: !this.options.sanitizer + && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), + text: cap[0] + }); + continue; + } + + // def + if (top && (cap = this.rules.def.exec(src))) { + src = src.substring(cap[0].length); + if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1); + tag = cap[1].toLowerCase().replace(/\s+/g, ' '); + if (!this.tokens.links[tag]) { + this.tokens.links[tag] = { + href: cap[2], + title: cap[3] + }; + } + continue; + } + + // table (gfm) + if (cap = this.rules.table.exec(src)) { + item = { + type: 'table', + header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : [] + }; + + if (item.header.length === item.align.length) { + src = src.substring(cap[0].length); + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = splitCells( + item.cells[i].replace(/^ *\| *| *\| *$/g, ''), + item.header.length); + } + + this.tokens.push(item); + + continue; + } + } + + // lheading + if (cap = this.rules.lheading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[2] === '=' ? 1 : 2, + text: cap[1] + }); + continue; + } + + // top-level paragraph + if (top && (cap = this.rules.paragraph.exec(src))) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'paragraph', + text: cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1] + }); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + // Top-level should never reach here. + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'text', + text: cap[0] + }); + continue; + } + + if (src) { + throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return this.tokens; +}; + +/** + * Inline-Level Grammar + */ + +var inline = { + escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, + autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, + url: noop, + tag: '^comment' + + '|^' // self-closing tag + + '|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' // open tag + + '|^<\\?[\\s\\S]*?\\?>' // processing instruction, e.g. + + '|^' // declaration, e.g. + + '|^', // CDATA section + link: /^!?\[(label)\]\(href(?:\s+(title))?\s*\)/, + reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/, + nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/, + strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/, + em: /^_([^\s_])_(?!_)|^\*([^\s*"<\[])\*(?!\*)|^_([^\s][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s"<\[][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/, + code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, + br: /^( {2,}|\\)\n(?!\s*$)/, + del: noop, + text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\?@\\[^_{|}~'; +inline.em = edit(inline.em).replace(/punctuation/g, inline._punctuation).getRegex(); + +inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g; + +inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/; +inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/; +inline.autolink = edit(inline.autolink) + .replace('scheme', inline._scheme) + .replace('email', inline._email) + .getRegex(); + +inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/; + +inline.tag = edit(inline.tag) + .replace('comment', block._comment) + .replace('attribute', inline._attribute) + .getRegex(); + +inline._label = /(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|`(?!`)|[^\[\]\\`])*?/; +inline._href = /\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)/; +inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/; + +inline.link = edit(inline.link) + .replace('label', inline._label) + .replace('href', inline._href) + .replace('title', inline._title) + .getRegex(); + +inline.reflink = edit(inline.reflink) + .replace('label', inline._label) + .getRegex(); + +/** + * Normal Inline Grammar + */ + +inline.normal = merge({}, inline); + +/** + * Pedantic Inline Grammar + */ + +inline.pedantic = merge({}, inline.normal, { + strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, + em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/, + link: edit(/^!?\[(label)\]\((.*?)\)/) + .replace('label', inline._label) + .getRegex(), + reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/) + .replace('label', inline._label) + .getRegex() +}); + +/** + * GFM Inline Grammar + */ + +inline.gfm = merge({}, inline.normal, { + escape: edit(inline.escape).replace('])', '~|])').getRegex(), + _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/, + url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, + _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/, + del: /^~+(?=\S)([\s\S]*?\S)~+/, + text: /^(`+|[^`])(?:[\s\S]*?(?:(?=[\\/i.test(cap[0])) { + this.inLink = false; + } + if (!this.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.inRawBlock = true; + } else if (this.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) { + this.inRawBlock = false; + } + + src = src.substring(cap[0].length); + out += this.options.sanitize + ? this.options.sanitizer + ? this.options.sanitizer(cap[0]) + : escape(cap[0]) + : cap[0]; + continue; + } + + // link + if (cap = this.rules.link.exec(src)) { + var lastParenIndex = findClosingBracket(cap[2], '()'); + if (lastParenIndex > -1) { + var linkLen = cap[0].length - (cap[2].length - lastParenIndex) - (cap[3] || '').length; + cap[2] = cap[2].substring(0, lastParenIndex); + cap[0] = cap[0].substring(0, linkLen).trim(); + cap[3] = ''; + } + src = src.substring(cap[0].length); + this.inLink = true; + href = cap[2]; + if (this.options.pedantic) { + link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href); + + if (link) { + href = link[1]; + title = link[3]; + } else { + title = ''; + } + } else { + title = cap[3] ? cap[3].slice(1, -1) : ''; + } + href = href.trim().replace(/^<([\s\S]*)>$/, '$1'); + out += this.outputLink(cap, { + href: InlineLexer.escapes(href), + title: InlineLexer.escapes(title) + }); + this.inLink = false; + continue; + } + + // reflink, nolink + if ((cap = this.rules.reflink.exec(src)) + || (cap = this.rules.nolink.exec(src))) { + src = src.substring(cap[0].length); + link = (cap[2] || cap[1]).replace(/\s+/g, ' '); + link = this.links[link.toLowerCase()]; + if (!link || !link.href) { + out += cap[0].charAt(0); + src = cap[0].substring(1) + src; + continue; + } + this.inLink = true; + out += this.outputLink(cap, link); + this.inLink = false; + continue; + } + + // strong + if (cap = this.rules.strong.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1])); + continue; + } + + // em + if (cap = this.rules.em.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1])); + continue; + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.codespan(escape(cap[2].trim(), true)); + continue; + } + + // br + if (cap = this.rules.br.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.br(); + continue; + } + + // del (gfm) + if (cap = this.rules.del.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.del(this.output(cap[1])); + continue; + } + + // autolink + if (cap = this.rules.autolink.exec(src)) { + src = src.substring(cap[0].length); + if (cap[2] === '@') { + text = escape(this.mangle(cap[1])); + href = 'mailto:' + text; + } else { + text = escape(cap[1]); + href = text; + } + out += this.renderer.link(href, null, text); + continue; + } + + // url (gfm) + if (!this.inLink && (cap = this.rules.url.exec(src))) { + if (cap[2] === '@') { + text = escape(cap[0]); + href = 'mailto:' + text; + } else { + // do extended autolink path validation + do { + prevCapZero = cap[0]; + cap[0] = this.rules._backpedal.exec(cap[0])[0]; + } while (prevCapZero !== cap[0]); + text = escape(cap[0]); + if (cap[1] === 'www.') { + href = 'http://' + text; + } else { + href = text; + } + } + src = src.substring(cap[0].length); + out += this.renderer.link(href, null, text); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + src = src.substring(cap[0].length); + if (this.inRawBlock) { + out += this.renderer.text(cap[0]); + } else { + out += this.renderer.text(escape(this.smartypants(cap[0]))); + } + continue; + } + + if (src) { + throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return out; +}; + +InlineLexer.escapes = function(text) { + return text ? text.replace(InlineLexer.rules._escapes, '$1') : text; +}; + +/** + * Compile Link + */ + +InlineLexer.prototype.outputLink = function(cap, link) { + var href = link.href, + title = link.title ? escape(link.title) : null; + + return cap[0].charAt(0) !== '!' + ? this.renderer.link(href, title, this.output(cap[1])) + : this.renderer.image(href, title, escape(cap[1])); +}; + +/** + * Smartypants Transformations + */ + +InlineLexer.prototype.smartypants = function(text) { + if (!this.options.smartypants) return text; + return text + // em-dashes + .replace(/---/g, '\u2014') + // en-dashes + .replace(/--/g, '\u2013') + // opening singles + .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') + // closing singles & apostrophes + .replace(/'/g, '\u2019') + // opening doubles + .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') + // closing doubles + .replace(/"/g, '\u201d') + // ellipses + .replace(/\.{3}/g, '\u2026'); +}; + +/** + * Mangle Links + */ + +InlineLexer.prototype.mangle = function(text) { + if (!this.options.mangle) return text; + var out = '', + l = text.length, + i = 0, + ch; + + for (; i < l; i++) { + ch = text.charCodeAt(i); + if (Math.random() > 0.5) { + ch = 'x' + ch.toString(16); + } + out += '&#' + ch + ';'; + } + + return out; +}; + +/** + * Renderer + */ + +function Renderer(options) { + this.options = options || marked.defaults; +} + +Renderer.prototype.code = function(code, infostring, escaped) { + var lang = (infostring || '').match(/\S*/)[0]; + if (this.options.highlight) { + var out = this.options.highlight(code, lang); + if (out != null && out !== code) { + escaped = true; + code = out; + } + } + + if (!lang) { + return '
'
+      + (escaped ? code : escape(code, true))
+      + '
'; + } + + return '
'
+    + (escaped ? code : escape(code, true))
+    + '
\n'; +}; + +Renderer.prototype.blockquote = function(quote) { + return '
\n' + quote + '
\n'; +}; + +Renderer.prototype.html = function(html) { + return html; +}; + +Renderer.prototype.heading = function(text, level, raw, slugger) { + if (this.options.headerIds) { + return '' + + text + + '\n'; + } + // ignore IDs + return '' + text + '\n'; +}; + +Renderer.prototype.hr = function() { + return this.options.xhtml ? '
\n' : '
\n'; +}; + +Renderer.prototype.list = function(body, ordered, start) { + var type = ordered ? 'ol' : 'ul', + startatt = (ordered && start !== 1) ? (' start="' + start + '"') : ''; + return '<' + type + startatt + '>\n' + body + '\n'; +}; + +Renderer.prototype.listitem = function(text) { + return '
  • ' + text + '
  • \n'; +}; + +Renderer.prototype.checkbox = function(checked) { + return ' '; +}; + +Renderer.prototype.paragraph = function(text) { + return '

    ' + text + '

    \n'; +}; + +Renderer.prototype.table = function(header, body) { + if (body) body = '' + body + ''; + + return '\n' + + '\n' + + header + + '\n' + + body + + '
    \n'; +}; + +Renderer.prototype.tablerow = function(content) { + return '\n' + content + '\n'; +}; + +Renderer.prototype.tablecell = function(content, flags) { + var type = flags.header ? 'th' : 'td'; + var tag = flags.align + ? '<' + type + ' align="' + flags.align + '">' + : '<' + type + '>'; + return tag + content + '\n'; +}; + +// span level renderer +Renderer.prototype.strong = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.em = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.codespan = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.br = function() { + return this.options.xhtml ? '
    ' : '
    '; +}; + +Renderer.prototype.del = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.link = function(href, title, text) { + href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); + if (href === null) { + return text; + } + var out = ''; + return out; +}; + +Renderer.prototype.image = function(href, title, text) { + href = cleanUrl(this.options.sanitize, this.options.baseUrl, href); + if (href === null) { + return text; + } + + var out = '' + text + '' : '>'; + return out; +}; + +Renderer.prototype.text = function(text) { + return text; +}; + +/** + * TextRenderer + * returns only the textual part of the token + */ + +function TextRenderer() {} + +// no need for block level renderers + +TextRenderer.prototype.strong = +TextRenderer.prototype.em = +TextRenderer.prototype.codespan = +TextRenderer.prototype.del = +TextRenderer.prototype.text = function (text) { + return text; +}; + +TextRenderer.prototype.link = +TextRenderer.prototype.image = function(href, title, text) { + return '' + text; +}; + +TextRenderer.prototype.br = function() { + return ''; +}; + +/** + * Parsing & Compiling + */ + +function Parser(options) { + this.tokens = []; + this.token = null; + this.options = options || marked.defaults; + this.options.renderer = this.options.renderer || new Renderer(); + this.renderer = this.options.renderer; + this.renderer.options = this.options; + this.slugger = new Slugger(); +} + +/** + * Static Parse Method + */ + +Parser.parse = function(src, options) { + var parser = new Parser(options); + return parser.parse(src); +}; + +/** + * Parse Loop + */ + +Parser.prototype.parse = function(src) { + this.inline = new InlineLexer(src.links, this.options); + // use an InlineLexer with a TextRenderer to extract pure text + this.inlineText = new InlineLexer( + src.links, + merge({}, this.options, {renderer: new TextRenderer()}) + ); + this.tokens = src.reverse(); + + var out = ''; + while (this.next()) { + out += this.tok(); + } + + return out; +}; + +/** + * Next Token + */ + +Parser.prototype.next = function() { + return this.token = this.tokens.pop(); +}; + +/** + * Preview Next Token + */ + +Parser.prototype.peek = function() { + return this.tokens[this.tokens.length - 1] || 0; +}; + +/** + * Parse Text Tokens + */ + +Parser.prototype.parseText = function() { + var body = this.token.text; + + while (this.peek().type === 'text') { + body += '\n' + this.next().text; + } + + return this.inline.output(body); +}; + +/** + * Parse Current Token + */ + +Parser.prototype.tok = function() { + switch (this.token.type) { + case 'space': { + return ''; + } + case 'hr': { + return this.renderer.hr(); + } + case 'heading': { + return this.renderer.heading( + this.inline.output(this.token.text), + this.token.depth, + unescape(this.inlineText.output(this.token.text)), + this.slugger); + } + case 'code': { + return this.renderer.code(this.token.text, + this.token.lang, + this.token.escaped); + } + case 'table': { + var header = '', + body = '', + i, + row, + cell, + j; + + // header + cell = ''; + for (i = 0; i < this.token.header.length; i++) { + cell += this.renderer.tablecell( + this.inline.output(this.token.header[i]), + { header: true, align: this.token.align[i] } + ); + } + header += this.renderer.tablerow(cell); + + for (i = 0; i < this.token.cells.length; i++) { + row = this.token.cells[i]; + + cell = ''; + for (j = 0; j < row.length; j++) { + cell += this.renderer.tablecell( + this.inline.output(row[j]), + { header: false, align: this.token.align[j] } + ); + } + + body += this.renderer.tablerow(cell); + } + return this.renderer.table(header, body); + } + case 'blockquote_start': { + body = ''; + + while (this.next().type !== 'blockquote_end') { + body += this.tok(); + } + + return this.renderer.blockquote(body); + } + case 'list_start': { + body = ''; + var ordered = this.token.ordered, + start = this.token.start; + + while (this.next().type !== 'list_end') { + body += this.tok(); + } + + return this.renderer.list(body, ordered, start); + } + case 'list_item_start': { + body = ''; + var loose = this.token.loose; + var checked = this.token.checked; + var task = this.token.task; + + if (this.token.task) { + body += this.renderer.checkbox(checked); + } + + while (this.next().type !== 'list_item_end') { + body += !loose && this.token.type === 'text' + ? this.parseText() + : this.tok(); + } + return this.renderer.listitem(body, task, checked); + } + case 'html': { + // TODO parse inline content if parameter markdown=1 + return this.renderer.html(this.token.text); + } + case 'paragraph': { + return this.renderer.paragraph(this.inline.output(this.token.text)); + } + case 'text': { + return this.renderer.paragraph(this.parseText()); + } + default: { + var errMsg = 'Token with "' + this.token.type + '" type was not found.'; + if (this.options.silent) { + console.log(errMsg); + } else { + throw new Error(errMsg); + } + } + } +}; + +/** + * Slugger generates header id + */ + +function Slugger () { + this.seen = {}; +} + +/** + * Convert string to unique id + */ + +Slugger.prototype.slug = function (value) { + var slug = value + .toLowerCase() + .trim() + .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '') + .replace(/\s/g, '-'); + + if (this.seen.hasOwnProperty(slug)) { + var originalSlug = slug; + do { + this.seen[originalSlug]++; + slug = originalSlug + '-' + this.seen[originalSlug]; + } while (this.seen.hasOwnProperty(slug)); + } + this.seen[slug] = 0; + + return slug; +}; + +/** + * Helpers + */ + +function escape(html, encode) { + if (encode) { + if (escape.escapeTest.test(html)) { + return html.replace(escape.escapeReplace, function (ch) { return escape.replacements[ch]; }); + } + } else { + if (escape.escapeTestNoEncode.test(html)) { + return html.replace(escape.escapeReplaceNoEncode, function (ch) { return escape.replacements[ch]; }); + } + } + + return html; +} + +escape.escapeTest = /[&<>"']/; +escape.escapeReplace = /[&<>"']/g; +escape.replacements = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; + +escape.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/; +escape.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g; + +function unescape(html) { + // explicitly match decimal, hex, and named HTML entities + return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, function(_, n) { + n = n.toLowerCase(); + if (n === 'colon') return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)); + } + return ''; + }); +} + +function edit(regex, opt) { + regex = regex.source || regex; + opt = opt || ''; + return { + replace: function(name, val) { + val = val.source || val; + val = val.replace(/(^|[^\[])\^/g, '$1'); + regex = regex.replace(name, val); + return this; + }, + getRegex: function() { + return new RegExp(regex, opt); + } + }; +} + +function cleanUrl(sanitize, base, href) { + if (sanitize) { + try { + var prot = decodeURIComponent(unescape(href)) + .replace(/[^\w:]/g, '') + .toLowerCase(); + } catch (e) { + return null; + } + if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { + return null; + } + } + if (base && !originIndependentUrl.test(href)) { + href = resolveUrl(base, href); + } + try { + href = encodeURI(href).replace(/%25/g, '%'); + } catch (e) { + return null; + } + return href; +} + +function resolveUrl(base, href) { + if (!baseUrls[' ' + base]) { + // we can ignore everything in base after the last slash of its path component, + // but we might need to add _that_ + // https://tools.ietf.org/html/rfc3986#section-3 + if (/^[^:]+:\/*[^/]*$/.test(base)) { + baseUrls[' ' + base] = base + '/'; + } else { + baseUrls[' ' + base] = rtrim(base, '/', true); + } + } + base = baseUrls[' ' + base]; + + if (href.slice(0, 2) === '//') { + return base.replace(/:[\s\S]*/, ':') + href; + } else if (href.charAt(0) === '/') { + return base.replace(/(:\/*[^/]*)[\s\S]*/, '$1') + href; + } else { + return base + href; + } +} +var baseUrls = {}; +var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; + +function noop() {} +noop.exec = noop; + +function merge(obj) { + var i = 1, + target, + key; + + for (; i < arguments.length; i++) { + target = arguments[i]; + for (key in target) { + if (Object.prototype.hasOwnProperty.call(target, key)) { + obj[key] = target[key]; + } + } + } + + return obj; +} + +function splitCells(tableRow, count) { + // ensure that every cell-delimiting pipe has a space + // before it to distinguish it from an escaped pipe + var row = tableRow.replace(/\|/g, function (match, offset, str) { + var escaped = false, + curr = offset; + while (--curr >= 0 && str[curr] === '\\') escaped = !escaped; + if (escaped) { + // odd number of slashes means | is escaped + // so we leave it alone + return '|'; + } else { + // add space before unescaped | + return ' |'; + } + }), + cells = row.split(/ \|/), + i = 0; + + if (cells.length > count) { + cells.splice(count); + } else { + while (cells.length < count) cells.push(''); + } + + for (; i < cells.length; i++) { + // leading or trailing whitespace is ignored per the gfm spec + cells[i] = cells[i].trim().replace(/\\\|/g, '|'); + } + return cells; +} + +// Remove trailing 'c's. Equivalent to str.replace(/c*$/, ''). +// /c*$/ is vulnerable to REDOS. +// invert: Remove suffix of non-c chars instead. Default falsey. +function rtrim(str, c, invert) { + if (str.length === 0) { + return ''; + } + + // Length of suffix matching the invert condition. + var suffLen = 0; + + // Step left until we fail to match the invert condition. + while (suffLen < str.length) { + var currChar = str.charAt(str.length - suffLen - 1); + if (currChar === c && !invert) { + suffLen++; + } else if (currChar !== c && invert) { + suffLen++; + } else { + break; + } + } + + return str.substr(0, str.length - suffLen); +} + +function findClosingBracket(str, b) { + if (str.indexOf(b[1]) === -1) { + return -1; + } + var level = 0; + for (var i = 0; i < str.length; i++) { + if (str[i] === '\\') { + i++; + } else if (str[i] === b[0]) { + level++; + } else if (str[i] === b[1]) { + level--; + if (level < 0) { + return i; + } + } + } + return -1; +} + +/** + * Marked + */ + +function marked(src, opt, callback) { + // throw error in case of non string input + if (typeof src === 'undefined' || src === null) { + throw new Error('marked(): input parameter is undefined or null'); + } + if (typeof src !== 'string') { + throw new Error('marked(): input parameter is of type ' + + Object.prototype.toString.call(src) + ', string expected'); + } + + if (callback || typeof opt === 'function') { + if (!callback) { + callback = opt; + opt = null; + } + + opt = merge({}, marked.defaults, opt || {}); + + var highlight = opt.highlight, + tokens, + pending, + i = 0; + + try { + tokens = Lexer.lex(src, opt); + } catch (e) { + return callback(e); + } + + pending = tokens.length; + + var done = function(err) { + if (err) { + opt.highlight = highlight; + return callback(err); + } + + var out; + + try { + out = Parser.parse(tokens, opt); + } catch (e) { + err = e; + } + + opt.highlight = highlight; + + return err + ? callback(err) + : callback(null, out); + }; + + if (!highlight || highlight.length < 3) { + return done(); + } + + delete opt.highlight; + + if (!pending) return done(); + + for (; i < tokens.length; i++) { + (function(token) { + if (token.type !== 'code') { + return --pending || done(); + } + return highlight(token.text, token.lang, function(err, code) { + if (err) return done(err); + if (code == null || code === token.text) { + return --pending || done(); + } + token.text = code; + token.escaped = true; + --pending || done(); + }); + })(tokens[i]); + } + + return; + } + try { + if (opt) opt = merge({}, marked.defaults, opt); + return Parser.parse(Lexer.lex(src, opt), opt); + } catch (e) { + e.message += '\nPlease report this to https://github.com/markedjs/marked.'; + if ((opt || marked.defaults).silent) { + return '

    An error occurred:

    '
    +        + escape(e.message + '', true)
    +        + '
    '; + } + throw e; + } +} + +/** + * Options + */ + +marked.options = +marked.setOptions = function(opt) { + merge(marked.defaults, opt); + return marked; +}; + +marked.getDefaults = function () { + return { + baseUrl: null, + breaks: false, + gfm: true, + headerIds: true, + headerPrefix: '', + highlight: null, + langPrefix: 'language-', + mangle: true, + pedantic: false, + renderer: new Renderer(), + sanitize: false, + sanitizer: null, + silent: false, + smartLists: false, + smartypants: false, + tables: true, + xhtml: false + }; +}; + +marked.defaults = marked.getDefaults(); + +/** + * Expose + */ + +marked.Parser = Parser; +marked.parser = Parser.parse; + +marked.Renderer = Renderer; +marked.TextRenderer = TextRenderer; + +marked.Lexer = Lexer; +marked.lexer = Lexer.lex; + +marked.InlineLexer = InlineLexer; +marked.inlineLexer = InlineLexer.output; + +marked.Slugger = Slugger; + +marked.parse = marked; + +if (typeof module !== 'undefined' && typeof exports === 'object') { + module.exports = marked; +} else if (typeof define === 'function' && define.amd) { + define(function() { return marked; }); +} else { + root.marked = marked; +} +})(this || (typeof window !== 'undefined' ? window : global)); diff --git a/packages/markdown/marked/man/marked.1 b/packages/markdown/marked/man/marked.1 new file mode 100644 index 00000000..848b4424 --- /dev/null +++ b/packages/markdown/marked/man/marked.1 @@ -0,0 +1,114 @@ +.ds q \N'34' +.TH marked 1 + +.SH NAME +marked \- a javascript markdown parser + +.SH SYNOPSIS +.B marked +[\-o \fI\fP] [\-i \fI\fP] [\-\-help] +[\-\-tokens] [\-\-pedantic] [\-\-gfm] +[\-\-breaks] [\-\-tables] [\-\-sanitize] +[\-\-smart\-lists] [\-\-lang\-prefix \fI\fP] +[\-\-no\-etc...] [\-\-silent] [\fIfilename\fP] + +.SH DESCRIPTION +.B marked +is a full-featured javascript markdown parser, built for speed. +It also includes multiple GFM features. + +.SH EXAMPLES +.TP +cat in.md | marked > out.html +.TP +echo "hello *world*" | marked +.TP +marked \-o out.html \-i in.md \-\-gfm +.TP +marked \-\-output="hello world.html" \-i in.md \-\-no-breaks + +.SH OPTIONS +.TP +.BI \-o,\ \-\-output\ [\fIoutput\fP] +Specify file output. If none is specified, write to stdout. +.TP +.BI \-i,\ \-\-input\ [\fIinput\fP] +Specify file input, otherwise use last argument as input file. +If no input file is specified, read from stdin. +.TP +.BI \-\-test +Makes sure the test(s) pass. +.RS +.PP +.B \-\-glob [\fIfile\fP] +Specify which test to use. +.PP +.B \-\-fix +Fixes tests. +.PP +.B \-\-bench +Benchmarks the test(s). +.PP +.B \-\-time +Times The test(s). +.PP +.B \-\-minified +Runs test file(s) as minified. +.PP +.B \-\-stop +Stop process if a test fails. +.RE +.TP +.BI \-t,\ \-\-tokens +Output a token stream instead of html. +.TP +.BI \-\-pedantic +Conform to obscure parts of markdown.pl as much as possible. +Don't fix original markdown bugs. +.TP +.BI \-\-gfm +Enable github flavored markdown. +.TP +.BI \-\-breaks +Enable GFM line breaks. Only works with the gfm option. +.TP +.BI \-\-tables +Enable GFM tables. Only works with the gfm option. +.TP +.BI \-\-sanitize +Sanitize output. Ignore any HTML input. +.TP +.BI \-\-smart\-lists +Use smarter list behavior than the original markdown. +.TP +.BI \-\-lang\-prefix\ [\fIprefix\fP] +Set the prefix for code block classes. +.TP +.BI \-\-mangle +Mangle email addresses. +.TP +.BI \-\-no\-sanitize,\ \-no-etc... +The inverse of any of the marked options above. +.TP +.BI \-\-silent +Silence error output. +.TP +.BI \-h,\ \-\-help +Display help information. + +.SH CONFIGURATION +For configuring and running programmatically. + +.B Example + + require('marked')('*foo*', { gfm: true }); + +.SH BUGS +Please report any bugs to https://github.com/markedjs/marked. + +.SH LICENSE +Copyright (c) 2011-2014, Christopher Jeffrey (MIT License). + +.SH "SEE ALSO" +.BR markdown(1), +.BR node.js(1) diff --git a/packages/markdown/marked/man/marked.1.txt b/packages/markdown/marked/man/marked.1.txt new file mode 100644 index 00000000..ea07ad36 --- /dev/null +++ b/packages/markdown/marked/man/marked.1.txt @@ -0,0 +1,99 @@ +marked(1) General Commands Manual marked(1) + +NAME + marked - a javascript markdown parser + +SYNOPSIS + marked [-o ] [-i ] [--help] [--tokens] + [--pedantic] [--gfm] [--breaks] [--tables] [--sanitize] + [--smart-lists] [--lang-prefix ] [--no-etc...] [--silent] + [filename] + +DESCRIPTION + marked is a full-featured javascript markdown parser, built for speed. + It also includes multiple GFM features. + +EXAMPLES + cat in.md | marked > out.html + + echo "hello *world*" | marked + + marked -o out.html -i in.md --gfm + + marked --output="hello world.html" -i in.md --no-breaks + +OPTIONS + -o, --output [output] + Specify file output. If none is specified, write to stdout. + + -i, --input [input] + Specify file input, otherwise use last argument as input file. + If no input file is specified, read from stdin. + + --test Makes sure the test(s) pass. + + --glob [file] Specify which test to use. + + --fix Fixes tests. + + --bench Benchmarks the test(s). + + --time Times The test(s). + + --minified Runs test file(s) as minified. + + --stop Stop process if a test fails. + + -t, --tokens + Output a token stream instead of html. + + --pedantic + Conform to obscure parts of markdown.pl as much as possible. + Don't fix original markdown bugs. + + --gfm Enable github flavored markdown. + + --breaks + Enable GFM line breaks. Only works with the gfm option. + + --tables + Enable GFM tables. Only works with the gfm option. + + --sanitize + Sanitize output. Ignore any HTML input. + + --smart-lists + Use smarter list behavior than the original markdown. + + --lang-prefix [prefix] + Set the prefix for code block classes. + + --mangle + Mangle email addresses. + + --no-sanitize, -no-etc... + The inverse of any of the marked options above. + + --silent + Silence error output. + + -h, --help + Display help information. + +CONFIGURATION + For configuring and running programmatically. + + Example + + require('marked')('*foo*', { gfm: true }); + +BUGS + Please report any bugs to https://github.com/markedjs/marked. + +LICENSE + Copyright (c) 2011-2014, Christopher Jeffrey (MIT License). + +SEE ALSO + markdown(1), node.js(1) + + marked(1) diff --git a/packages/markdown/marked/marked.min.js b/packages/markdown/marked/marked.min.js new file mode 100644 index 00000000..085cfb56 --- /dev/null +++ b/packages/markdown/marked/marked.min.js @@ -0,0 +1,6 @@ +/** + * marked - a markdown parser + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ +!function(e){"use strict";var k={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:f,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,nptable:f,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?\\?>\\n*|\\n*|\\n*|)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,table:f,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,text:/^[^\n]+/};function a(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||b.defaults,this.rules=k.normal,this.options.pedantic?this.rules=k.pedantic:this.options.gfm&&(this.options.tables?this.rules=k.tables:this.rules=k.gfm)}k._label=/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,k._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,k.def=i(k.def).replace("label",k._label).replace("title",k._title).getRegex(),k.bullet=/(?:[*+-]|\d{1,9}\.)/,k.item=/^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/,k.item=i(k.item,"gm").replace(/bull/g,k.bullet).getRegex(),k.list=i(k.list).replace(/bull/g,k.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+k.def.source+")").getRegex(),k._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",k._comment=//,k.html=i(k.html,"i").replace("comment",k._comment).replace("tag",k._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),k.paragraph=i(k.paragraph).replace("hr",k.hr).replace("heading",k.heading).replace("lheading",k.lheading).replace("tag",k._tag).getRegex(),k.blockquote=i(k.blockquote).replace("paragraph",k.paragraph).getRegex(),k.normal=d({},k),k.gfm=d({},k.normal,{fences:/^ {0,3}(`{3,}|~{3,})([^`\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),k.gfm.paragraph=i(k.paragraph).replace("(?!","(?!"+k.gfm.fences.source.replace("\\1","\\2")+"|"+k.list.source.replace("\\1","\\3")+"|").getRegex(),k.tables=d({},k.gfm,{nptable:/^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,table:/^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/}),k.pedantic=d({},k.normal,{html:i("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",k._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/}),a.rules=k,a.lex=function(e,t){return new a(t).lex(e)},a.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},a.prototype.token=function(e,t){var n,r,s,i,l,o,a,h,p,u,c,g,f,d,m,b;for(e=e.replace(/^ +$/gm,"");e;)if((s=this.rules.newline.exec(e))&&(e=e.substring(s[0].length),1 ?/gm,""),this.token(s,t),this.tokens.push({type:"blockquote_end"});else if(s=this.rules.list.exec(e)){for(e=e.substring(s[0].length),a={type:"list_start",ordered:d=1<(i=s[2]).length,start:d?+i:"",loose:!1},this.tokens.push(a),n=!(h=[]),f=(s=s[0].match(this.rules.item)).length,c=0;c?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:f,tag:"^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^",link:/^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,strong:/^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,em:/^_([^\s_])_(?!_)|^\*([^\s*"<\[])\*(?!\*)|^_([^\s][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s"<\[][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:f,text:/^(`+|[^`])(?:[\s\S]*?(?:(?=[\\?@\\[^_{|}~",n.em=i(n.em).replace(/punctuation/g,n._punctuation).getRegex(),n._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,n._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,n._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,n.autolink=i(n.autolink).replace("scheme",n._scheme).replace("email",n._email).getRegex(),n._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,n.tag=i(n.tag).replace("comment",k._comment).replace("attribute",n._attribute).getRegex(),n._label=/(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|`(?!`)|[^\[\]\\`])*?/,n._href=/\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)/,n._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,n.link=i(n.link).replace("label",n._label).replace("href",n._href).replace("title",n._title).getRegex(),n.reflink=i(n.reflink).replace("label",n._label).getRegex(),n.normal=d({},n),n.pedantic=d({},n.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,link:i(/^!?\[(label)\]\((.*?)\)/).replace("label",n._label).getRegex(),reflink:i(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",n._label).getRegex()}),n.gfm=d({},n.normal,{escape:i(n.escape).replace("])","~|])").getRegex(),_extended_email:/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,url:/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^~+(?=\S)([\s\S]*?\S)~+/,text:/^(`+|[^`])(?:[\s\S]*?(?:(?=[\\/i.test(i[0])&&(this.inLink=!1),!this.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(i[0])?this.inRawBlock=!0:this.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(i[0])&&(this.inRawBlock=!1),e=e.substring(i[0].length),o+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(i[0]):u(i[0]):i[0];else if(i=this.rules.link.exec(e)){var a=m(i[2],"()");if(-1$/,"$1"),o+=this.outputLink(i,{href:p.escapes(r),title:p.escapes(s)}),this.inLink=!1}else if((i=this.rules.reflink.exec(e))||(i=this.rules.nolink.exec(e))){if(e=e.substring(i[0].length),t=(i[2]||i[1]).replace(/\s+/g," "),!(t=this.links[t.toLowerCase()])||!t.href){o+=i[0].charAt(0),e=i[0].substring(1)+e;continue}this.inLink=!0,o+=this.outputLink(i,t),this.inLink=!1}else if(i=this.rules.strong.exec(e))e=e.substring(i[0].length),o+=this.renderer.strong(this.output(i[4]||i[3]||i[2]||i[1]));else if(i=this.rules.em.exec(e))e=e.substring(i[0].length),o+=this.renderer.em(this.output(i[6]||i[5]||i[4]||i[3]||i[2]||i[1]));else if(i=this.rules.code.exec(e))e=e.substring(i[0].length),o+=this.renderer.codespan(u(i[2].trim(),!0));else if(i=this.rules.br.exec(e))e=e.substring(i[0].length),o+=this.renderer.br();else if(i=this.rules.del.exec(e))e=e.substring(i[0].length),o+=this.renderer.del(this.output(i[1]));else if(i=this.rules.autolink.exec(e))e=e.substring(i[0].length),r="@"===i[2]?"mailto:"+(n=u(this.mangle(i[1]))):n=u(i[1]),o+=this.renderer.link(r,null,n);else if(this.inLink||!(i=this.rules.url.exec(e))){if(i=this.rules.text.exec(e))e=e.substring(i[0].length),this.inRawBlock?o+=this.renderer.text(i[0]):o+=this.renderer.text(u(this.smartypants(i[0])));else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}else{if("@"===i[2])r="mailto:"+(n=u(i[0]));else{for(;l=i[0],i[0]=this.rules._backpedal.exec(i[0])[0],l!==i[0];);n=u(i[0]),r="www."===i[1]?"http://"+n:n}e=e.substring(i[0].length),o+=this.renderer.link(r,null,n)}return o},p.escapes=function(e){return e?e.replace(p.rules._escapes,"$1"):e},p.prototype.outputLink=function(e,t){var n=t.href,r=t.title?u(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,u(e[1]))},p.prototype.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e},p.prototype.mangle=function(e){if(!this.options.mangle)return e;for(var t,n="",r=e.length,s=0;s'+(n?e:u(e,!0))+"\n":"
    "+(n?e:u(e,!0))+"
    "},r.prototype.blockquote=function(e){return"
    \n"+e+"
    \n"},r.prototype.html=function(e){return e},r.prototype.heading=function(e,t,n,r){return this.options.headerIds?"'+e+"\n":""+e+"\n"},r.prototype.hr=function(){return this.options.xhtml?"
    \n":"
    \n"},r.prototype.list=function(e,t,n){var r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"\n"},r.prototype.listitem=function(e){return"
  • "+e+"
  • \n"},r.prototype.checkbox=function(e){return" "},r.prototype.paragraph=function(e){return"

    "+e+"

    \n"},r.prototype.table=function(e,t){return t&&(t=""+t+""),"\n\n"+e+"\n"+t+"
    \n"},r.prototype.tablerow=function(e){return"\n"+e+"\n"},r.prototype.tablecell=function(e,t){var n=t.header?"th":"td";return(t.align?"<"+n+' align="'+t.align+'">':"<"+n+">")+e+"\n"},r.prototype.strong=function(e){return""+e+""},r.prototype.em=function(e){return""+e+""},r.prototype.codespan=function(e){return""+e+""},r.prototype.br=function(){return this.options.xhtml?"
    ":"
    "},r.prototype.del=function(e){return""+e+""},r.prototype.link=function(e,t,n){if(null===(e=l(this.options.sanitize,this.options.baseUrl,e)))return n;var r='
    "},r.prototype.image=function(e,t,n){if(null===(e=l(this.options.sanitize,this.options.baseUrl,e)))return n;var r=''+n+'":">"},r.prototype.text=function(e){return e},s.prototype.strong=s.prototype.em=s.prototype.codespan=s.prototype.del=s.prototype.text=function(e){return e},s.prototype.link=s.prototype.image=function(e,t,n){return""+n},s.prototype.br=function(){return""},h.parse=function(e,t){return new h(t).parse(e)},h.prototype.parse=function(e){this.inline=new p(e.links,this.options),this.inlineText=new p(e.links,d({},this.options,{renderer:new s})),this.tokens=e.reverse();for(var t="";this.next();)t+=this.tok();return t},h.prototype.next=function(){return this.token=this.tokens.pop()},h.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},h.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},h.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,c(this.inlineText.output(this.token.text)),this.slugger);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,s="",i="";for(n="",e=0;e?@[\]^`{|}~]/g,"").replace(/\s/g,"-");if(this.seen.hasOwnProperty(t))for(var n=t;this.seen[n]++,t=n+"-"+this.seen[n],this.seen.hasOwnProperty(t););return this.seen[t]=0,t},u.escapeTest=/[&<>"']/,u.escapeReplace=/[&<>"']/g,u.replacements={"&":"&","<":"<",">":">",'"':""","'":"'"},u.escapeTestNoEncode=/[<>"']|&(?!#?\w+;)/,u.escapeReplaceNoEncode=/[<>"']|&(?!#?\w+;)/g;var o={},g=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function f(){}function d(e){for(var t,n,r=1;rt)n.splice(t);else for(;n.lengthAn error occurred:

    "+u(e.message+"",!0)+"
    ";throw e}}f.exec=f,b.options=b.setOptions=function(e){return d(b.defaults,e),b},b.getDefaults=function(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:new r,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tables:!0,xhtml:!1}},b.defaults=b.getDefaults(),b.Parser=h,b.parser=h.parse,b.Renderer=r,b.TextRenderer=s,b.Lexer=a,b.lexer=a.lex,b.InlineLexer=p,b.inlineLexer=p.output,b.Slugger=t,b.parse=b,"undefined"!=typeof module&&"object"==typeof exports?module.exports=b:"function"==typeof define&&define.amd?define(function(){return b}):e.marked=b}(this||("undefined"!=typeof window?window:global)); \ No newline at end of file diff --git a/packages/markdown/marked/package.json b/packages/markdown/marked/package.json new file mode 100644 index 00000000..43cea559 --- /dev/null +++ b/packages/markdown/marked/package.json @@ -0,0 +1,69 @@ +{ + "name": "marked", + "description": "A markdown parser built for speed", + "author": "Christopher Jeffrey", + "version": "0.6.2", + "main": "./lib/marked.js", + "bin": "./bin/marked", + "man": "./man/marked.1", + "files": [ + "bin/", + "lib/", + "man/", + "marked.min.js" + ], + "repository": "git://github.com/markedjs/marked.git", + "homepage": "https://marked.js.org", + "bugs": { + "url": "http://github.com/markedjs/marked/issues" + }, + "license": "MIT", + "keywords": [ + "markdown", + "markup", + "html" + ], + "tags": [ + "markdown", + "markup", + "html" + ], + "devDependencies": { + "@markedjs/html-differ": "^2.0.1", + "cheerio": "^1.0.0-rc.3", + "commonmark": "0.x", + "eslint": "^5.15.1", + "eslint-config-standard": "^12.0.0", + "eslint-plugin-import": "^2.16.0", + "eslint-plugin-node": "^8.0.1", + "eslint-plugin-promise": "^4.0.1", + "eslint-plugin-standard": "^4.0.0", + "eslint-plugin-vuln-regex-detector": "^1.0.4", + "front-matter": "^3.0.1", + "glob-to-regexp": "^0.4.0", + "jasmine": "^3.3.1", + "markdown": "0.x", + "markdown-it": "8.x", + "node-fetch": "^2.3.0", + "uglify-js": "^3.4.9" + }, + "scripts": { + "test": "jasmine --config=jasmine.json", + "test:unit": "npm test -- test/unit/**/*-spec.js", + "test:specs": "npm test -- test/specs/**/*-spec.js", + "test:cm": "npm test -- test/specs/commonmark/**/*-spec.js", + "test:gfm": "npm test -- test/specs/gfm/**/*-spec.js", + "test:marked": "npm test -- test/specs/marked/**/*-spec.js", + "test:old": "node test", + "test:lint": "eslint bin/marked .", + "test:redos": "eslint --plugin vuln-regex-detector --rule '\"vuln-regex-detector/no-vuln-regex\": 2' lib/marked.js", + "test:node4": "npx node@4 ./node_modules/jasmine/bin/jasmine.js --config=jasmine.json", + "bench": "node test --bench", + "lint": "eslint --fix bin/marked .", + "build": "uglifyjs lib/marked.js -cm --comments /Copyright/ -o marked.min.js", + "preversion": "npm run build && (git diff --quiet || git commit -am 'minify')" + }, + "engines": { + "node": ">=0.10.0" + } +} diff --git a/packages/markdown/marked/test/README b/packages/markdown/marked/test/README new file mode 100644 index 00000000..51f6560b --- /dev/null +++ b/packages/markdown/marked/test/README @@ -0,0 +1,10 @@ +In this directory: + +# +# MarkdownTester -- Run tests for Markdown implementations +# +# Copyright (c) 2004-2005 John Gruber +# +# + +Partially modified for testing purposes. diff --git a/packages/markdown/marked/test/browser/index.html b/packages/markdown/marked/test/browser/index.html new file mode 100644 index 00000000..fbde1293 --- /dev/null +++ b/packages/markdown/marked/test/browser/index.html @@ -0,0 +1,5 @@ + +marked tests +

    testing...

    + + diff --git a/packages/markdown/marked/test/browser/index.js b/packages/markdown/marked/test/browser/index.js new file mode 100644 index 00000000..8208fa3f --- /dev/null +++ b/packages/markdown/marked/test/browser/index.js @@ -0,0 +1,39 @@ +var fs = require('fs'), + path = require('path'); + +var testMod = require('../'), + load = testMod.load; + +var express = require('express'), + app = express(); + +var files = load(); + +app.use(function(req, res, next) { + var setHeader = res.setHeader; + res.setHeader = function(name) { + switch (name) { + case 'Cache-Control': + case 'Last-Modified': + case 'ETag': + return; + } + return setHeader.apply(res, arguments); + }; + next(); +}); + +app.get('/test.js', function(req, res, next) { + var test = fs.readFileSync(path.join(__dirname, 'test.js'), 'utf8'); + var testScript = test.replace('__TESTS__', JSON.stringify(files)) + .replace('__MAIN__', testMod.runTests + '') + .replace('__LIBS__', testMod.testFile + ''); + + res.contentType('.js'); + res.send(testScript); +}); + +app.use(express.static(path.join(__dirname, '/../../lib'))); +app.use(express.static(__dirname)); + +app.listen(8080); diff --git a/packages/markdown/marked/test/browser/test.js b/packages/markdown/marked/test/browser/test.js new file mode 100644 index 00000000..59917dd4 --- /dev/null +++ b/packages/markdown/marked/test/browser/test.js @@ -0,0 +1,66 @@ + +;(function() { + var console = {}, + files = __TESTS__; // eslint-disable-line no-undef + + console.log = function(text) { + var args = Array.prototype.slice.call(arguments, 1), + i = 0; + + text = text.replace(/%\w/g, function() { + return args[i++] || ''; + }); + + if (window.console) window.console.log(text); + document.body.innerHTML += '
    ' + escape(text) + '
    '; + }; + + if (!Object.keys) { + Object.keys = function(obj) { + var out = [], + key; + + for (key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + out.push(key); + } + } + + return out; + }; + } + + if (!Array.prototype.forEach) { + // eslint-disable-next-line no-extend-native + Array.prototype.forEach = function(callback, context) { + for (var i = 0; i < this.length; i++) { + callback.call(context || null, this[i], i, this); + } + }; + } + + if (!String.prototype.trim) { + // eslint-disable-next-line no-extend-native + String.prototype.trim = function() { + return this.replace(/^\s+|\s+$/g, ''); + }; + } + + // eslint-disable-next-line no-unused-vars + function load() { + return files; + } + + function escape(html, encode) { + return html + .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + __LIBS__; // eslint-disable-line no-undef, no-unused-expressions + + (__MAIN__)(); // eslint-disable-line no-undef +}).call(this); diff --git a/packages/markdown/marked/test/helpers/helpers.js b/packages/markdown/marked/test/helpers/helpers.js new file mode 100644 index 00000000..44632fcd --- /dev/null +++ b/packages/markdown/marked/test/helpers/helpers.js @@ -0,0 +1,26 @@ +const marked = require('../../'); +const htmlDiffer = require('./html-differ.js'); + +beforeEach(() => { + marked.setOptions(marked.getDefaults()); + + jasmine.addMatchers({ + toRender: () => { + return { + compare: (spec, expected) => { + const result = {}; + const actual = marked(spec.markdown, spec.options); + result.pass = htmlDiffer.isEqual(expected, actual); + + if (result.pass) { + result.message = `${spec.markdown}\n------\n\nExpected: Should Fail`; + } else { + const diff = htmlDiffer.firstDiff(actual, expected); + result.message = `Expected: ${diff.expected}\n Actual: ${diff.actual}`; + } + return result; + } + }; + } + }); +}); diff --git a/packages/markdown/marked/test/helpers/html-differ.js b/packages/markdown/marked/test/helpers/html-differ.js new file mode 100644 index 00000000..44052be4 --- /dev/null +++ b/packages/markdown/marked/test/helpers/html-differ.js @@ -0,0 +1,38 @@ +const HtmlDiffer = require('@markedjs/html-differ').HtmlDiffer; +const htmlDiffer = new HtmlDiffer({ignoreSelfClosingSlash: true}); + +module.exports = { + isEqual: htmlDiffer.isEqual.bind(htmlDiffer), + firstDiff: (actual, expected, padding) => { + padding = padding || 30; + const result = htmlDiffer + .diffHtml(actual, expected) + .reduce((obj, diff) => { + if (diff.added) { + if (obj.firstIndex === null) { + obj.firstIndex = obj.expected.length; + } + obj.expected += diff.value; + } else if (diff.removed) { + if (obj.firstIndex === null) { + obj.firstIndex = obj.actual.length; + } + obj.actual += diff.value; + } else { + obj.actual += diff.value; + obj.expected += diff.value; + } + + return obj; + }, { + firstIndex: null, + actual: '', + expected: '' + }); + + return { + actual: result.actual.substring(result.firstIndex - padding, result.firstIndex + padding), + expected: result.expected.substring(result.firstIndex - padding, result.firstIndex + padding) + }; + } +}; diff --git a/packages/markdown/marked/test/index.js b/packages/markdown/marked/test/index.js new file mode 100644 index 00000000..5027ee5b --- /dev/null +++ b/packages/markdown/marked/test/index.js @@ -0,0 +1,551 @@ +#!/usr/bin/env node +'use strict'; +// 'use strict' is here so we can use let and const in node 4 + +/** + * marked tests + * Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ + +/** + * Modules + */ + +const fs = require('fs'); +const path = require('path'); +const fm = require('front-matter'); +const g2r = require('glob-to-regexp'); +let marked = require('../'); +const htmlDiffer = require('./helpers/html-differ.js'); + +/** + * Load Tests + */ + +function load(options) { + options = options || {}; + const dir = path.join(__dirname, 'compiled_tests'); + const glob = g2r(options.glob || '*', { extended: true }); + + const list = fs + .readdirSync(dir) + .filter(file => { + return path.extname(file) === '.md'; + }) + .sort(); + + const files = list.reduce((obj, item) => { + const name = path.basename(item, '.md'); + if (glob.test(name)) { + const file = path.join(dir, item); + const content = fm(fs.readFileSync(file, 'utf8')); + + obj[name] = { + options: content.attributes, + text: content.body, + html: fs.readFileSync(file.replace(/[^.]+$/, 'html'), 'utf8') + }; + } + return obj; + }, {}); + + if (options.bench || options.time) { + if (!options.glob) { + // Change certain tests to allow + // comparison to older benchmark times. + fs.readdirSync(path.join(__dirname, 'new')).forEach(name => { + if (path.extname(name) === '.html') return; + if (name === 'main.md') return; + delete files[name]; + }); + } + + if (files['backslash_escapes.md']) { + files['backslash_escapes.md'] = { + text: 'hello world \\[how](are you) today' + }; + } + + if (files['main.md']) { + files['main.md'].text = files['main.md'].text.replace('* * *\n\n', ''); + } + } + + return files; +} + +/** + * Test Runner + */ + +function runTests(engine, options) { + if (typeof engine !== 'function') { + options = engine; + engine = null; + } + + engine = engine || marked; + options = options || {}; + + let succeeded = 0; + let failed = 0; + const files = options.files || load(options); + const filenames = Object.keys(files); + + if (options.marked) { + marked.setOptions(options.marked); + } + + for (let i = 0; i < filenames.length; i++) { + const filename = filenames[i]; + const file = files[filename]; + + const success = testFile(engine, file, filename, i + 1); + + if (success) { + succeeded++; + } else { + failed++; + if (options.stop) { + break; + } + } + } + + console.log('\n%d/%d tests completed successfully.', succeeded, filenames.length); + if (failed) console.log('%d/%d tests failed.', failed, filenames.length); + + return !failed; +} + +/** + * Test a file + */ + +function testFile(engine, file, filename, index) { + const opts = Object.keys(file.options); + + if (marked._original) { + marked.defaults = marked._original; + delete marked._original; + } + + console.log('#%d. Test %s', index, filename); + + if (opts.length) { + marked._original = marked.defaults; + marked.defaults = {}; + Object.keys(marked._original).forEach(key => { + marked.defaults[key] = marked._original[key]; + }); + opts.forEach(key => { + if (marked.defaults.hasOwnProperty(key)) { + marked.defaults[key] = file.options[key]; + } + }); + } + + const before = process.hrtime(); + + let text, html, elapsed; + try { + text = engine(file.text); + html = file.html; + } catch (e) { + elapsed = process.hrtime(before); + console.log('\n failed in %dms\n', prettyElapsedTime(elapsed)); + throw e; + } + + elapsed = process.hrtime(before); + + if (htmlDiffer.isEqual(text, html)) { + if (elapsed[0] > 0) { + console.log('\n failed because it took too long.\n\n passed in %dms\n', prettyElapsedTime(elapsed)); + return false; + } + console.log(' passed in %dms', prettyElapsedTime(elapsed)); + return true; + } + + const diff = htmlDiffer.firstDiff(text, html); + + console.log('\n failed in %dms', prettyElapsedTime(elapsed)); + console.log(' Expected: %s', diff.expected); + console.log(' Actual: %s\n', diff.actual); + return false; +} + +/** + * Benchmark a function + */ + +function bench(name, files, engine) { + const start = Date.now(); + + for (let i = 0; i < 1000; i++) { + for (const filename in files) { + engine(files[filename].text); + } + } + + const end = Date.now(); + + console.log('%s completed in %dms.', name, end - start); +} + +/** + * Benchmark all engines + */ + +function runBench(options) { + options = options || {}; + const files = load(options); + + // Non-GFM, Non-pedantic + marked.setOptions({ + gfm: false, + tables: false, + breaks: false, + pedantic: false, + sanitize: false, + smartLists: false + }); + if (options.marked) { + marked.setOptions(options.marked); + } + bench('marked', files, marked); + + // GFM + marked.setOptions({ + gfm: true, + tables: false, + breaks: false, + pedantic: false, + sanitize: false, + smartLists: false + }); + if (options.marked) { + marked.setOptions(options.marked); + } + bench('marked (gfm)', files, marked); + + // Pedantic + marked.setOptions({ + gfm: false, + tables: false, + breaks: false, + pedantic: true, + sanitize: false, + smartLists: false + }); + if (options.marked) { + marked.setOptions(options.marked); + } + bench('marked (pedantic)', files, marked); + + try { + bench('commonmark', files, (() => { + const commonmark = require('commonmark'); + const parser = new commonmark.Parser(); + const writer = new commonmark.HtmlRenderer(); + return function (text) { + return writer.render(parser.parse(text)); + }; + })()); + } catch (e) { + console.log('Could not bench commonmark. (Error: %s)', e.message); + } + + try { + bench('markdown-it', files, (() => { + const MarkdownIt = require('markdown-it'); + const md = new MarkdownIt(); + return md.render.bind(md); + })()); + } catch (e) { + console.log('Could not bench markdown-it. (Error: %s)', e.message); + } + + try { + bench('markdown.js', files, (() => { + const markdown = require('markdown').markdown; + return markdown.toHTML.bind(markdown); + })()); + } catch (e) { + console.log('Could not bench markdown.js. (Error: %s)', e.message); + } + + return true; +} + +/** + * A simple one-time benchmark + */ + +function time(options) { + options = options || {}; + const files = load(options); + if (options.marked) { + marked.setOptions(options.marked); + } + bench('marked', files, marked); + + return true; +} + +/** + * Markdown Test Suite Fixer + * This function is responsible for "fixing" + * the markdown test suite. There are + * certain aspects of the suite that + * are strange or might make tests + * fail for reasons unrelated to + * conformance. + */ + +function fix() { + ['compiled_tests', 'original', 'new', 'redos'].forEach(dir => { + try { + fs.mkdirSync(path.resolve(__dirname, dir)); + } catch (e) { + // directory already exists + } + }); + + // rm -rf tests + fs.readdirSync(path.resolve(__dirname, 'compiled_tests')).forEach(file => { + fs.unlinkSync(path.resolve(__dirname, 'compiled_tests', file)); + }); + + // cp -r original tests + fs.readdirSync(path.resolve(__dirname, 'original')).forEach(file => { + let text = fs.readFileSync(path.resolve(__dirname, 'original', file), 'utf8'); + + if (path.extname(file) === '.md') { + if (fm.test(text)) { + text = fm(text); + text = `---\n${text.frontmatter}\ngfm: false\n---\n${text.body}`; + } else { + text = `---\ngfm: false\n---\n${text}`; + } + } + + fs.writeFileSync(path.resolve(__dirname, 'compiled_tests', file), text); + }); + + // node fix.js + const dir = path.join(__dirname, 'compiled_tests'); + + fs.readdirSync(dir).filter(file => { + return path.extname(file) === '.html'; + }).forEach(file => { + file = path.join(dir, file); + let html = fs.readFileSync(file, 'utf8'); + + // fix unencoded quotes + html = html + .replace(/='([^\n']*)'(?=[^<>\n]*>)/g, '=&__APOS__;$1&__APOS__;') + .replace(/="([^\n"]*)"(?=[^<>\n]*>)/g, '=&__QUOT__;$1&__QUOT__;') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(/&__QUOT__;/g, '"') + .replace(/&__APOS__;/g, '\''); + + fs.writeFileSync(file, html); + }); + + // turn
    into
    + fs.readdirSync(dir).forEach(file => { + file = path.join(dir, file); + let text = fs.readFileSync(file, 'utf8'); + + text = text.replace(/(<|<)hr\s*\/(>|>)/g, '$1hr$2'); + + fs.writeFileSync(file, text); + }); + + // markdown does some strange things. + // it does not encode naked `>`, marked does. + { + const file = `${dir}/amps_and_angles_encoding.html`; + const html = fs.readFileSync(file, 'utf8') + .replace('6 > 5.', '6 > 5.'); + + fs.writeFileSync(file, html); + } + + // cp new/* tests/ + fs.readdirSync(path.resolve(__dirname, 'new')).forEach(file => { + fs.writeFileSync(path.resolve(__dirname, 'compiled_tests', file), + fs.readFileSync(path.resolve(__dirname, 'new', file))); + }); + + // cp redos/* tests/ + fs.readdirSync(path.resolve(__dirname, 'redos')).forEach(file => { + fs.writeFileSync(path.resolve(__dirname, 'compiled_tests', file), + fs.readFileSync(path.resolve(__dirname, 'redos', file))); + }); +} + +/** + * Argument Parsing + */ + +function parseArg(argv) { + argv = argv.slice(2); + + const options = {}; + const orphans = []; + + function getarg() { + let arg = argv.shift(); + + if (arg.indexOf('--') === 0) { + // e.g. --opt + arg = arg.split('='); + if (arg.length > 1) { + // e.g. --opt=val + argv.unshift(arg.slice(1).join('=')); + } + arg = arg[0]; + } else if (arg[0] === '-') { + if (arg.length > 2) { + // e.g. -abc + argv = arg.substring(1).split('').map(ch => { + return `-${ch}`; + }).concat(argv); + arg = argv.shift(); + } else { + // e.g. -a + } + } else { + // e.g. foo + } + + return arg; + } + + while (argv.length) { + let arg = getarg(); + switch (arg) { + case '-f': + case '--fix': + case 'fix': + if (options.fix !== false) { + options.fix = true; + } + break; + case '--no-fix': + case 'no-fix': + options.fix = false; + break; + case '-b': + case '--bench': + options.bench = true; + break; + case '-s': + case '--stop': + options.stop = true; + break; + case '-t': + case '--time': + options.time = true; + break; + case '-m': + case '--minified': + options.minified = true; + break; + case '--glob': + arg = argv.shift(); + options.glob = arg.replace(/^=/, ''); + break; + default: + if (arg.indexOf('--') === 0) { + const opt = camelize(arg.replace(/^--(no-)?/, '')); + if (!marked.defaults.hasOwnProperty(opt)) { + continue; + } + options.marked = options.marked || {}; + if (arg.indexOf('--no-') === 0) { + options.marked[opt] = typeof marked.defaults[opt] !== 'boolean' + ? null + : false; + } else { + options.marked[opt] = typeof marked.defaults[opt] !== 'boolean' + ? argv.shift() + : true; + } + } else { + orphans.push(arg); + } + break; + } + } + + return options; +} + +/** + * Helpers + */ + +function camelize(text) { + return text.replace(/(\w)-(\w)/g, (_, a, b) => a + b.toUpperCase()); +} + +/** + * Main + */ + +function main(argv) { + const opt = parseArg(argv); + + if (opt.fix !== false) { + fix(); + } + + if (opt.fix) { + // only run fix + return; + } + + if (opt.bench) { + return runBench(opt); + } + + if (opt.time) { + return time(opt); + } + + if (opt.minified) { + marked = require('../marked.min.js'); + } + return runTests(opt); +} + +/** + * Execute + */ + +if (!module.parent) { + process.title = 'marked'; + process.exit(main(process.argv.slice()) ? 0 : 1); +} else { + exports = main; + exports.main = main; + exports.runTests = runTests; + exports.testFile = testFile; + exports.runBench = runBench; + exports.load = load; + exports.bench = bench; + module.exports = exports; +} + +// returns time to millisecond granularity +function prettyElapsedTime(hrtimeElapsed) { + const seconds = hrtimeElapsed[0]; + const frac = Math.round(hrtimeElapsed[1] / 1e3) / 1e3; + return seconds * 1e3 + frac; +} diff --git a/packages/markdown/marked/test/json-to-files.js b/packages/markdown/marked/test/json-to-files.js new file mode 100644 index 00000000..d7e72aaf --- /dev/null +++ b/packages/markdown/marked/test/json-to-files.js @@ -0,0 +1,62 @@ +const path = require('path'); +const fs = require('fs'); + +const folder = process.argv[2]; +const jsonFile = process.argv[3]; + +if (!folder || !jsonFile) { + console.log('node ./json-to-files.js {path to folder} {path to json file}'); + process.exit(1); +} + +const specs = require(jsonFile); + +const files = specs.reduce((obj, spec) => { + if (!obj[spec.section]) { + obj[spec.section] = { + md: [], + html: [], + options: {} + }; + } + + obj[spec.section].md.push(spec.markdown); + obj[spec.section].html.push(spec.html); + Object.assign(obj[spec.section].options, spec.options); + + return obj; +}, {}); + +try { + fs.mkdirSync(folder, {recursive: true}); +} catch (ex) { + // already exists +} + +for (const section in files) { + const file = files[section]; + const name = section.toLowerCase().replace(' ', '_'); + const frontMatter = Object.keys(file.options).map(opt => { + let value = file.options[opt]; + if (typeof value !== 'string') { + value = JSON.stringify(value); + } + return `${opt}: ${value}`; + }).join('\n'); + + let markdown = file.md.join('\n\n'); + if (frontMatter) { + markdown = `---\n${frontMatter}\n---\n\n${markdown}`; + } + const html = file.html.join('\n\n'); + + const mdFile = path.resolve(folder, `${name}.md`); + const htmlFile = path.resolve(folder, `${name}.html`); + + if (fs.existsSync(mdFile) || fs.existsSync(htmlFile)) { + throw new Error(`${name} already exists.`); + } + + fs.writeFileSync(mdFile, markdown); + fs.writeFileSync(htmlFile, html); +} diff --git a/packages/markdown/marked/test/new/adjacent_lists.html b/packages/markdown/marked/test/new/adjacent_lists.html new file mode 100644 index 00000000..b4cd8f50 --- /dev/null +++ b/packages/markdown/marked/test/new/adjacent_lists.html @@ -0,0 +1,9 @@ +
      +
    • This should be
    • +
    • An unordered list
    • +
    + +
      +
    1. This should be
    2. +
    3. An unordered list
    4. +
    diff --git a/packages/markdown/marked/test/new/adjacent_lists.md b/packages/markdown/marked/test/new/adjacent_lists.md new file mode 100644 index 00000000..3fd460b3 --- /dev/null +++ b/packages/markdown/marked/test/new/adjacent_lists.md @@ -0,0 +1,5 @@ +* This should be +* An unordered list + +1. This should be +2. An unordered list diff --git a/packages/markdown/marked/test/new/autolink_lines.html b/packages/markdown/marked/test/new/autolink_lines.html new file mode 100644 index 00000000..aa2bed4d --- /dev/null +++ b/packages/markdown/marked/test/new/autolink_lines.html @@ -0,0 +1,3 @@ +

    hello world +http://example.com +

    diff --git a/packages/markdown/marked/test/new/autolink_lines.md b/packages/markdown/marked/test/new/autolink_lines.md new file mode 100644 index 00000000..c9b61a2c --- /dev/null +++ b/packages/markdown/marked/test/new/autolink_lines.md @@ -0,0 +1,2 @@ +hello world + diff --git a/packages/markdown/marked/test/new/autolinks.html b/packages/markdown/marked/test/new/autolinks.html new file mode 100644 index 00000000..8fa4837e --- /dev/null +++ b/packages/markdown/marked/test/new/autolinks.html @@ -0,0 +1,15 @@ +

    (See https://www.example.com/fhqwhgads.)

    + +

    ((http://foo.com))

    + +

    ((http://foo.com.))

    + +

    HTTP://FOO.COM

    + +

    hTtP://fOo.CoM

    + +

    hello@email.com

    + +

    me@example.com

    + +

    test@test.com

    \ No newline at end of file diff --git a/packages/markdown/marked/test/new/autolinks.md b/packages/markdown/marked/test/new/autolinks.md new file mode 100644 index 00000000..1f5f739c --- /dev/null +++ b/packages/markdown/marked/test/new/autolinks.md @@ -0,0 +1,15 @@ +(See https://www.example.com/fhqwhgads.) + +((http://foo.com)) + +((http://foo.com.)) + +HTTP://FOO.COM + +hTtP://fOo.CoM + +~~hello@email.com~~ + +**me@example.com** + +__test@test.com__ \ No newline at end of file diff --git a/packages/markdown/marked/test/new/blockquote_list_item.html b/packages/markdown/marked/test/new/blockquote_list_item.html new file mode 100644 index 00000000..83cf0bdd --- /dev/null +++ b/packages/markdown/marked/test/new/blockquote_list_item.html @@ -0,0 +1,3 @@ +

    This fails in markdown.pl and upskirt:

    + +
    • hello

      world

    diff --git a/packages/markdown/marked/test/new/blockquote_list_item.md b/packages/markdown/marked/test/new/blockquote_list_item.md new file mode 100644 index 00000000..19e93829 --- /dev/null +++ b/packages/markdown/marked/test/new/blockquote_list_item.md @@ -0,0 +1,4 @@ +This fails in markdown.pl and upskirt: + +* hello + > world diff --git a/packages/markdown/marked/test/new/case_insensitive_refs.html b/packages/markdown/marked/test/new/case_insensitive_refs.html new file mode 100644 index 00000000..c54388ea --- /dev/null +++ b/packages/markdown/marked/test/new/case_insensitive_refs.html @@ -0,0 +1 @@ +

    hi

    diff --git a/packages/markdown/marked/test/new/case_insensitive_refs.md b/packages/markdown/marked/test/new/case_insensitive_refs.md new file mode 100644 index 00000000..598915a8 --- /dev/null +++ b/packages/markdown/marked/test/new/case_insensitive_refs.md @@ -0,0 +1,3 @@ +[hi] + +[HI]: /url diff --git a/packages/markdown/marked/test/new/cm_autolinks.html b/packages/markdown/marked/test/new/cm_autolinks.html new file mode 100644 index 00000000..e7ae0ee4 --- /dev/null +++ b/packages/markdown/marked/test/new/cm_autolinks.html @@ -0,0 +1,91 @@ +

    Here are some valid autolinks:

    + +

    Example 565

    + +

    http://foo.bar.baz

    + +

    Example 566

    + +

    http://foo.bar.baz/test?q=hello&id=22&boolean

    + +

    Example 567

    + +

    irc://foo.bar:2233/baz

    + +

    Example 568

    + +

    Uppercase is also fine:

    + +

    MAILTO:FOO@BAR.BAZ

    + +

    Note that many strings that count as absolute URIs for purposes of this spec are not valid URIs, because their schemes are not registered or because of other problems with their syntax:

    + +

    Example 569

    + +

    a+b+c:d

    + +

    Example 570

    + +

    made-up-scheme://foo,bar

    + +

    Example 571

    + +

    http://../

    + +

    Example 572

    + +

    localhost:5001/foo

    + +

    Example 573

    + +

    Spaces are not allowed in autolinks:

    + +

    <http://foo.bar/baz bim>

    + +

    Example 574

    + +

    Backslash-escapes do not work inside autolinks:

    + +

    http://example.com/\[\

    + +

    Examples of email autolinks:

    + +

    Example 575

    + +

    foo@bar.example.com

    + +

    Example 576

    + +

    foo+special@Bar.baz-bar0.com

    + +

    Example 577

    + +

    Backslash-escapes do not work inside email autolinks:

    + +

    <foo+@bar.example.com>

    + +

    These are not autolinks:

    + +

    Example 578

    + +

    <>

    + +

    Example 579

    + +

    < http://foo.bar >

    + +

    Example 580

    + +

    <m:abc>

    + +

    Example 581

    + +

    <foo.bar.baz>

    + +

    Example 582

    + +

    http://example.com

    + +

    Example 583

    + +

    foo@bar.example.com

    \ No newline at end of file diff --git a/packages/markdown/marked/test/new/cm_autolinks.md b/packages/markdown/marked/test/new/cm_autolinks.md new file mode 100644 index 00000000..a19d830c --- /dev/null +++ b/packages/markdown/marked/test/new/cm_autolinks.md @@ -0,0 +1,96 @@ +--- +gfm: false +mangle: false +--- + +Here are some valid autolinks: + +### Example 565 + + + +### Example 566 + + + +### Example 567 + + + +### Example 568 + +Uppercase is also fine: + + + +Note that many strings that count as absolute URIs for purposes of this spec are not valid URIs, because their schemes are not registered or because of other problems with their syntax: + +### Example 569 + + + +### Example 570 + + + +### Example 571 + + + +### Example 572 + + + +### Example 573 + +Spaces are not allowed in autolinks: + + + +### Example 574 + +Backslash-escapes do not work inside autolinks: + + + +Examples of email autolinks: + +### Example 575 + + + +### Example 576 + + + +### Example 577 + +Backslash-escapes do not work inside email autolinks: + + + +These are not autolinks: + +### Example 578 + +<> + +### Example 579 + +< http://foo.bar > + +### Example 580 + + + +### Example 581 + + + +### Example 582 + +http://example.com + +### Example 583 + +foo@bar.example.com \ No newline at end of file diff --git a/packages/markdown/marked/test/new/cm_blockquotes.html b/packages/markdown/marked/test/new/cm_blockquotes.html new file mode 100644 index 00000000..b4d51b1f --- /dev/null +++ b/packages/markdown/marked/test/new/cm_blockquotes.html @@ -0,0 +1,233 @@ +

    Example 191

    + +
    +

    Foo

    +

    bar +baz

    +
    + +

    Example 192

    + +

    The spaces after the > characters can be omitted:

    + +
    +

    Bar

    +

    bar +baz

    +
    + +

    Example 193

    + +

    The > characters can be indented 1-3 spaces:

    + +
    +

    Baz

    +

    bar +baz

    +
    + +

    Example 194

    + +

    Four spaces gives us a code block:

    + +
    > # Qux
    +> bar
    +> baz
    + +

    Example 195

    + +

    The Laziness clause allows us to omit the > before paragraph continuation text:

    + +
    +

    Quux

    +

    bar +baz

    +
    + +

    Example 196

    + +

    A block quote can contain some lazy and some non-lazy continuation lines:

    + +
    +

    bar +baz +foo

    +
    + +

    Example 197

    + +

    Laziness only applies to lines that would have been continuations of paragraphs had they been prepended with block quote markers. For example, the > cannot be omitted in the second line of

    + +
    +

    foo

    +
    +
    + +

    without changing the meaning.

    + +

    Example 198

    + +
    Similarly, if we omit the `>` in the second line then the block quote ends after the first line:
    +
    +> - foo
    +- bar
    + +

    Example 199

    + +

    For the same reason, we can’t omit the > in front of subsequent lines of an indented or fenced code block:

    + +
    +
    foo
    +
    +
    bar
    + +

    Example 200

    + +
    > ```
    +foo
    +```
    +
    +<blockquote>
    +<pre><code></code></pre>
    +</blockquote>
    +<p>foo</p>
    +<pre><code></code></pre>
    + +

    Example 201

    +
    > foo
    +    - bar
    +
    +<blockquote>
    +<p>foo
    +- bar</p>
    +</blockquote>
    + +

    Example 202

    + +

    A block quote can be empty:

    + +
    +
    + +

    Example 203

    + +
    +
    + +

    Example 204

    + +

    A block quote can have initial or final blank lines:

    + +
    +

    foo

    +
    + + +

    Example 205

    + +

    A blank line always separates block quotes:

    + +
    +

    foo

    +
    +
    +

    bar

    +
    + +

    Example 206

    + +

    Consecutiveness means that if we put these block quotes together, we get a single block quote:

    + +
    +

    foo +bar

    +
    + +

    Example 207

    + +

    To get a block quote with two paragraphs, use:

    + +
    +

    foo

    +

    bar

    +
    + +

    Example 208

    + +

    Block quotes can interrupt paragraphs:

    + +

    foo

    +
    +

    bar

    +
    + +

    Example 209

    + +

    In general, blank lines are not needed before or after block quotes:

    + +
    +

    aaa

    +
    +
    +
    +

    bbb

    +
    + +

    Example 210

    + +

    However, because of laziness, a blank line is needed between a block quote and a following paragraph:

    + +
    +

    bar +baz

    +
    + +

    Example 211

    + +
    +

    bar

    +
    +

    baz

    + +

    Example 212

    + +
    +

    bar

    +
    +

    baz

    + +

    Example 213

    + +

    It is a consequence of the Laziness rule that any number of initial >s may be omitted on a continuation line of a nested block quote:

    + +
    +
    +
    +

    foo +bar

    +
    +
    +
    + +

    Example 214

    + +
    +
    +
    +

    foo +bar +baz

    +
    +
    +
    + +

    Example 215

    + +

    When including an indented code block in a block quote, remember that the block quote marker includes both the > and a following space. So five spaces are needed after the >:

    + +
    +
    code
    +
    +
    +

    not code

    +
    diff --git a/packages/markdown/marked/test/new/cm_blockquotes.md b/packages/markdown/marked/test/new/cm_blockquotes.md new file mode 100644 index 00000000..6a80a6f3 --- /dev/null +++ b/packages/markdown/marked/test/new/cm_blockquotes.md @@ -0,0 +1,189 @@ +### Example 191 + +> # Foo +> bar +> baz + +### Example 192 + +The spaces after the `>` characters can be omitted: + +># Bar +>bar +> baz + +### Example 193 + +The `>` characters can be indented 1-3 spaces: + + > # Baz + > bar + > baz + +### Example 194 + +Four spaces gives us a code block: + + > # Qux + > bar + > baz + +### Example 195 + +The Laziness clause allows us to omit the `>` before paragraph continuation text: + +> # Quux +> bar +baz + +### Example 196 + +A block quote can contain some lazy and some non-lazy continuation lines: + +> bar +baz +> foo + +### Example 197 + +Laziness only applies to lines that would have been continuations of paragraphs had they been prepended with block quote markers. For example, the `>` cannot be omitted in the second line of + +> foo +--- + +without changing the meaning. + +### Example 198 + + Similarly, if we omit the `>` in the second line then the block quote ends after the first line: + + > - foo + - bar + +### Example 199 + +For the same reason, we can’t omit the `>` in front of subsequent lines of an indented or fenced code block: + +> foo + + bar + +### Example 200 + + > ``` + foo + ``` + +
    +
    +
    +

    foo

    +
    + +### Example 201 + + > foo + - bar + +
    +

    foo + - bar

    +
    + +### Example 202 + +A block quote can be empty: + +> + +### Example 203 + +> +> +> + +### Example 204 + +A block quote can have initial or final blank lines: + +> +> foo +> + +### Example 205 + +A blank line always separates block quotes: + +> foo + +> bar + +### Example 206 + +Consecutiveness means that if we put these block quotes together, we get a single block quote: + +> foo +> bar + +### Example 207 + +To get a block quote with two paragraphs, use: + +> foo +> +> bar + +### Example 208 + +Block quotes can interrupt paragraphs: + +foo +> bar + +### Example 209 + +In general, blank lines are not needed before or after block quotes: + +> aaa +*** +> bbb + +### Example 210 + +However, because of laziness, a blank line is needed between a block quote and a following paragraph: + +> bar +baz + +### Example 211 + +> bar + +baz + +### Example 212 + +> bar +> +baz + +### Example 213 + +It is a consequence of the Laziness rule that any number of initial `>`s may be omitted on a continuation line of a nested block quote: + +> > > foo +bar + +### Example 214 + +>>> foo +> bar +>>baz + +### Example 215 + +When including an indented code block in a block quote, remember that the block quote marker includes both the `>` and a following space. So five spaces are needed after the `>`: + +> code + +> not code diff --git a/packages/markdown/marked/test/new/cm_html_blocks.html b/packages/markdown/marked/test/new/cm_html_blocks.html new file mode 100644 index 00000000..80fdff57 --- /dev/null +++ b/packages/markdown/marked/test/new/cm_html_blocks.html @@ -0,0 +1,300 @@ +

    HTML blocks

    + +

    Example 116

    + +
    +
    +**Hello**,
    +

    world. +

    +
    + +

    Example 117

    + + + + + +
    + hi +
    +

    okay.

    + +

    Example 118

    + + +*foo* + +

    Example 120

    + +
    +

    Markdown

    +
    + +

    Example 121

    + +
    +
    + +

    Example 122

    + +
    +
    + +

    Example 123

    + +
    +*foo* +

    bar

    + +

    Example 124

    + +
    Example 125

    + +
    Example 126 + +
    Example 127 + + + +

    Example 128

    + +
    +foo +
    + +

    Example 129

    + +
    +``` c +int x = 33; +``` + +

    Example 130

    + + +*bar* + + +

    Example 131

    + + +*bar* + + +

    Example 132

    + + +*bar* + + +

    Example 133

    + + +*bar* + +

    Example 134

    + + +*foo* + + +

    Example 135

    + + +

    foo

    +
    + +

    Example 136

    + +

    foo

    + +

    Example 137

    + +
    
    +import Text.HTML.TagSoup
    +
    +main :: IO ()
    +main = print $ parseTags tags
    +
    +

    okay

    + +

    Example 138

    + + +

    okay

    + +

    Example 139

    + + +

    okay

    + +

    Example 141

    + +
    +
    +foo +
    +

    bar

    + +

    Example 142

    + +
      +
    • +
      +
    • +
    • foo
    • +
    + +

    Example 143

    + + +

    foo

    + +

    Example 144

    + +*bar* +

    baz

    + +

    Example 145

    + +1. *bar* + +

    Example 146

    + + +

    okay

    + +

    Example 147

    + +'; + +?> +

    okay

    + +

    Example 148

    + + + +

    Example 149

    + + +

    okay

    + +

    Example 150

    + + +
    <!-- foo -->
    +
    + +

    Example 151

    + +
    +
    <div>
    +
    + +

    Example 152

    + +

    Foo

    +
    +bar +
    + +

    Example 153

    + +
    +bar +
    +*foo* + +

    Example 154

    + +

    Foo + +baz

    + +

    Example 155

    + +
    +

    Emphasized text.

    +
    + +

    Example 156

    + +
    +*Emphasized* text. +
    + +

    Example 157

    + + + + + +
    +Hi +
    + +

    Example 158

    + + + +
    <td>
    +  Hi
    +</td>
    +
    + +
    + +

    Example 140

    + +

    If there is no matching end tag, the block will end at the end of the document (or the enclosing block quote or list item):

    + + +okay + +### Example 141 + +>
    +> foo + +bar + +### Example 142 + +-
    +- foo + +### Example 143 + + +*foo* + +### Example 144 + +*bar* +*baz* + +### Example 145 + +1. *bar* + +### Example 146 + + +okay + +### Example 147 + +'; + +?> +okay + +### Example 148 + + + +### Example 149 + + +okay + +### Example 150 + + + + + +### Example 151 + +
    + +
    + +### Example 152 + +Foo +
    +bar +
    + +### Example 153 + +
    +bar +
    +*foo* + +### Example 154 + +Foo +
    +baz + +### Example 155 + +
    + +*Emphasized* text. + +
    + +### Example 156 + +
    +*Emphasized* text. +
    + +### Example 157 + + + + + + + + + +
    +Hi +
    + +### Example 158 + + + + + + + + + +
    + Hi +
    + +### Example 140 + +If there is no matching end tag, the block will end at the end of the document (or the enclosing block quote or list item): + +\nokay\n", + "html": "\nh1 {color:red;}\n\np {color:blue;}\n\n

    okay

    \n", + "example": 141, + "start_line": 2430, + "end_line": 2446, + "section": "HTML blocks" + }, + { + "markdown": "\n\nfoo\n", + "html": "\n\nfoo\n", + "example": 142, + "start_line": 2453, + "end_line": 2463, + "section": "HTML blocks" + }, + { + "markdown": ">
    \n> foo\n\nbar\n", + "html": "
    \n
    \nfoo\n
    \n

    bar

    \n", + "example": 143, + "start_line": 2466, + "end_line": 2477, + "section": "HTML blocks" + }, + { + "markdown": "-
    \n- foo\n", + "html": "
      \n
    • \n
      \n
    • \n
    • foo
    • \n
    \n", + "example": 144, + "start_line": 2480, + "end_line": 2490, + "section": "HTML blocks" + }, + { + "markdown": "\n*foo*\n", + "html": "\n

    foo

    \n", + "example": 145, + "start_line": 2495, + "end_line": 2501, + "section": "HTML blocks" + }, + { + "markdown": "*bar*\n*baz*\n", + "html": "*bar*\n

    baz

    \n", + "example": 146, + "start_line": 2504, + "end_line": 2510, + "section": "HTML blocks" + }, + { + "markdown": "1. *bar*\n", + "html": "1. *bar*\n", + "example": 147, + "start_line": 2516, + "end_line": 2524, + "section": "HTML blocks" + }, + { + "markdown": "\nokay\n", + "html": "\n

    okay

    \n", + "example": 148, + "start_line": 2529, + "end_line": 2541, + "section": "HTML blocks" + }, + { + "markdown": "';\n\n?>\nokay\n", + "html": "';\n\n?>\n

    okay

    \n", + "example": 149, + "start_line": 2547, + "end_line": 2561, + "section": "HTML blocks" + }, + { + "markdown": "\n", + "html": "\n", + "example": 150, + "start_line": 2566, + "end_line": 2570, + "section": "HTML blocks" + }, + { + "markdown": "\nokay\n", + "html": "\n

    okay

    \n", + "example": 151, + "start_line": 2575, + "end_line": 2603, + "section": "HTML blocks" + }, + { + "markdown": " \n\n \n", + "html": " \n
    <!-- foo -->\n
    \n", + "example": 152, + "start_line": 2608, + "end_line": 2616, + "section": "HTML blocks" + }, + { + "markdown": "
    \n\n
    \n", + "html": "
    \n
    <div>\n
    \n", + "example": 153, + "start_line": 2619, + "end_line": 2627, + "section": "HTML blocks" + }, + { + "markdown": "Foo\n
    \nbar\n
    \n", + "html": "

    Foo

    \n
    \nbar\n
    \n", + "example": 154, + "start_line": 2633, + "end_line": 2643, + "section": "HTML blocks" + }, + { + "markdown": "
    \nbar\n
    \n*foo*\n", + "html": "
    \nbar\n
    \n*foo*\n", + "example": 155, + "start_line": 2650, + "end_line": 2660, + "section": "HTML blocks" + }, + { + "markdown": "Foo\n
    \nbaz\n", + "html": "

    Foo\n\nbaz

    \n", + "example": 156, + "start_line": 2665, + "end_line": 2673, + "section": "HTML blocks" + }, + { + "markdown": "
    \n\n*Emphasized* text.\n\n
    \n", + "html": "
    \n

    Emphasized text.

    \n
    \n", + "example": 157, + "start_line": 2706, + "end_line": 2716, + "section": "HTML blocks" + }, + { + "markdown": "
    \n*Emphasized* text.\n
    \n", + "html": "
    \n*Emphasized* text.\n
    \n", + "example": 158, + "start_line": 2719, + "end_line": 2727, + "section": "HTML blocks" + }, + { + "markdown": "\n\n\n\n\n\n\n\n
    \nHi\n
    \n", + "html": "\n\n\n\n
    \nHi\n
    \n", + "example": 159, + "start_line": 2741, + "end_line": 2761, + "section": "HTML blocks" + }, + { + "markdown": "\n\n \n\n \n\n \n\n
    \n Hi\n
    \n", + "html": "\n \n
    <td>\n  Hi\n</td>\n
    \n \n
    \n", + "example": 160, + "start_line": 2768, + "end_line": 2789, + "section": "HTML blocks" + }, + { + "markdown": "[foo]: /url \"title\"\n\n[foo]\n", + "html": "

    foo

    \n", + "example": 161, + "start_line": 2816, + "end_line": 2822, + "section": "Link reference definitions" + }, + { + "markdown": " [foo]: \n /url \n 'the title' \n\n[foo]\n", + "html": "

    foo

    \n", + "example": 162, + "start_line": 2825, + "end_line": 2833, + "section": "Link reference definitions" + }, + { + "markdown": "[Foo*bar\\]]:my_(url) 'title (with parens)'\n\n[Foo*bar\\]]\n", + "html": "

    Foo*bar]

    \n", + "example": 163, + "start_line": 2836, + "end_line": 2842, + "section": "Link reference definitions" + }, + { + "markdown": "[Foo bar]:\n\n'title'\n\n[Foo bar]\n", + "html": "

    Foo bar

    \n", + "example": 164, + "start_line": 2845, + "end_line": 2853, + "section": "Link reference definitions", + "shouldFail": true + }, + { + "markdown": "[foo]: /url '\ntitle\nline1\nline2\n'\n\n[foo]\n", + "html": "

    foo

    \n", + "example": 165, + "start_line": 2858, + "end_line": 2872, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url 'title\n\nwith blank line'\n\n[foo]\n", + "html": "

    [foo]: /url 'title

    \n

    with blank line'

    \n

    [foo]

    \n", + "example": 166, + "start_line": 2877, + "end_line": 2887, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]:\n/url\n\n[foo]\n", + "html": "

    foo

    \n", + "example": 167, + "start_line": 2892, + "end_line": 2899, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]:\n\n[foo]\n", + "html": "

    [foo]:

    \n

    [foo]

    \n", + "example": 168, + "start_line": 2904, + "end_line": 2911, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: <>\n\n[foo]\n", + "html": "

    foo

    \n", + "example": 169, + "start_line": 2916, + "end_line": 2922, + "section": "Link reference definitions", + "shouldFail": true + }, + { + "markdown": "[foo]: (baz)\n\n[foo]\n", + "html": "

    [foo]: (baz)

    \n

    [foo]

    \n", + "example": 170, + "start_line": 2927, + "end_line": 2934, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url\\bar\\*baz \"foo\\\"bar\\baz\"\n\n[foo]\n", + "html": "

    foo

    \n", + "example": 171, + "start_line": 2940, + "end_line": 2946, + "section": "Link reference definitions", + "shouldFail": true + }, + { + "markdown": "[foo]\n\n[foo]: url\n", + "html": "

    foo

    \n", + "example": 172, + "start_line": 2951, + "end_line": 2957, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]\n\n[foo]: first\n[foo]: second\n", + "html": "

    foo

    \n", + "example": 173, + "start_line": 2963, + "end_line": 2970, + "section": "Link reference definitions" + }, + { + "markdown": "[FOO]: /url\n\n[Foo]\n", + "html": "

    Foo

    \n", + "example": 174, + "start_line": 2976, + "end_line": 2982, + "section": "Link reference definitions" + }, + { + "markdown": "[ΑΓΩ]: /φου\n\n[αγω]\n", + "html": "

    αγω

    \n", + "example": 175, + "start_line": 2985, + "end_line": 2991, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url\n", + "html": "", + "example": 176, + "start_line": 2997, + "end_line": 3000, + "section": "Link reference definitions" + }, + { + "markdown": "[\nfoo\n]: /url\nbar\n", + "html": "

    bar

    \n", + "example": 177, + "start_line": 3005, + "end_line": 3012, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url \"title\" ok\n", + "html": "

    [foo]: /url "title" ok

    \n", + "example": 178, + "start_line": 3018, + "end_line": 3022, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url\n\"title\" ok\n", + "html": "

    "title" ok

    \n", + "example": 179, + "start_line": 3027, + "end_line": 3032, + "section": "Link reference definitions" + }, + { + "markdown": " [foo]: /url \"title\"\n\n[foo]\n", + "html": "
    [foo]: /url "title"\n
    \n

    [foo]

    \n", + "example": 180, + "start_line": 3038, + "end_line": 3046, + "section": "Link reference definitions" + }, + { + "markdown": "```\n[foo]: /url\n```\n\n[foo]\n", + "html": "
    [foo]: /url\n
    \n

    [foo]

    \n", + "example": 181, + "start_line": 3052, + "end_line": 3062, + "section": "Link reference definitions" + }, + { + "markdown": "Foo\n[bar]: /baz\n\n[bar]\n", + "html": "

    Foo\n[bar]: /baz

    \n

    [bar]

    \n", + "example": 182, + "start_line": 3067, + "end_line": 3076, + "section": "Link reference definitions" + }, + { + "markdown": "# [Foo]\n[foo]: /url\n> bar\n", + "html": "

    Foo

    \n
    \n

    bar

    \n
    \n", + "example": 183, + "start_line": 3082, + "end_line": 3091, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url\nbar\n===\n[foo]\n", + "html": "

    bar

    \n

    foo

    \n", + "example": 184, + "start_line": 3093, + "end_line": 3101, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url\n===\n[foo]\n", + "html": "

    ===\nfoo

    \n", + "example": 185, + "start_line": 3103, + "end_line": 3110, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /foo-url \"foo\"\n[bar]: /bar-url\n \"bar\"\n[baz]: /baz-url\n\n[foo],\n[bar],\n[baz]\n", + "html": "

    foo,\nbar,\nbaz

    \n", + "example": 186, + "start_line": 3116, + "end_line": 3129, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]\n\n> [foo]: /url\n", + "html": "

    foo

    \n
    \n
    \n", + "example": 187, + "start_line": 3137, + "end_line": 3145, + "section": "Link reference definitions" + }, + { + "markdown": "[foo]: /url\n", + "html": "", + "example": 188, + "start_line": 3154, + "end_line": 3157, + "section": "Link reference definitions" + }, + { + "markdown": "aaa\n\nbbb\n", + "html": "

    aaa

    \n

    bbb

    \n", + "example": 189, + "start_line": 3171, + "end_line": 3178, + "section": "Paragraphs" + }, + { + "markdown": "aaa\nbbb\n\nccc\nddd\n", + "html": "

    aaa\nbbb

    \n

    ccc\nddd

    \n", + "example": 190, + "start_line": 3183, + "end_line": 3194, + "section": "Paragraphs" + }, + { + "markdown": "aaa\n\n\nbbb\n", + "html": "

    aaa

    \n

    bbb

    \n", + "example": 191, + "start_line": 3199, + "end_line": 3207, + "section": "Paragraphs" + }, + { + "markdown": " aaa\n bbb\n", + "html": "

    aaa\nbbb

    \n", + "example": 192, + "start_line": 3212, + "end_line": 3218, + "section": "Paragraphs" + }, + { + "markdown": "aaa\n bbb\n ccc\n", + "html": "

    aaa\nbbb\nccc

    \n", + "example": 193, + "start_line": 3224, + "end_line": 3232, + "section": "Paragraphs" + }, + { + "markdown": " aaa\nbbb\n", + "html": "

    aaa\nbbb

    \n", + "example": 194, + "start_line": 3238, + "end_line": 3244, + "section": "Paragraphs" + }, + { + "markdown": " aaa\nbbb\n", + "html": "
    aaa\n
    \n

    bbb

    \n", + "example": 195, + "start_line": 3247, + "end_line": 3254, + "section": "Paragraphs" + }, + { + "markdown": "aaa \nbbb \n", + "html": "

    aaa
    \nbbb

    \n", + "example": 196, + "start_line": 3261, + "end_line": 3267, + "section": "Paragraphs" + }, + { + "markdown": " \n\naaa\n \n\n# aaa\n\n \n", + "html": "

    aaa

    \n

    aaa

    \n", + "example": 197, + "start_line": 3278, + "end_line": 3290, + "section": "Blank lines" + }, + { + "markdown": "> # Foo\n> bar\n> baz\n", + "html": "
    \n

    Foo

    \n

    bar\nbaz

    \n
    \n", + "example": 198, + "start_line": 3344, + "end_line": 3354, + "section": "Block quotes" + }, + { + "markdown": "># Foo\n>bar\n> baz\n", + "html": "
    \n

    Foo

    \n

    bar\nbaz

    \n
    \n", + "example": 199, + "start_line": 3359, + "end_line": 3369, + "section": "Block quotes" + }, + { + "markdown": " > # Foo\n > bar\n > baz\n", + "html": "
    \n

    Foo

    \n

    bar\nbaz

    \n
    \n", + "example": 200, + "start_line": 3374, + "end_line": 3384, + "section": "Block quotes" + }, + { + "markdown": " > # Foo\n > bar\n > baz\n", + "html": "
    > # Foo\n> bar\n> baz\n
    \n", + "example": 201, + "start_line": 3389, + "end_line": 3398, + "section": "Block quotes" + }, + { + "markdown": "> # Foo\n> bar\nbaz\n", + "html": "
    \n

    Foo

    \n

    bar\nbaz

    \n
    \n", + "example": 202, + "start_line": 3404, + "end_line": 3414, + "section": "Block quotes" + }, + { + "markdown": "> bar\nbaz\n> foo\n", + "html": "
    \n

    bar\nbaz\nfoo

    \n
    \n", + "example": 203, + "start_line": 3420, + "end_line": 3430, + "section": "Block quotes" + }, + { + "markdown": "> foo\n---\n", + "html": "
    \n

    foo

    \n
    \n
    \n", + "example": 204, + "start_line": 3444, + "end_line": 3452, + "section": "Block quotes" + }, + { + "markdown": "> - foo\n- bar\n", + "html": "
    \n
      \n
    • foo
    • \n
    \n
    \n
      \n
    • bar
    • \n
    \n", + "example": 205, + "start_line": 3464, + "end_line": 3476, + "section": "Block quotes", + "shouldFail": true + }, + { + "markdown": "> foo\n bar\n", + "html": "
    \n
    foo\n
    \n
    \n
    bar\n
    \n", + "example": 206, + "start_line": 3482, + "end_line": 3492, + "section": "Block quotes", + "shouldFail": true + }, + { + "markdown": "> ```\nfoo\n```\n", + "html": "
    \n
    \n
    \n

    foo

    \n
    \n", + "example": 207, + "start_line": 3495, + "end_line": 3505, + "section": "Block quotes", + "shouldFail": true + }, + { + "markdown": "> foo\n - bar\n", + "html": "
    \n

    foo\n- bar

    \n
    \n", + "example": 208, + "start_line": 3511, + "end_line": 3519, + "section": "Block quotes" + }, + { + "markdown": ">\n", + "html": "
    \n
    \n", + "example": 209, + "start_line": 3535, + "end_line": 3540, + "section": "Block quotes" + }, + { + "markdown": ">\n> \n> \n", + "html": "
    \n
    \n", + "example": 210, + "start_line": 3543, + "end_line": 3550, + "section": "Block quotes" + }, + { + "markdown": ">\n> foo\n> \n", + "html": "
    \n

    foo

    \n
    \n", + "example": 211, + "start_line": 3555, + "end_line": 3563, + "section": "Block quotes" + }, + { + "markdown": "> foo\n\n> bar\n", + "html": "
    \n

    foo

    \n
    \n
    \n

    bar

    \n
    \n", + "example": 212, + "start_line": 3568, + "end_line": 3579, + "section": "Block quotes" + }, + { + "markdown": "> foo\n> bar\n", + "html": "
    \n

    foo\nbar

    \n
    \n", + "example": 213, + "start_line": 3590, + "end_line": 3598, + "section": "Block quotes" + }, + { + "markdown": "> foo\n>\n> bar\n", + "html": "
    \n

    foo

    \n

    bar

    \n
    \n", + "example": 214, + "start_line": 3603, + "end_line": 3612, + "section": "Block quotes" + }, + { + "markdown": "foo\n> bar\n", + "html": "

    foo

    \n
    \n

    bar

    \n
    \n", + "example": 215, + "start_line": 3617, + "end_line": 3625, + "section": "Block quotes" + }, + { + "markdown": "> aaa\n***\n> bbb\n", + "html": "
    \n

    aaa

    \n
    \n
    \n
    \n

    bbb

    \n
    \n", + "example": 216, + "start_line": 3631, + "end_line": 3643, + "section": "Block quotes" + }, + { + "markdown": "> bar\nbaz\n", + "html": "
    \n

    bar\nbaz

    \n
    \n", + "example": 217, + "start_line": 3649, + "end_line": 3657, + "section": "Block quotes" + }, + { + "markdown": "> bar\n\nbaz\n", + "html": "
    \n

    bar

    \n
    \n

    baz

    \n", + "example": 218, + "start_line": 3660, + "end_line": 3669, + "section": "Block quotes" + }, + { + "markdown": "> bar\n>\nbaz\n", + "html": "
    \n

    bar

    \n
    \n

    baz

    \n", + "example": 219, + "start_line": 3672, + "end_line": 3681, + "section": "Block quotes" + }, + { + "markdown": "> > > foo\nbar\n", + "html": "
    \n
    \n
    \n

    foo\nbar

    \n
    \n
    \n
    \n", + "example": 220, + "start_line": 3688, + "end_line": 3700, + "section": "Block quotes" + }, + { + "markdown": ">>> foo\n> bar\n>>baz\n", + "html": "
    \n
    \n
    \n

    foo\nbar\nbaz

    \n
    \n
    \n
    \n", + "example": 221, + "start_line": 3703, + "end_line": 3717, + "section": "Block quotes" + }, + { + "markdown": "> code\n\n> not code\n", + "html": "
    \n
    code\n
    \n
    \n
    \n

    not code

    \n
    \n", + "example": 222, + "start_line": 3725, + "end_line": 3737, + "section": "Block quotes" + }, + { + "markdown": "A paragraph\nwith two lines.\n\n indented code\n\n> A block quote.\n", + "html": "

    A paragraph\nwith two lines.

    \n
    indented code\n
    \n
    \n

    A block quote.

    \n
    \n", + "example": 223, + "start_line": 3779, + "end_line": 3794, + "section": "List items" + }, + { + "markdown": "1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n", + "html": "
      \n
    1. \n

      A paragraph\nwith two lines.

      \n
      indented code\n
      \n
      \n

      A block quote.

      \n
      \n
    2. \n
    \n", + "example": 224, + "start_line": 3801, + "end_line": 3820, + "section": "List items" + }, + { + "markdown": "- one\n\n two\n", + "html": "
      \n
    • one
    • \n
    \n

    two

    \n", + "example": 225, + "start_line": 3834, + "end_line": 3843, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "- one\n\n two\n", + "html": "
      \n
    • \n

      one

      \n

      two

      \n
    • \n
    \n", + "example": 226, + "start_line": 3846, + "end_line": 3857, + "section": "List items" + }, + { + "markdown": " - one\n\n two\n", + "html": "
      \n
    • one
    • \n
    \n
     two\n
    \n", + "example": 227, + "start_line": 3860, + "end_line": 3870, + "section": "List items", + "shouldFail": true + }, + { + "markdown": " - one\n\n two\n", + "html": "
      \n
    • \n

      one

      \n

      two

      \n
    • \n
    \n", + "example": 228, + "start_line": 3873, + "end_line": 3884, + "section": "List items" + }, + { + "markdown": " > > 1. one\n>>\n>> two\n", + "html": "
    \n
    \n
      \n
    1. \n

      one

      \n

      two

      \n
    2. \n
    \n
    \n
    \n", + "example": 229, + "start_line": 3895, + "end_line": 3910, + "section": "List items" + }, + { + "markdown": ">>- one\n>>\n > > two\n", + "html": "
    \n
    \n
      \n
    • one
    • \n
    \n

    two

    \n
    \n
    \n", + "example": 230, + "start_line": 3922, + "end_line": 3935, + "section": "List items" + }, + { + "markdown": "-one\n\n2.two\n", + "html": "

    -one

    \n

    2.two

    \n", + "example": 231, + "start_line": 3941, + "end_line": 3948, + "section": "List items" + }, + { + "markdown": "- foo\n\n\n bar\n", + "html": "
      \n
    • \n

      foo

      \n

      bar

      \n
    • \n
    \n", + "example": 232, + "start_line": 3954, + "end_line": 3966, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "1. foo\n\n ```\n bar\n ```\n\n baz\n\n > bam\n", + "html": "
      \n
    1. \n

      foo

      \n
      bar\n
      \n

      baz

      \n
      \n

      bam

      \n
      \n
    2. \n
    \n", + "example": 233, + "start_line": 3971, + "end_line": 3993, + "section": "List items" + }, + { + "markdown": "- Foo\n\n bar\n\n\n baz\n", + "html": "
      \n
    • \n

      Foo

      \n
      bar\n\n\nbaz\n
      \n
    • \n
    \n", + "example": 234, + "start_line": 3999, + "end_line": 4017, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "123456789. ok\n", + "html": "
      \n
    1. ok
    2. \n
    \n", + "example": 235, + "start_line": 4021, + "end_line": 4027, + "section": "List items" + }, + { + "markdown": "1234567890. not ok\n", + "html": "

    1234567890. not ok

    \n", + "example": 236, + "start_line": 4030, + "end_line": 4034, + "section": "List items" + }, + { + "markdown": "0. ok\n", + "html": "
      \n
    1. ok
    2. \n
    \n", + "example": 237, + "start_line": 4039, + "end_line": 4045, + "section": "List items" + }, + { + "markdown": "003. ok\n", + "html": "
      \n
    1. ok
    2. \n
    \n", + "example": 238, + "start_line": 4048, + "end_line": 4054, + "section": "List items" + }, + { + "markdown": "-1. not ok\n", + "html": "

    -1. not ok

    \n", + "example": 239, + "start_line": 4059, + "end_line": 4063, + "section": "List items" + }, + { + "markdown": "- foo\n\n bar\n", + "html": "
      \n
    • \n

      foo

      \n
      bar\n
      \n
    • \n
    \n", + "example": 240, + "start_line": 4082, + "end_line": 4094, + "section": "List items" + }, + { + "markdown": " 10. foo\n\n bar\n", + "html": "
      \n
    1. \n

      foo

      \n
      bar\n
      \n
    2. \n
    \n", + "example": 241, + "start_line": 4099, + "end_line": 4111, + "section": "List items" + }, + { + "markdown": " indented code\n\nparagraph\n\n more code\n", + "html": "
    indented code\n
    \n

    paragraph

    \n
    more code\n
    \n", + "example": 242, + "start_line": 4118, + "end_line": 4130, + "section": "List items" + }, + { + "markdown": "1. indented code\n\n paragraph\n\n more code\n", + "html": "
      \n
    1. \n
      indented code\n
      \n

      paragraph

      \n
      more code\n
      \n
    2. \n
    \n", + "example": 243, + "start_line": 4133, + "end_line": 4149, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "1. indented code\n\n paragraph\n\n more code\n", + "html": "
      \n
    1. \n
       indented code\n
      \n

      paragraph

      \n
      more code\n
      \n
    2. \n
    \n", + "example": 244, + "start_line": 4155, + "end_line": 4171, + "section": "List items", + "shouldFail": true + }, + { + "markdown": " foo\n\nbar\n", + "html": "

    foo

    \n

    bar

    \n", + "example": 245, + "start_line": 4182, + "end_line": 4189, + "section": "List items" + }, + { + "markdown": "- foo\n\n bar\n", + "html": "
      \n
    • foo
    • \n
    \n

    bar

    \n", + "example": 246, + "start_line": 4192, + "end_line": 4201, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "- foo\n\n bar\n", + "html": "
      \n
    • \n

      foo

      \n

      bar

      \n
    • \n
    \n", + "example": 247, + "start_line": 4209, + "end_line": 4220, + "section": "List items" + }, + { + "markdown": "-\n foo\n-\n ```\n bar\n ```\n-\n baz\n", + "html": "
      \n
    • foo
    • \n
    • \n
      bar\n
      \n
    • \n
    • \n
      baz\n
      \n
    • \n
    \n", + "example": 248, + "start_line": 4237, + "end_line": 4258, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "- \n foo\n", + "html": "
      \n
    • foo
    • \n
    \n", + "example": 249, + "start_line": 4263, + "end_line": 4270, + "section": "List items" + }, + { + "markdown": "-\n\n foo\n", + "html": "
      \n
    • \n
    \n

    foo

    \n", + "example": 250, + "start_line": 4277, + "end_line": 4286, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "- foo\n-\n- bar\n", + "html": "
      \n
    • foo
    • \n
    • \n
    • bar
    • \n
    \n", + "example": 251, + "start_line": 4291, + "end_line": 4301, + "section": "List items" + }, + { + "markdown": "- foo\n- \n- bar\n", + "html": "
      \n
    • foo
    • \n
    • \n
    • bar
    • \n
    \n", + "example": 252, + "start_line": 4306, + "end_line": 4316, + "section": "List items" + }, + { + "markdown": "1. foo\n2.\n3. bar\n", + "html": "
      \n
    1. foo
    2. \n
    3. \n
    4. bar
    5. \n
    \n", + "example": 253, + "start_line": 4321, + "end_line": 4331, + "section": "List items" + }, + { + "markdown": "*\n", + "html": "
      \n
    • \n
    \n", + "example": 254, + "start_line": 4336, + "end_line": 4342, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "foo\n*\n\nfoo\n1.\n", + "html": "

    foo\n*

    \n

    foo\n1.

    \n", + "example": 255, + "start_line": 4346, + "end_line": 4357, + "section": "List items" + }, + { + "markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n", + "html": "
      \n
    1. \n

      A paragraph\nwith two lines.

      \n
      indented code\n
      \n
      \n

      A block quote.

      \n
      \n
    2. \n
    \n", + "example": 256, + "start_line": 4368, + "end_line": 4387, + "section": "List items" + }, + { + "markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n", + "html": "
      \n
    1. \n

      A paragraph\nwith two lines.

      \n
      indented code\n
      \n
      \n

      A block quote.

      \n
      \n
    2. \n
    \n", + "example": 257, + "start_line": 4392, + "end_line": 4411, + "section": "List items" + }, + { + "markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n", + "html": "
      \n
    1. \n

      A paragraph\nwith two lines.

      \n
      indented code\n
      \n
      \n

      A block quote.

      \n
      \n
    2. \n
    \n", + "example": 258, + "start_line": 4416, + "end_line": 4435, + "section": "List items" + }, + { + "markdown": " 1. A paragraph\n with two lines.\n\n indented code\n\n > A block quote.\n", + "html": "
    1.  A paragraph\n    with two lines.\n\n        indented code\n\n    > A block quote.\n
    \n", + "example": 259, + "start_line": 4440, + "end_line": 4455, + "section": "List items" + }, + { + "markdown": " 1. A paragraph\nwith two lines.\n\n indented code\n\n > A block quote.\n", + "html": "
      \n
    1. \n

      A paragraph\nwith two lines.

      \n
      indented code\n
      \n
      \n

      A block quote.

      \n
      \n
    2. \n
    \n", + "example": 260, + "start_line": 4470, + "end_line": 4489, + "section": "List items" + }, + { + "markdown": " 1. A paragraph\n with two lines.\n", + "html": "
      \n
    1. A paragraph\nwith two lines.
    2. \n
    \n", + "example": 261, + "start_line": 4494, + "end_line": 4502, + "section": "List items" + }, + { + "markdown": "> 1. > Blockquote\ncontinued here.\n", + "html": "
    \n
      \n
    1. \n
      \n

      Blockquote\ncontinued here.

      \n
      \n
    2. \n
    \n
    \n", + "example": 262, + "start_line": 4507, + "end_line": 4521, + "section": "List items" + }, + { + "markdown": "> 1. > Blockquote\n> continued here.\n", + "html": "
    \n
      \n
    1. \n
      \n

      Blockquote\ncontinued here.

      \n
      \n
    2. \n
    \n
    \n", + "example": 263, + "start_line": 4524, + "end_line": 4538, + "section": "List items" + }, + { + "markdown": "- foo\n - bar\n - baz\n - boo\n", + "html": "
      \n
    • foo\n
        \n
      • bar\n
          \n
        • baz\n
            \n
          • boo
          • \n
          \n
        • \n
        \n
      • \n
      \n
    • \n
    \n", + "example": 264, + "start_line": 4552, + "end_line": 4573, + "section": "List items" + }, + { + "markdown": "- foo\n - bar\n - baz\n - boo\n", + "html": "
      \n
    • foo
    • \n
    • bar
    • \n
    • baz
    • \n
    • boo
    • \n
    \n", + "example": 265, + "start_line": 4578, + "end_line": 4590, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "10) foo\n - bar\n", + "html": "
      \n
    1. foo\n
        \n
      • bar
      • \n
      \n
    2. \n
    \n", + "example": 266, + "start_line": 4595, + "end_line": 4606, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "10) foo\n - bar\n", + "html": "
      \n
    1. foo
    2. \n
    \n
      \n
    • bar
    • \n
    \n", + "example": 267, + "start_line": 4611, + "end_line": 4621, + "section": "List items", + "shouldFail": true + }, + { + "markdown": "- - foo\n", + "html": "
      \n
    • \n
        \n
      • foo
      • \n
      \n
    • \n
    \n", + "example": 268, + "start_line": 4626, + "end_line": 4636, + "section": "List items" + }, + { + "markdown": "1. - 2. foo\n", + "html": "
      \n
    1. \n
        \n
      • \n
          \n
        1. foo
        2. \n
        \n
      • \n
      \n
    2. \n
    \n", + "example": 269, + "start_line": 4639, + "end_line": 4653, + "section": "List items" + }, + { + "markdown": "- # Foo\n- Bar\n ---\n baz\n", + "html": "
      \n
    • \n

      Foo

      \n
    • \n
    • \n

      Bar

      \nbaz
    • \n
    \n", + "example": 270, + "start_line": 4658, + "end_line": 4672, + "section": "List items" + }, + { + "markdown": "- foo\n- bar\n+ baz\n", + "html": "
      \n
    • foo
    • \n
    • bar
    • \n
    \n
      \n
    • baz
    • \n
    \n", + "example": 271, + "start_line": 4894, + "end_line": 4906, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "1. foo\n2. bar\n3) baz\n", + "html": "
      \n
    1. foo
    2. \n
    3. bar
    4. \n
    \n
      \n
    1. baz
    2. \n
    \n", + "example": 272, + "start_line": 4909, + "end_line": 4921, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "Foo\n- bar\n- baz\n", + "html": "

    Foo

    \n
      \n
    • bar
    • \n
    • baz
    • \n
    \n", + "example": 273, + "start_line": 4928, + "end_line": 4938, + "section": "Lists" + }, + { + "markdown": "The number of windows in my house is\n14. The number of doors is 6.\n", + "html": "

    The number of windows in my house is\n14. The number of doors is 6.

    \n", + "example": 274, + "start_line": 5005, + "end_line": 5011, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "The number of windows in my house is\n1. The number of doors is 6.\n", + "html": "

    The number of windows in my house is

    \n
      \n
    1. The number of doors is 6.
    2. \n
    \n", + "example": 275, + "start_line": 5015, + "end_line": 5023, + "section": "Lists" + }, + { + "markdown": "- foo\n\n- bar\n\n\n- baz\n", + "html": "
      \n
    • \n

      foo

      \n
    • \n
    • \n

      bar

      \n
    • \n
    • \n

      baz

      \n
    • \n
    \n", + "example": 276, + "start_line": 5029, + "end_line": 5048, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "- foo\n - bar\n - baz\n\n\n bim\n", + "html": "
      \n
    • foo\n
        \n
      • bar\n
          \n
        • \n

          baz

          \n

          bim

          \n
        • \n
        \n
      • \n
      \n
    • \n
    \n", + "example": 277, + "start_line": 5050, + "end_line": 5072, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "- foo\n- bar\n\n\n\n- baz\n- bim\n", + "html": "
      \n
    • foo
    • \n
    • bar
    • \n
    \n\n
      \n
    • baz
    • \n
    • bim
    • \n
    \n", + "example": 278, + "start_line": 5080, + "end_line": 5098, + "section": "Lists" + }, + { + "markdown": "- foo\n\n notcode\n\n- foo\n\n\n\n code\n", + "html": "
      \n
    • \n

      foo

      \n

      notcode

      \n
    • \n
    • \n

      foo

      \n
    • \n
    \n\n
    code\n
    \n", + "example": 279, + "start_line": 5101, + "end_line": 5124, + "section": "Lists" + }, + { + "markdown": "- a\n - b\n - c\n - d\n - e\n - f\n- g\n", + "html": "
      \n
    • a
    • \n
    • b
    • \n
    • c
    • \n
    • d
    • \n
    • e
    • \n
    • f
    • \n
    • g
    • \n
    \n", + "example": 280, + "start_line": 5132, + "end_line": 5150, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "1. a\n\n 2. b\n\n 3. c\n", + "html": "
      \n
    1. \n

      a

      \n
    2. \n
    3. \n

      b

      \n
    4. \n
    5. \n

      c

      \n
    6. \n
    \n", + "example": 281, + "start_line": 5153, + "end_line": 5171, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "- a\n - b\n - c\n - d\n - e\n", + "html": "
      \n
    • a
    • \n
    • b
    • \n
    • c
    • \n
    • d\n- e
    • \n
    \n", + "example": 282, + "start_line": 5177, + "end_line": 5191, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "1. a\n\n 2. b\n\n 3. c\n", + "html": "
      \n
    1. \n

      a

      \n
    2. \n
    3. \n

      b

      \n
    4. \n
    \n
    3. c\n
    \n", + "example": 283, + "start_line": 5197, + "end_line": 5214, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "- a\n- b\n\n- c\n", + "html": "
      \n
    • \n

      a

      \n
    • \n
    • \n

      b

      \n
    • \n
    • \n

      c

      \n
    • \n
    \n", + "example": 284, + "start_line": 5220, + "end_line": 5237, + "section": "Lists" + }, + { + "markdown": "* a\n*\n\n* c\n", + "html": "
      \n
    • \n

      a

      \n
    • \n
    • \n
    • \n

      c

      \n
    • \n
    \n", + "example": 285, + "start_line": 5242, + "end_line": 5257, + "section": "Lists" + }, + { + "markdown": "- a\n- b\n\n c\n- d\n", + "html": "
      \n
    • \n

      a

      \n
    • \n
    • \n

      b

      \n

      c

      \n
    • \n
    • \n

      d

      \n
    • \n
    \n", + "example": 286, + "start_line": 5264, + "end_line": 5283, + "section": "Lists" + }, + { + "markdown": "- a\n- b\n\n [ref]: /url\n- d\n", + "html": "
      \n
    • \n

      a

      \n
    • \n
    • \n

      b

      \n
    • \n
    • \n

      d

      \n
    • \n
    \n", + "example": 287, + "start_line": 5286, + "end_line": 5304, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "- a\n- ```\n b\n\n\n ```\n- c\n", + "html": "
      \n
    • a
    • \n
    • \n
      b\n\n\n
      \n
    • \n
    • c
    • \n
    \n", + "example": 288, + "start_line": 5309, + "end_line": 5328, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "- a\n - b\n\n c\n- d\n", + "html": "
      \n
    • a\n
        \n
      • \n

        b

        \n

        c

        \n
      • \n
      \n
    • \n
    • d
    • \n
    \n", + "example": 289, + "start_line": 5335, + "end_line": 5353, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "* a\n > b\n >\n* c\n", + "html": "
      \n
    • a\n
      \n

      b

      \n
      \n
    • \n
    • c
    • \n
    \n", + "example": 290, + "start_line": 5359, + "end_line": 5373, + "section": "Lists" + }, + { + "markdown": "- a\n > b\n ```\n c\n ```\n- d\n", + "html": "
      \n
    • a\n
      \n

      b

      \n
      \n
      c\n
      \n
    • \n
    • d
    • \n
    \n", + "example": 291, + "start_line": 5379, + "end_line": 5397, + "section": "Lists", + "shouldFail": true + }, + { + "markdown": "- a\n", + "html": "
      \n
    • a
    • \n
    \n", + "example": 292, + "start_line": 5402, + "end_line": 5408, + "section": "Lists" + }, + { + "markdown": "- a\n - b\n", + "html": "
      \n
    • a\n
        \n
      • b
      • \n
      \n
    • \n
    \n", + "example": 293, + "start_line": 5411, + "end_line": 5422, + "section": "Lists" + }, + { + "markdown": "1. ```\n foo\n ```\n\n bar\n", + "html": "
      \n
    1. \n
      foo\n
      \n

      bar

      \n
    2. \n
    \n", + "example": 294, + "start_line": 5428, + "end_line": 5442, + "section": "Lists" + }, + { + "markdown": "* foo\n * bar\n\n baz\n", + "html": "
      \n
    • \n

      foo

      \n
        \n
      • bar
      • \n
      \n

      baz

      \n
    • \n
    \n", + "example": 295, + "start_line": 5447, + "end_line": 5462, + "section": "Lists" + }, + { + "markdown": "- a\n - b\n - c\n\n- d\n - e\n - f\n", + "html": "
      \n
    • \n

      a

      \n
        \n
      • b
      • \n
      • c
      • \n
      \n
    • \n
    • \n

      d

      \n
        \n
      • e
      • \n
      • f
      • \n
      \n
    • \n
    \n", + "example": 296, + "start_line": 5465, + "end_line": 5490, + "section": "Lists" + }, + { + "markdown": "`hi`lo`\n", + "html": "

    hilo`

    \n", + "example": 297, + "start_line": 5499, + "end_line": 5503, + "section": "Inlines" + }, + { + "markdown": "\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\n", + "html": "

    !"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~

    \n", + "example": 298, + "start_line": 5513, + "end_line": 5517, + "section": "Backslash escapes" + }, + { + "markdown": "\\\t\\A\\a\\ \\3\\φ\\«\n", + "html": "

    \\\t\\A\\a\\ \\3\\φ\\«

    \n", + "example": 299, + "start_line": 5523, + "end_line": 5527, + "section": "Backslash escapes" + }, + { + "markdown": "\\*not emphasized*\n\\
    not a tag\n\\[not a link](/foo)\n\\`not code`\n1\\. not a list\n\\* not a list\n\\# not a heading\n\\[foo]: /url \"not a reference\"\n\\ö not a character entity\n", + "html": "

    *not emphasized*\n<br/> not a tag\n[not a link](/foo)\n`not code`\n1. not a list\n* not a list\n# not a heading\n[foo]: /url "not a reference"\n&ouml; not a character entity

    \n", + "example": 300, + "start_line": 5533, + "end_line": 5553, + "section": "Backslash escapes" + }, + { + "markdown": "\\\\*emphasis*\n", + "html": "

    \\emphasis

    \n", + "example": 301, + "start_line": 5558, + "end_line": 5562, + "section": "Backslash escapes" + }, + { + "markdown": "foo\\\nbar\n", + "html": "

    foo
    \nbar

    \n", + "example": 302, + "start_line": 5567, + "end_line": 5573, + "section": "Backslash escapes" + }, + { + "markdown": "`` \\[\\` ``\n", + "html": "

    \\[\\`

    \n", + "example": 303, + "start_line": 5579, + "end_line": 5583, + "section": "Backslash escapes" + }, + { + "markdown": " \\[\\]\n", + "html": "
    \\[\\]\n
    \n", + "example": 304, + "start_line": 5586, + "end_line": 5591, + "section": "Backslash escapes" + }, + { + "markdown": "~~~\n\\[\\]\n~~~\n", + "html": "
    \\[\\]\n
    \n", + "example": 305, + "start_line": 5594, + "end_line": 5601, + "section": "Backslash escapes" + }, + { + "markdown": "\n", + "html": "

    http://example.com?find=\\*

    \n", + "example": 306, + "start_line": 5604, + "end_line": 5608, + "section": "Backslash escapes" + }, + { + "markdown": "\n", + "html": "\n", + "example": 307, + "start_line": 5611, + "end_line": 5615, + "section": "Backslash escapes" + }, + { + "markdown": "[foo](/bar\\* \"ti\\*tle\")\n", + "html": "

    foo

    \n", + "example": 308, + "start_line": 5621, + "end_line": 5625, + "section": "Backslash escapes" + }, + { + "markdown": "[foo]\n\n[foo]: /bar\\* \"ti\\*tle\"\n", + "html": "

    foo

    \n", + "example": 309, + "start_line": 5628, + "end_line": 5634, + "section": "Backslash escapes", + "shouldFail": true + }, + { + "markdown": "``` foo\\+bar\nfoo\n```\n", + "html": "
    foo\n
    \n", + "example": 310, + "start_line": 5637, + "end_line": 5644, + "section": "Backslash escapes", + "shouldFail": true + }, + { + "markdown": "  & © Æ Ď\n¾ ℋ ⅆ\n∲ ≧̸\n", + "html": "

      & © Æ Ď\n¾ ℋ ⅆ\n∲ ≧̸

    \n", + "example": 311, + "start_line": 5674, + "end_line": 5682, + "section": "Entity and numeric character references" + }, + { + "markdown": "# Ӓ Ϡ �\n", + "html": "

    # Ӓ Ϡ �

    \n", + "example": 312, + "start_line": 5693, + "end_line": 5697, + "section": "Entity and numeric character references" + }, + { + "markdown": "" ആ ಫ\n", + "html": "

    " ആ ಫ

    \n", + "example": 313, + "start_line": 5706, + "end_line": 5710, + "section": "Entity and numeric character references" + }, + { + "markdown": "  &x; &#; &#x;\n�\n&#abcdef0;\n&ThisIsNotDefined; &hi?;\n", + "html": "

    &nbsp &x; &#; &#x;\n&#987654321;\n&#abcdef0;\n&ThisIsNotDefined; &hi?;

    \n", + "example": 314, + "start_line": 5715, + "end_line": 5725, + "section": "Entity and numeric character references", + "shouldFail": true + }, + { + "markdown": "©\n", + "html": "

    &copy

    \n", + "example": 315, + "start_line": 5732, + "end_line": 5736, + "section": "Entity and numeric character references" + }, + { + "markdown": "&MadeUpEntity;\n", + "html": "

    &MadeUpEntity;

    \n", + "example": 316, + "start_line": 5742, + "end_line": 5746, + "section": "Entity and numeric character references" + }, + { + "markdown": "\n", + "html": "\n", + "example": 317, + "start_line": 5753, + "end_line": 5757, + "section": "Entity and numeric character references" + }, + { + "markdown": "[foo](/föö \"föö\")\n", + "html": "

    foo

    \n", + "example": 318, + "start_line": 5760, + "end_line": 5764, + "section": "Entity and numeric character references", + "shouldFail": true + }, + { + "markdown": "[foo]\n\n[foo]: /föö \"föö\"\n", + "html": "

    foo

    \n", + "example": 319, + "start_line": 5767, + "end_line": 5773, + "section": "Entity and numeric character references", + "shouldFail": true + }, + { + "markdown": "``` föö\nfoo\n```\n", + "html": "
    foo\n
    \n", + "example": 320, + "start_line": 5776, + "end_line": 5783, + "section": "Entity and numeric character references", + "shouldFail": true + }, + { + "markdown": "`föö`\n", + "html": "

    f&ouml;&ouml;

    \n", + "example": 321, + "start_line": 5789, + "end_line": 5793, + "section": "Entity and numeric character references" + }, + { + "markdown": " föfö\n", + "html": "
    f&ouml;f&ouml;\n
    \n", + "example": 322, + "start_line": 5796, + "end_line": 5801, + "section": "Entity and numeric character references" + }, + { + "markdown": "*foo*\n*foo*\n", + "html": "

    *foo*\nfoo

    \n", + "example": 323, + "start_line": 5808, + "end_line": 5814, + "section": "Entity and numeric character references" + }, + { + "markdown": "* foo\n\n* foo\n", + "html": "

    * foo

    \n
      \n
    • foo
    • \n
    \n", + "example": 324, + "start_line": 5816, + "end_line": 5825, + "section": "Entity and numeric character references" + }, + { + "markdown": "foo bar\n", + "html": "

    foo\n\nbar

    \n", + "example": 325, + "start_line": 5827, + "end_line": 5833, + "section": "Entity and numeric character references" + }, + { + "markdown": " foo\n", + "html": "

    \tfoo

    \n", + "example": 326, + "start_line": 5835, + "end_line": 5839, + "section": "Entity and numeric character references" + }, + { + "markdown": "[a](url "tit")\n", + "html": "

    [a](url "tit")

    \n", + "example": 327, + "start_line": 5842, + "end_line": 5846, + "section": "Entity and numeric character references" + }, + { + "markdown": "`foo`\n", + "html": "

    foo

    \n", + "example": 328, + "start_line": 5870, + "end_line": 5874, + "section": "Code spans" + }, + { + "markdown": "`` foo ` bar ``\n", + "html": "

    foo ` bar

    \n", + "example": 329, + "start_line": 5881, + "end_line": 5885, + "section": "Code spans" + }, + { + "markdown": "` `` `\n", + "html": "

    ``

    \n", + "example": 330, + "start_line": 5891, + "end_line": 5895, + "section": "Code spans" + }, + { + "markdown": "` `` `\n", + "html": "

    ``

    \n", + "example": 331, + "start_line": 5899, + "end_line": 5903, + "section": "Code spans" + }, + { + "markdown": "` a`\n", + "html": "

    a

    \n", + "example": 332, + "start_line": 5908, + "end_line": 5912, + "section": "Code spans" + }, + { + "markdown": "` b `\n", + "html": "

     b 

    \n", + "example": 333, + "start_line": 5917, + "end_line": 5921, + "section": "Code spans" + }, + { + "markdown": "` `\n` `\n", + "html": "

     \n

    \n", + "example": 334, + "start_line": 5925, + "end_line": 5931, + "section": "Code spans" + }, + { + "markdown": "``\nfoo\nbar \nbaz\n``\n", + "html": "

    foo bar baz

    \n", + "example": 335, + "start_line": 5936, + "end_line": 5944, + "section": "Code spans" + }, + { + "markdown": "``\nfoo \n``\n", + "html": "

    foo

    \n", + "example": 336, + "start_line": 5946, + "end_line": 5952, + "section": "Code spans" + }, + { + "markdown": "`foo bar \nbaz`\n", + "html": "

    foo bar baz

    \n", + "example": 337, + "start_line": 5957, + "end_line": 5962, + "section": "Code spans" + }, + { + "markdown": "`foo\\`bar`\n", + "html": "

    foo\\bar`

    \n", + "example": 338, + "start_line": 5974, + "end_line": 5978, + "section": "Code spans" + }, + { + "markdown": "``foo`bar``\n", + "html": "

    foo`bar

    \n", + "example": 339, + "start_line": 5985, + "end_line": 5989, + "section": "Code spans" + }, + { + "markdown": "` foo `` bar `\n", + "html": "

    foo `` bar

    \n", + "example": 340, + "start_line": 5991, + "end_line": 5995, + "section": "Code spans" + }, + { + "markdown": "*foo`*`\n", + "html": "

    *foo*

    \n", + "example": 341, + "start_line": 6003, + "end_line": 6007, + "section": "Code spans", + "shouldFail": true + }, + { + "markdown": "[not a `link](/foo`)\n", + "html": "

    [not a link](/foo)

    \n", + "example": 342, + "start_line": 6012, + "end_line": 6016, + "section": "Code spans", + "shouldFail": true + }, + { + "markdown": "``\n", + "html": "

    <a href="">`

    \n", + "example": 343, + "start_line": 6022, + "end_line": 6026, + "section": "Code spans" + }, + { + "markdown": "
    `\n", + "html": "

    `

    \n", + "example": 344, + "start_line": 6031, + "end_line": 6035, + "section": "Code spans" + }, + { + "markdown": "``\n", + "html": "

    <http://foo.bar.baz>`

    \n", + "example": 345, + "start_line": 6040, + "end_line": 6044, + "section": "Code spans" + }, + { + "markdown": "`\n", + "html": "

    http://foo.bar.`baz`

    \n", + "example": 346, + "start_line": 6049, + "end_line": 6053, + "section": "Code spans" + }, + { + "markdown": "```foo``\n", + "html": "

    ```foo``

    \n", + "example": 347, + "start_line": 6059, + "end_line": 6063, + "section": "Code spans" + }, + { + "markdown": "`foo\n", + "html": "

    `foo

    \n", + "example": 348, + "start_line": 6066, + "end_line": 6070, + "section": "Code spans" + }, + { + "markdown": "`foo``bar``\n", + "html": "

    `foobar

    \n", + "example": 349, + "start_line": 6075, + "end_line": 6079, + "section": "Code spans" + }, + { + "markdown": "*foo bar*\n", + "html": "

    foo bar

    \n", + "example": 350, + "start_line": 6292, + "end_line": 6296, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "a * foo bar*\n", + "html": "

    a * foo bar*

    \n", + "example": 351, + "start_line": 6302, + "end_line": 6306, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "a*\"foo\"*\n", + "html": "

    a*"foo"*

    \n", + "example": 352, + "start_line": 6313, + "end_line": 6317, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "* a *\n", + "html": "

    * a *

    \n", + "example": 353, + "start_line": 6322, + "end_line": 6326, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "foo*bar*\n", + "html": "

    foobar

    \n", + "example": 354, + "start_line": 6331, + "end_line": 6335, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "5*6*78\n", + "html": "

    5678

    \n", + "example": 355, + "start_line": 6338, + "end_line": 6342, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_foo bar_\n", + "html": "

    foo bar

    \n", + "example": 356, + "start_line": 6347, + "end_line": 6351, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_ foo bar_\n", + "html": "

    _ foo bar_

    \n", + "example": 357, + "start_line": 6357, + "end_line": 6361, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "a_\"foo\"_\n", + "html": "

    a_"foo"_

    \n", + "example": 358, + "start_line": 6367, + "end_line": 6371, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo_bar_\n", + "html": "

    foo_bar_

    \n", + "example": 359, + "start_line": 6376, + "end_line": 6380, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "5_6_78\n", + "html": "

    5_6_78

    \n", + "example": 360, + "start_line": 6383, + "end_line": 6387, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "пристаням_стремятся_\n", + "html": "

    пристаням_стремятся_

    \n", + "example": 361, + "start_line": 6390, + "end_line": 6394, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "aa_\"bb\"_cc\n", + "html": "

    aa_"bb"_cc

    \n", + "example": 362, + "start_line": 6400, + "end_line": 6404, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo-_(bar)_\n", + "html": "

    foo-(bar)

    \n", + "example": 363, + "start_line": 6411, + "end_line": 6415, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_foo*\n", + "html": "

    _foo*

    \n", + "example": 364, + "start_line": 6423, + "end_line": 6427, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo bar *\n", + "html": "

    *foo bar *

    \n", + "example": 365, + "start_line": 6433, + "end_line": 6437, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo bar\n*\n", + "html": "

    *foo bar\n*

    \n", + "example": 366, + "start_line": 6442, + "end_line": 6448, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*(*foo)\n", + "html": "

    *(*foo)

    \n", + "example": 367, + "start_line": 6455, + "end_line": 6459, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*(*foo*)*\n", + "html": "

    (foo)

    \n", + "example": 368, + "start_line": 6465, + "end_line": 6469, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo*bar\n", + "html": "

    foobar

    \n", + "example": 369, + "start_line": 6474, + "end_line": 6478, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_foo bar _\n", + "html": "

    _foo bar _

    \n", + "example": 370, + "start_line": 6487, + "end_line": 6491, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_(_foo)\n", + "html": "

    _(_foo)

    \n", + "example": 371, + "start_line": 6497, + "end_line": 6501, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "_(_foo_)_\n", + "html": "

    (foo)

    \n", + "example": 372, + "start_line": 6506, + "end_line": 6510, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "_foo_bar\n", + "html": "

    _foo_bar

    \n", + "example": 373, + "start_line": 6515, + "end_line": 6519, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_пристаням_стремятся\n", + "html": "

    _пристаням_стремятся

    \n", + "example": 374, + "start_line": 6522, + "end_line": 6526, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_foo_bar_baz_\n", + "html": "

    foo_bar_baz

    \n", + "example": 375, + "start_line": 6529, + "end_line": 6533, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_(bar)_.\n", + "html": "

    (bar).

    \n", + "example": 376, + "start_line": 6540, + "end_line": 6544, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo bar**\n", + "html": "

    foo bar

    \n", + "example": 377, + "start_line": 6549, + "end_line": 6553, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "** foo bar**\n", + "html": "

    ** foo bar**

    \n", + "example": 378, + "start_line": 6559, + "end_line": 6563, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "a**\"foo\"**\n", + "html": "

    a**"foo"**

    \n", + "example": 379, + "start_line": 6570, + "end_line": 6574, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "foo**bar**\n", + "html": "

    foobar

    \n", + "example": 380, + "start_line": 6579, + "end_line": 6583, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__foo bar__\n", + "html": "

    foo bar

    \n", + "example": 381, + "start_line": 6588, + "end_line": 6592, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__ foo bar__\n", + "html": "

    __ foo bar__

    \n", + "example": 382, + "start_line": 6598, + "end_line": 6602, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__\nfoo bar__\n", + "html": "

    __\nfoo bar__

    \n", + "example": 383, + "start_line": 6606, + "end_line": 6612, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "a__\"foo\"__\n", + "html": "

    a__"foo"__

    \n", + "example": 384, + "start_line": 6618, + "end_line": 6622, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo__bar__\n", + "html": "

    foo__bar__

    \n", + "example": 385, + "start_line": 6627, + "end_line": 6631, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "5__6__78\n", + "html": "

    5__6__78

    \n", + "example": 386, + "start_line": 6634, + "end_line": 6638, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "пристаням__стремятся__\n", + "html": "

    пристаням__стремятся__

    \n", + "example": 387, + "start_line": 6641, + "end_line": 6645, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__foo, __bar__, baz__\n", + "html": "

    foo, bar, baz

    \n", + "example": 388, + "start_line": 6648, + "end_line": 6652, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "foo-__(bar)__\n", + "html": "

    foo-(bar)

    \n", + "example": 389, + "start_line": 6659, + "end_line": 6663, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo bar **\n", + "html": "

    **foo bar **

    \n", + "example": 390, + "start_line": 6672, + "end_line": 6676, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "**(**foo)\n", + "html": "

    **(**foo)

    \n", + "example": 391, + "start_line": 6685, + "end_line": 6689, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*(**foo**)*\n", + "html": "

    (foo)

    \n", + "example": 392, + "start_line": 6695, + "end_line": 6699, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**Gomphocarpus (*Gomphocarpus physocarpus*, syn.\n*Asclepias physocarpa*)**\n", + "html": "

    Gomphocarpus (Gomphocarpus physocarpus, syn.\nAsclepias physocarpa)

    \n", + "example": 393, + "start_line": 6702, + "end_line": 6708, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo \"*bar*\" foo**\n", + "html": "

    foo "bar" foo

    \n", + "example": 394, + "start_line": 6711, + "end_line": 6715, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo**bar\n", + "html": "

    foobar

    \n", + "example": 395, + "start_line": 6720, + "end_line": 6724, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__foo bar __\n", + "html": "

    __foo bar __

    \n", + "example": 396, + "start_line": 6732, + "end_line": 6736, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__(__foo)\n", + "html": "

    __(__foo)

    \n", + "example": 397, + "start_line": 6742, + "end_line": 6746, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "_(__foo__)_\n", + "html": "

    (foo)

    \n", + "example": 398, + "start_line": 6752, + "end_line": 6756, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__foo__bar\n", + "html": "

    __foo__bar

    \n", + "example": 399, + "start_line": 6761, + "end_line": 6765, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__пристаням__стремятся\n", + "html": "

    __пристаням__стремятся

    \n", + "example": 400, + "start_line": 6768, + "end_line": 6772, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__foo__bar__baz__\n", + "html": "

    foo__bar__baz

    \n", + "example": 401, + "start_line": 6775, + "end_line": 6779, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__(bar)__.\n", + "html": "

    (bar).

    \n", + "example": 402, + "start_line": 6786, + "end_line": 6790, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo [bar](/url)*\n", + "html": "

    foo bar

    \n", + "example": 403, + "start_line": 6798, + "end_line": 6802, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo\nbar*\n", + "html": "

    foo\nbar

    \n", + "example": 404, + "start_line": 6805, + "end_line": 6811, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_foo __bar__ baz_\n", + "html": "

    foo bar baz

    \n", + "example": 405, + "start_line": 6817, + "end_line": 6821, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_foo _bar_ baz_\n", + "html": "

    foo bar baz

    \n", + "example": 406, + "start_line": 6824, + "end_line": 6828, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__foo_ bar_\n", + "html": "

    foo bar

    \n", + "example": 407, + "start_line": 6831, + "end_line": 6835, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo *bar**\n", + "html": "

    foo bar

    \n", + "example": 408, + "start_line": 6838, + "end_line": 6842, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo **bar** baz*\n", + "html": "

    foo bar baz

    \n", + "example": 409, + "start_line": 6845, + "end_line": 6849, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo**bar**baz*\n", + "html": "

    foobarbaz

    \n", + "example": 410, + "start_line": 6851, + "end_line": 6855, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo**bar*\n", + "html": "

    foo**bar

    \n", + "example": 411, + "start_line": 6875, + "end_line": 6879, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "***foo** bar*\n", + "html": "

    foo bar

    \n", + "example": 412, + "start_line": 6888, + "end_line": 6892, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo **bar***\n", + "html": "

    foo bar

    \n", + "example": 413, + "start_line": 6895, + "end_line": 6899, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo**bar***\n", + "html": "

    foobar

    \n", + "example": 414, + "start_line": 6902, + "end_line": 6906, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "foo***bar***baz\n", + "html": "

    foobarbaz

    \n", + "example": 415, + "start_line": 6913, + "end_line": 6917, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "foo******bar*********baz\n", + "html": "

    foobar***baz

    \n", + "example": 416, + "start_line": 6919, + "end_line": 6923, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo **bar *baz* bim** bop*\n", + "html": "

    foo bar baz bim bop

    \n", + "example": 417, + "start_line": 6928, + "end_line": 6932, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo [*bar*](/url)*\n", + "html": "

    foo bar

    \n", + "example": 418, + "start_line": 6935, + "end_line": 6939, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "** is not an empty emphasis\n", + "html": "

    ** is not an empty emphasis

    \n", + "example": 419, + "start_line": 6944, + "end_line": 6948, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**** is not an empty strong emphasis\n", + "html": "

    **** is not an empty strong emphasis

    \n", + "example": 420, + "start_line": 6951, + "end_line": 6955, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo [bar](/url)**\n", + "html": "

    foo bar

    \n", + "example": 421, + "start_line": 6964, + "end_line": 6968, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo\nbar**\n", + "html": "

    foo\nbar

    \n", + "example": 422, + "start_line": 6971, + "end_line": 6977, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__foo _bar_ baz__\n", + "html": "

    foo bar baz

    \n", + "example": 423, + "start_line": 6983, + "end_line": 6987, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__foo __bar__ baz__\n", + "html": "

    foo bar baz

    \n", + "example": 424, + "start_line": 6990, + "end_line": 6994, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "____foo__ bar__\n", + "html": "

    foo bar

    \n", + "example": 425, + "start_line": 6997, + "end_line": 7001, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "**foo **bar****\n", + "html": "

    foo bar

    \n", + "example": 426, + "start_line": 7004, + "end_line": 7008, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo *bar* baz**\n", + "html": "

    foo bar baz

    \n", + "example": 427, + "start_line": 7011, + "end_line": 7015, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo*bar*baz**\n", + "html": "

    foobarbaz

    \n", + "example": 428, + "start_line": 7018, + "end_line": 7022, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "***foo* bar**\n", + "html": "

    foo bar

    \n", + "example": 429, + "start_line": 7025, + "end_line": 7029, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo *bar***\n", + "html": "

    foo bar

    \n", + "example": 430, + "start_line": 7032, + "end_line": 7036, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo *bar **baz**\nbim* bop**\n", + "html": "

    foo bar baz\nbim bop

    \n", + "example": 431, + "start_line": 7041, + "end_line": 7047, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "**foo [*bar*](/url)**\n", + "html": "

    foo bar

    \n", + "example": 432, + "start_line": 7050, + "end_line": 7054, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__ is not an empty emphasis\n", + "html": "

    __ is not an empty emphasis

    \n", + "example": 433, + "start_line": 7059, + "end_line": 7063, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "____ is not an empty strong emphasis\n", + "html": "

    ____ is not an empty strong emphasis

    \n", + "example": 434, + "start_line": 7066, + "end_line": 7070, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo ***\n", + "html": "

    foo ***

    \n", + "example": 435, + "start_line": 7076, + "end_line": 7080, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo *\\**\n", + "html": "

    foo *

    \n", + "example": 436, + "start_line": 7083, + "end_line": 7087, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo *_*\n", + "html": "

    foo _

    \n", + "example": 437, + "start_line": 7090, + "end_line": 7094, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo *****\n", + "html": "

    foo *****

    \n", + "example": 438, + "start_line": 7097, + "end_line": 7101, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo **\\***\n", + "html": "

    foo *

    \n", + "example": 439, + "start_line": 7104, + "end_line": 7108, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo **_**\n", + "html": "

    foo _

    \n", + "example": 440, + "start_line": 7111, + "end_line": 7115, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo*\n", + "html": "

    *foo

    \n", + "example": 441, + "start_line": 7122, + "end_line": 7126, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo**\n", + "html": "

    foo*

    \n", + "example": 442, + "start_line": 7129, + "end_line": 7133, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "***foo**\n", + "html": "

    *foo

    \n", + "example": 443, + "start_line": 7136, + "end_line": 7140, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "****foo*\n", + "html": "

    ***foo

    \n", + "example": 444, + "start_line": 7143, + "end_line": 7147, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "**foo***\n", + "html": "

    foo*

    \n", + "example": 445, + "start_line": 7150, + "end_line": 7154, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo****\n", + "html": "

    foo***

    \n", + "example": 446, + "start_line": 7157, + "end_line": 7161, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "foo ___\n", + "html": "

    foo ___

    \n", + "example": 447, + "start_line": 7167, + "end_line": 7171, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo _\\__\n", + "html": "

    foo _

    \n", + "example": 448, + "start_line": 7174, + "end_line": 7178, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo _*_\n", + "html": "

    foo *

    \n", + "example": 449, + "start_line": 7181, + "end_line": 7185, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo _____\n", + "html": "

    foo _____

    \n", + "example": 450, + "start_line": 7188, + "end_line": 7192, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo __\\___\n", + "html": "

    foo _

    \n", + "example": 451, + "start_line": 7195, + "end_line": 7199, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "foo __*__\n", + "html": "

    foo *

    \n", + "example": 452, + "start_line": 7202, + "end_line": 7206, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__foo_\n", + "html": "

    _foo

    \n", + "example": 453, + "start_line": 7209, + "end_line": 7213, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "_foo__\n", + "html": "

    foo_

    \n", + "example": 454, + "start_line": 7220, + "end_line": 7224, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "___foo__\n", + "html": "

    _foo

    \n", + "example": 455, + "start_line": 7227, + "end_line": 7231, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "____foo_\n", + "html": "

    ___foo

    \n", + "example": 456, + "start_line": 7234, + "end_line": 7238, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__foo___\n", + "html": "

    foo_

    \n", + "example": 457, + "start_line": 7241, + "end_line": 7245, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "_foo____\n", + "html": "

    foo___

    \n", + "example": 458, + "start_line": 7248, + "end_line": 7252, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "**foo**\n", + "html": "

    foo

    \n", + "example": 459, + "start_line": 7258, + "end_line": 7262, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*_foo_*\n", + "html": "

    foo

    \n", + "example": 460, + "start_line": 7265, + "end_line": 7269, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "__foo__\n", + "html": "

    foo

    \n", + "example": 461, + "start_line": 7272, + "end_line": 7276, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_*foo*_\n", + "html": "

    foo

    \n", + "example": 462, + "start_line": 7279, + "end_line": 7283, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "****foo****\n", + "html": "

    foo

    \n", + "example": 463, + "start_line": 7289, + "end_line": 7293, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "____foo____\n", + "html": "

    foo

    \n", + "example": 464, + "start_line": 7296, + "end_line": 7300, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "******foo******\n", + "html": "

    foo

    \n", + "example": 465, + "start_line": 7307, + "end_line": 7311, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "***foo***\n", + "html": "

    foo

    \n", + "example": 466, + "start_line": 7316, + "end_line": 7320, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "_____foo_____\n", + "html": "

    foo

    \n", + "example": 467, + "start_line": 7323, + "end_line": 7327, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo _bar* baz_\n", + "html": "

    foo _bar baz_

    \n", + "example": 468, + "start_line": 7332, + "end_line": 7336, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*foo __bar *baz bim__ bam*\n", + "html": "

    foo bar *baz bim bam

    \n", + "example": 469, + "start_line": 7339, + "end_line": 7343, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**foo **bar baz**\n", + "html": "

    **foo bar baz

    \n", + "example": 470, + "start_line": 7348, + "end_line": 7352, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*foo *bar baz*\n", + "html": "

    *foo bar baz

    \n", + "example": 471, + "start_line": 7355, + "end_line": 7359, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*[bar*](/url)\n", + "html": "

    *bar*

    \n", + "example": 472, + "start_line": 7364, + "end_line": 7368, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "_foo [bar_](/url)\n", + "html": "

    _foo bar_

    \n", + "example": 473, + "start_line": 7371, + "end_line": 7375, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "*\n", + "html": "

    *

    \n", + "example": 474, + "start_line": 7378, + "end_line": 7382, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**\n", + "html": "

    **

    \n", + "example": 475, + "start_line": 7385, + "end_line": 7389, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__\n", + "html": "

    __

    \n", + "example": 476, + "start_line": 7392, + "end_line": 7396, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "*a `*`*\n", + "html": "

    a *

    \n", + "example": 477, + "start_line": 7399, + "end_line": 7403, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "_a `_`_\n", + "html": "

    a _

    \n", + "example": 478, + "start_line": 7406, + "end_line": 7410, + "section": "Emphasis and strong emphasis" + }, + { + "markdown": "**a\n", + "html": "

    **ahttp://foo.bar/?q=**

    \n", + "example": 479, + "start_line": 7413, + "end_line": 7417, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "__a\n", + "html": "

    __ahttp://foo.bar/?q=__

    \n", + "example": 480, + "start_line": 7420, + "end_line": 7424, + "section": "Emphasis and strong emphasis", + "shouldFail": true + }, + { + "markdown": "[link](/uri \"title\")\n", + "html": "

    link

    \n", + "example": 481, + "start_line": 7503, + "end_line": 7507, + "section": "Links" + }, + { + "markdown": "[link](/uri)\n", + "html": "

    link

    \n", + "example": 482, + "start_line": 7512, + "end_line": 7516, + "section": "Links" + }, + { + "markdown": "[link]()\n", + "html": "

    link

    \n", + "example": 483, + "start_line": 7521, + "end_line": 7525, + "section": "Links" + }, + { + "markdown": "[link](<>)\n", + "html": "

    link

    \n", + "example": 484, + "start_line": 7528, + "end_line": 7532, + "section": "Links" + }, + { + "markdown": "[link](/my uri)\n", + "html": "

    [link](/my uri)

    \n", + "example": 485, + "start_line": 7537, + "end_line": 7541, + "section": "Links" + }, + { + "markdown": "[link](
    )\n", + "html": "

    link

    \n", + "example": 486, + "start_line": 7543, + "end_line": 7547, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[link](foo\nbar)\n", + "html": "

    [link](foo\nbar)

    \n", + "example": 487, + "start_line": 7552, + "end_line": 7558, + "section": "Links" + }, + { + "markdown": "[link]()\n", + "html": "

    [link]()

    \n", + "example": 488, + "start_line": 7560, + "end_line": 7566, + "section": "Links" + }, + { + "markdown": "[a]()\n", + "html": "

    a

    \n", + "example": 489, + "start_line": 7571, + "end_line": 7575, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[link]()\n", + "html": "

    [link](<foo>)

    \n", + "example": 490, + "start_line": 7579, + "end_line": 7583, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[a](\n[a](c)\n", + "html": "

    [a](<b)c\n[a](<b)c>\n[a](c)

    \n", + "example": 491, + "start_line": 7588, + "end_line": 7596, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[link](\\(foo\\))\n", + "html": "

    link

    \n", + "example": 492, + "start_line": 7600, + "end_line": 7604, + "section": "Links" + }, + { + "markdown": "[link](foo(and(bar)))\n", + "html": "

    link

    \n", + "example": 493, + "start_line": 7609, + "end_line": 7613, + "section": "Links" + }, + { + "markdown": "[link](foo\\(and\\(bar\\))\n", + "html": "

    link

    \n", + "example": 494, + "start_line": 7618, + "end_line": 7622, + "section": "Links" + }, + { + "markdown": "[link]()\n", + "html": "

    link

    \n", + "example": 495, + "start_line": 7625, + "end_line": 7629, + "section": "Links" + }, + { + "markdown": "[link](foo\\)\\:)\n", + "html": "

    link

    \n", + "example": 496, + "start_line": 7635, + "end_line": 7639, + "section": "Links" + }, + { + "markdown": "[link](#fragment)\n\n[link](http://example.com#fragment)\n\n[link](http://example.com?foo=3#frag)\n", + "html": "

    link

    \n

    link

    \n

    link

    \n", + "example": 497, + "start_line": 7644, + "end_line": 7654, + "section": "Links" + }, + { + "markdown": "[link](foo\\bar)\n", + "html": "

    link

    \n", + "example": 498, + "start_line": 7660, + "end_line": 7664, + "section": "Links" + }, + { + "markdown": "[link](foo%20bä)\n", + "html": "

    link

    \n", + "example": 499, + "start_line": 7676, + "end_line": 7680, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[link](\"title\")\n", + "html": "

    link

    \n", + "example": 500, + "start_line": 7687, + "end_line": 7691, + "section": "Links" + }, + { + "markdown": "[link](/url \"title\")\n[link](/url 'title')\n[link](/url (title))\n", + "html": "

    link\nlink\nlink

    \n", + "example": 501, + "start_line": 7696, + "end_line": 7704, + "section": "Links" + }, + { + "markdown": "[link](/url \"title \\\""\")\n", + "html": "

    link

    \n", + "example": 502, + "start_line": 7710, + "end_line": 7714, + "section": "Links" + }, + { + "markdown": "[link](/url \"title\")\n", + "html": "

    link

    \n", + "example": 503, + "start_line": 7720, + "end_line": 7724, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[link](/url \"title \"and\" title\")\n", + "html": "

    [link](/url "title "and" title")

    \n", + "example": 504, + "start_line": 7729, + "end_line": 7733, + "section": "Links" + }, + { + "markdown": "[link](/url 'title \"and\" title')\n", + "html": "

    link

    \n", + "example": 505, + "start_line": 7738, + "end_line": 7742, + "section": "Links" + }, + { + "markdown": "[link]( /uri\n \"title\" )\n", + "html": "

    link

    \n", + "example": 506, + "start_line": 7762, + "end_line": 7767, + "section": "Links" + }, + { + "markdown": "[link] (/uri)\n", + "html": "

    [link] (/uri)

    \n", + "example": 507, + "start_line": 7773, + "end_line": 7777, + "section": "Links" + }, + { + "markdown": "[link [foo [bar]]](/uri)\n", + "html": "

    link [foo [bar]]

    \n", + "example": 508, + "start_line": 7783, + "end_line": 7787, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[link] bar](/uri)\n", + "html": "

    [link] bar](/uri)

    \n", + "example": 509, + "start_line": 7790, + "end_line": 7794, + "section": "Links" + }, + { + "markdown": "[link [bar](/uri)\n", + "html": "

    [link bar

    \n", + "example": 510, + "start_line": 7797, + "end_line": 7801, + "section": "Links" + }, + { + "markdown": "[link \\[bar](/uri)\n", + "html": "

    link [bar

    \n", + "example": 511, + "start_line": 7804, + "end_line": 7808, + "section": "Links" + }, + { + "markdown": "[link *foo **bar** `#`*](/uri)\n", + "html": "

    link foo bar #

    \n", + "example": 512, + "start_line": 7813, + "end_line": 7817, + "section": "Links" + }, + { + "markdown": "[![moon](moon.jpg)](/uri)\n", + "html": "

    \"moon\"

    \n", + "example": 513, + "start_line": 7820, + "end_line": 7824, + "section": "Links" + }, + { + "markdown": "[foo [bar](/uri)](/uri)\n", + "html": "

    [foo bar](/uri)

    \n", + "example": 514, + "start_line": 7829, + "end_line": 7833, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo *[bar [baz](/uri)](/uri)*](/uri)\n", + "html": "

    [foo [bar baz](/uri)](/uri)

    \n", + "example": 515, + "start_line": 7836, + "end_line": 7840, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "![[[foo](uri1)](uri2)](uri3)\n", + "html": "

    \"[foo](uri2)\"

    \n", + "example": 516, + "start_line": 7843, + "end_line": 7847, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "*[foo*](/uri)\n", + "html": "

    *foo*

    \n", + "example": 517, + "start_line": 7853, + "end_line": 7857, + "section": "Links" + }, + { + "markdown": "[foo *bar](baz*)\n", + "html": "

    foo *bar

    \n", + "example": 518, + "start_line": 7860, + "end_line": 7864, + "section": "Links" + }, + { + "markdown": "*foo [bar* baz]\n", + "html": "

    foo [bar baz]

    \n", + "example": 519, + "start_line": 7870, + "end_line": 7874, + "section": "Links" + }, + { + "markdown": "[foo \n", + "html": "

    [foo

    \n", + "example": 520, + "start_line": 7880, + "end_line": 7884, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo`](/uri)`\n", + "html": "

    [foo](/uri)

    \n", + "example": 521, + "start_line": 7887, + "end_line": 7891, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo\n", + "html": "

    [foohttp://example.com/?search=](uri)

    \n", + "example": 522, + "start_line": 7894, + "end_line": 7898, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo][bar]\n\n[bar]: /url \"title\"\n", + "html": "

    foo

    \n", + "example": 523, + "start_line": 7932, + "end_line": 7938, + "section": "Links" + }, + { + "markdown": "[link [foo [bar]]][ref]\n\n[ref]: /uri\n", + "html": "

    link [foo [bar]]

    \n", + "example": 524, + "start_line": 7947, + "end_line": 7953, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[link \\[bar][ref]\n\n[ref]: /uri\n", + "html": "

    link [bar

    \n", + "example": 525, + "start_line": 7956, + "end_line": 7962, + "section": "Links" + }, + { + "markdown": "[link *foo **bar** `#`*][ref]\n\n[ref]: /uri\n", + "html": "

    link foo bar #

    \n", + "example": 526, + "start_line": 7967, + "end_line": 7973, + "section": "Links" + }, + { + "markdown": "[![moon](moon.jpg)][ref]\n\n[ref]: /uri\n", + "html": "

    \"moon\"

    \n", + "example": 527, + "start_line": 7976, + "end_line": 7982, + "section": "Links" + }, + { + "markdown": "[foo [bar](/uri)][ref]\n\n[ref]: /uri\n", + "html": "

    [foo bar]ref

    \n", + "example": 528, + "start_line": 7987, + "end_line": 7993, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo *bar [baz][ref]*][ref]\n\n[ref]: /uri\n", + "html": "

    [foo bar baz]ref

    \n", + "example": 529, + "start_line": 7996, + "end_line": 8002, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "*[foo*][ref]\n\n[ref]: /uri\n", + "html": "

    *foo*

    \n", + "example": 530, + "start_line": 8011, + "end_line": 8017, + "section": "Links" + }, + { + "markdown": "[foo *bar][ref]\n\n[ref]: /uri\n", + "html": "

    foo *bar

    \n", + "example": 531, + "start_line": 8020, + "end_line": 8026, + "section": "Links" + }, + { + "markdown": "[foo \n\n[ref]: /uri\n", + "html": "

    [foo

    \n", + "example": 532, + "start_line": 8032, + "end_line": 8038, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo`][ref]`\n\n[ref]: /uri\n", + "html": "

    [foo][ref]

    \n", + "example": 533, + "start_line": 8041, + "end_line": 8047, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo\n\n[ref]: /uri\n", + "html": "

    [foohttp://example.com/?search=][ref]

    \n", + "example": 534, + "start_line": 8050, + "end_line": 8056, + "section": "Links", + "shouldFail": true + }, + { + "markdown": "[foo][BaR]\n\n[bar]: /url \"title\"\n", + "html": "

    foo

    \n", + "example": 535, + "start_line": 8061, + "end_line": 8067, + "section": "Links" + }, + { + "markdown": "[Толпой][Толпой] is a Russian word.\n\n[ТОЛПОЙ]: /url\n", + "html": "

    Толпой is a Russian word.

    \n", + "example": 536, + "start_line": 8072, + "end_line": 8078, + "section": "Links" + }, + { + "markdown": "[Foo\n bar]: /url\n\n[Baz][Foo bar]\n", + "html": "

    Baz

    \n", + "example": 537, + "start_line": 8084, + "end_line": 8091, + "section": "Links" + }, + { + "markdown": "[foo] [bar]\n\n[bar]: /url \"title\"\n", + "html": "

    [foo] bar

    \n", + "example": 538, + "start_line": 8097, + "end_line": 8103, + "section": "Links" + }, + { + "markdown": "[foo]\n[bar]\n\n[bar]: /url \"title\"\n", + "html": "

    [foo]\nbar

    \n", + "example": 539, + "start_line": 8106, + "end_line": 8114, + "section": "Links" + }, + { + "markdown": "[foo]: /url1\n\n[foo]: /url2\n\n[bar][foo]\n", + "html": "

    bar

    \n", + "example": 540, + "start_line": 8147, + "end_line": 8155, + "section": "Links" + }, + { + "markdown": "[bar][foo\\!]\n\n[foo!]: /url\n", + "html": "

    [bar][foo!]

    \n", + "example": 541, + "start_line": 8162, + "end_line": 8168, + "section": "Links" + }, + { + "markdown": "[foo][ref[]\n\n[ref[]: /uri\n", + "html": "

    [foo][ref[]

    \n

    [ref[]: /uri

    \n", + "example": 542, + "start_line": 8174, + "end_line": 8181, + "section": "Links" + }, + { + "markdown": "[foo][ref[bar]]\n\n[ref[bar]]: /uri\n", + "html": "

    [foo][ref[bar]]

    \n

    [ref[bar]]: /uri

    \n", + "example": 543, + "start_line": 8184, + "end_line": 8191, + "section": "Links" + }, + { + "markdown": "[[[foo]]]\n\n[[[foo]]]: /url\n", + "html": "

    [[[foo]]]

    \n

    [[[foo]]]: /url

    \n", + "example": 544, + "start_line": 8194, + "end_line": 8201, + "section": "Links" + }, + { + "markdown": "[foo][ref\\[]\n\n[ref\\[]: /uri\n", + "html": "

    foo

    \n", + "example": 545, + "start_line": 8204, + "end_line": 8210, + "section": "Links" + }, + { + "markdown": "[bar\\\\]: /uri\n\n[bar\\\\]\n", + "html": "

    bar\\

    \n", + "example": 546, + "start_line": 8215, + "end_line": 8221, + "section": "Links" + }, + { + "markdown": "[]\n\n[]: /uri\n", + "html": "

    []

    \n

    []: /uri

    \n", + "example": 547, + "start_line": 8226, + "end_line": 8233, + "section": "Links" + }, + { + "markdown": "[\n ]\n\n[\n ]: /uri\n", + "html": "

    [\n]

    \n

    [\n]: /uri

    \n", + "example": 548, + "start_line": 8236, + "end_line": 8247, + "section": "Links" + }, + { + "markdown": "[foo][]\n\n[foo]: /url \"title\"\n", + "html": "

    foo

    \n", + "example": 549, + "start_line": 8259, + "end_line": 8265, + "section": "Links" + }, + { + "markdown": "[*foo* bar][]\n\n[*foo* bar]: /url \"title\"\n", + "html": "

    foo bar

    \n", + "example": 550, + "start_line": 8268, + "end_line": 8274, + "section": "Links" + }, + { + "markdown": "[Foo][]\n\n[foo]: /url \"title\"\n", + "html": "

    Foo

    \n", + "example": 551, + "start_line": 8279, + "end_line": 8285, + "section": "Links" + }, + { + "markdown": "[foo] \n[]\n\n[foo]: /url \"title\"\n", + "html": "

    foo\n[]

    \n", + "example": 552, + "start_line": 8292, + "end_line": 8300, + "section": "Links" + }, + { + "markdown": "[foo]\n\n[foo]: /url \"title\"\n", + "html": "

    foo

    \n", + "example": 553, + "start_line": 8312, + "end_line": 8318, + "section": "Links" + }, + { + "markdown": "[*foo* bar]\n\n[*foo* bar]: /url \"title\"\n", + "html": "

    foo bar

    \n", + "example": 554, + "start_line": 8321, + "end_line": 8327, + "section": "Links" + }, + { + "markdown": "[[*foo* bar]]\n\n[*foo* bar]: /url \"title\"\n", + "html": "

    [foo bar]

    \n", + "example": 555, + "start_line": 8330, + "end_line": 8336, + "section": "Links" + }, + { + "markdown": "[[bar [foo]\n\n[foo]: /url\n", + "html": "

    [[bar foo

    \n", + "example": 556, + "start_line": 8339, + "end_line": 8345, + "section": "Links" + }, + { + "markdown": "[Foo]\n\n[foo]: /url \"title\"\n", + "html": "

    Foo

    \n", + "example": 557, + "start_line": 8350, + "end_line": 8356, + "section": "Links" + }, + { + "markdown": "[foo] bar\n\n[foo]: /url\n", + "html": "

    foo bar

    \n", + "example": 558, + "start_line": 8361, + "end_line": 8367, + "section": "Links" + }, + { + "markdown": "\\[foo]\n\n[foo]: /url \"title\"\n", + "html": "

    [foo]

    \n", + "example": 559, + "start_line": 8373, + "end_line": 8379, + "section": "Links" + }, + { + "markdown": "[foo*]: /url\n\n*[foo*]\n", + "html": "

    *foo*

    \n", + "example": 560, + "start_line": 8385, + "end_line": 8391, + "section": "Links" + }, + { + "markdown": "[foo][bar]\n\n[foo]: /url1\n[bar]: /url2\n", + "html": "

    foo

    \n", + "example": 561, + "start_line": 8397, + "end_line": 8404, + "section": "Links" + }, + { + "markdown": "[foo][]\n\n[foo]: /url1\n", + "html": "

    foo

    \n", + "example": 562, + "start_line": 8406, + "end_line": 8412, + "section": "Links" + }, + { + "markdown": "[foo]()\n\n[foo]: /url1\n", + "html": "

    foo

    \n", + "example": 563, + "start_line": 8416, + "end_line": 8422, + "section": "Links" + }, + { + "markdown": "[foo](not a link)\n\n[foo]: /url1\n", + "html": "

    foo(not a link)

    \n", + "example": 564, + "start_line": 8424, + "end_line": 8430, + "section": "Links" + }, + { + "markdown": "[foo][bar][baz]\n\n[baz]: /url\n", + "html": "

    [foo]bar

    \n", + "example": 565, + "start_line": 8435, + "end_line": 8441, + "section": "Links" + }, + { + "markdown": "[foo][bar][baz]\n\n[baz]: /url1\n[bar]: /url2\n", + "html": "

    foobaz

    \n", + "example": 566, + "start_line": 8447, + "end_line": 8454, + "section": "Links" + }, + { + "markdown": "[foo][bar][baz]\n\n[baz]: /url1\n[foo]: /url2\n", + "html": "

    [foo]bar

    \n", + "example": 567, + "start_line": 8460, + "end_line": 8467, + "section": "Links" + }, + { + "markdown": "![foo](/url \"title\")\n", + "html": "

    \"foo\"

    \n", + "example": 568, + "start_line": 8483, + "end_line": 8487, + "section": "Images" + }, + { + "markdown": "![foo *bar*]\n\n[foo *bar*]: train.jpg \"train & tracks\"\n", + "html": "

    \"foo

    \n", + "example": 569, + "start_line": 8490, + "end_line": 8496, + "section": "Images", + "shouldFail": true + }, + { + "markdown": "![foo ![bar](/url)](/url2)\n", + "html": "

    \"foo

    \n", + "example": 570, + "start_line": 8499, + "end_line": 8503, + "section": "Images", + "shouldFail": true + }, + { + "markdown": "![foo [bar](/url)](/url2)\n", + "html": "

    \"foo

    \n", + "example": 571, + "start_line": 8506, + "end_line": 8510, + "section": "Images", + "shouldFail": true + }, + { + "markdown": "![foo *bar*][]\n\n[foo *bar*]: train.jpg \"train & tracks\"\n", + "html": "

    \"foo

    \n", + "example": 572, + "start_line": 8520, + "end_line": 8526, + "section": "Images", + "shouldFail": true + }, + { + "markdown": "![foo *bar*][foobar]\n\n[FOOBAR]: train.jpg \"train & tracks\"\n", + "html": "

    \"foo

    \n", + "example": 573, + "start_line": 8529, + "end_line": 8535, + "section": "Images", + "shouldFail": true + }, + { + "markdown": "![foo](train.jpg)\n", + "html": "

    \"foo\"

    \n", + "example": 574, + "start_line": 8538, + "end_line": 8542, + "section": "Images" + }, + { + "markdown": "My ![foo bar](/path/to/train.jpg \"title\" )\n", + "html": "

    My \"foo

    \n", + "example": 575, + "start_line": 8545, + "end_line": 8549, + "section": "Images" + }, + { + "markdown": "![foo]()\n", + "html": "

    \"foo\"

    \n", + "example": 576, + "start_line": 8552, + "end_line": 8556, + "section": "Images" + }, + { + "markdown": "![](/url)\n", + "html": "

    \"\"

    \n", + "example": 577, + "start_line": 8559, + "end_line": 8563, + "section": "Images" + }, + { + "markdown": "![foo][bar]\n\n[bar]: /url\n", + "html": "

    \"foo\"

    \n", + "example": 578, + "start_line": 8568, + "end_line": 8574, + "section": "Images" + }, + { + "markdown": "![foo][bar]\n\n[BAR]: /url\n", + "html": "

    \"foo\"

    \n", + "example": 579, + "start_line": 8577, + "end_line": 8583, + "section": "Images" + }, + { + "markdown": "![foo][]\n\n[foo]: /url \"title\"\n", + "html": "

    \"foo\"

    \n", + "example": 580, + "start_line": 8588, + "end_line": 8594, + "section": "Images" + }, + { + "markdown": "![*foo* bar][]\n\n[*foo* bar]: /url \"title\"\n", + "html": "

    \"foo

    \n", + "example": 581, + "start_line": 8597, + "end_line": 8603, + "section": "Images", + "shouldFail": true + }, + { + "markdown": "![Foo][]\n\n[foo]: /url \"title\"\n", + "html": "

    \"Foo\"

    \n", + "example": 582, + "start_line": 8608, + "end_line": 8614, + "section": "Images" + }, + { + "markdown": "![foo] \n[]\n\n[foo]: /url \"title\"\n", + "html": "

    \"foo\"\n[]

    \n", + "example": 583, + "start_line": 8620, + "end_line": 8628, + "section": "Images" + }, + { + "markdown": "![foo]\n\n[foo]: /url \"title\"\n", + "html": "

    \"foo\"

    \n", + "example": 584, + "start_line": 8633, + "end_line": 8639, + "section": "Images" + }, + { + "markdown": "![*foo* bar]\n\n[*foo* bar]: /url \"title\"\n", + "html": "

    \"foo

    \n", + "example": 585, + "start_line": 8642, + "end_line": 8648, + "section": "Images", + "shouldFail": true + }, + { + "markdown": "![[foo]]\n\n[[foo]]: /url \"title\"\n", + "html": "

    ![[foo]]

    \n

    [[foo]]: /url "title"

    \n", + "example": 586, + "start_line": 8653, + "end_line": 8660, + "section": "Images" + }, + { + "markdown": "![Foo]\n\n[foo]: /url \"title\"\n", + "html": "

    \"Foo\"

    \n", + "example": 587, + "start_line": 8665, + "end_line": 8671, + "section": "Images" + }, + { + "markdown": "!\\[foo]\n\n[foo]: /url \"title\"\n", + "html": "

    ![foo]

    \n", + "example": 588, + "start_line": 8677, + "end_line": 8683, + "section": "Images" + }, + { + "markdown": "\\![foo]\n\n[foo]: /url \"title\"\n", + "html": "

    !foo

    \n", + "example": 589, + "start_line": 8689, + "end_line": 8695, + "section": "Images" + }, + { + "markdown": "\n", + "html": "

    http://foo.bar.baz

    \n", + "example": 590, + "start_line": 8722, + "end_line": 8726, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    http://foo.bar.baz/test?q=hello&id=22&boolean

    \n", + "example": 591, + "start_line": 8729, + "end_line": 8733, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    irc://foo.bar:2233/baz

    \n", + "example": 592, + "start_line": 8736, + "end_line": 8740, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    MAILTO:FOO@BAR.BAZ

    \n", + "example": 593, + "start_line": 8745, + "end_line": 8749, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    a+b+c:d

    \n", + "example": 594, + "start_line": 8757, + "end_line": 8761, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    made-up-scheme://foo,bar

    \n", + "example": 595, + "start_line": 8764, + "end_line": 8768, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    http://../

    \n", + "example": 596, + "start_line": 8771, + "end_line": 8775, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    localhost:5001/foo

    \n", + "example": 597, + "start_line": 8778, + "end_line": 8782, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    <http://foo.bar/baz bim>

    \n", + "example": 598, + "start_line": 8787, + "end_line": 8791, + "section": "Autolinks", + "shouldFail": true + }, + { + "markdown": "\n", + "html": "

    http://example.com/\\[\\

    \n", + "example": 599, + "start_line": 8796, + "end_line": 8800, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    foo@bar.example.com

    \n", + "example": 600, + "start_line": 8818, + "end_line": 8822, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    foo+special@Bar.baz-bar0.com

    \n", + "example": 601, + "start_line": 8825, + "end_line": 8829, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    <foo+@bar.example.com>

    \n", + "example": 602, + "start_line": 8834, + "end_line": 8838, + "section": "Autolinks" + }, + { + "markdown": "<>\n", + "html": "

    <>

    \n", + "example": 603, + "start_line": 8843, + "end_line": 8847, + "section": "Autolinks" + }, + { + "markdown": "< http://foo.bar >\n", + "html": "

    < http://foo.bar >

    \n", + "example": 604, + "start_line": 8850, + "end_line": 8854, + "section": "Autolinks", + "shouldFail": true + }, + { + "markdown": "\n", + "html": "

    <m:abc>

    \n", + "example": 605, + "start_line": 8857, + "end_line": 8861, + "section": "Autolinks" + }, + { + "markdown": "\n", + "html": "

    <foo.bar.baz>

    \n", + "example": 606, + "start_line": 8864, + "end_line": 8868, + "section": "Autolinks" + }, + { + "markdown": "http://example.com\n", + "html": "

    http://example.com

    \n", + "example": 607, + "start_line": 8871, + "end_line": 8875, + "section": "Autolinks", + "shouldFail": true + }, + { + "markdown": "foo@bar.example.com\n", + "html": "

    foo@bar.example.com

    \n", + "example": 608, + "start_line": 8878, + "end_line": 8882, + "section": "Autolinks", + "shouldFail": true + }, + { + "markdown": "\n", + "html": "

    \n", + "example": 609, + "start_line": 8960, + "end_line": 8964, + "section": "Raw HTML" + }, + { + "markdown": "\n", + "html": "

    \n", + "example": 610, + "start_line": 8969, + "end_line": 8973, + "section": "Raw HTML" + }, + { + "markdown": "\n", + "html": "

    \n", + "example": 611, + "start_line": 8978, + "end_line": 8984, + "section": "Raw HTML" + }, + { + "markdown": "\n", + "html": "

    \n", + "example": 612, + "start_line": 8989, + "end_line": 8995, + "section": "Raw HTML" + }, + { + "markdown": "Foo \n", + "html": "

    Foo

    \n", + "example": 613, + "start_line": 9000, + "end_line": 9004, + "section": "Raw HTML" + }, + { + "markdown": "<33> <__>\n", + "html": "

    <33> <__>

    \n", + "example": 614, + "start_line": 9009, + "end_line": 9013, + "section": "Raw HTML" + }, + { + "markdown": "
    \n", + "html": "

    <a h*#ref="hi">

    \n", + "example": 615, + "start_line": 9018, + "end_line": 9022, + "section": "Raw HTML" + }, + { + "markdown": "
    \n", + "html": "

    <a href="hi'> <a href=hi'>

    \n", + "example": 616, + "start_line": 9027, + "end_line": 9031, + "section": "Raw HTML" + }, + { + "markdown": "< a><\nfoo>\n\n", + "html": "

    < a><\nfoo><bar/ >\n<foo bar=baz\nbim!bop />

    \n", + "example": 617, + "start_line": 9036, + "end_line": 9046, + "section": "Raw HTML" + }, + { + "markdown": "
    \n", + "html": "

    <a href='bar'title=title>

    \n", + "example": 618, + "start_line": 9051, + "end_line": 9055, + "section": "Raw HTML" + }, + { + "markdown": "
    \n", + "html": "

    \n", + "example": 619, + "start_line": 9060, + "end_line": 9064, + "section": "Raw HTML" + }, + { + "markdown": "\n", + "html": "

    </a href="foo">

    \n", + "example": 620, + "start_line": 9069, + "end_line": 9073, + "section": "Raw HTML" + }, + { + "markdown": "foo \n", + "html": "

    foo

    \n", + "example": 621, + "start_line": 9078, + "end_line": 9084, + "section": "Raw HTML" + }, + { + "markdown": "foo \n", + "html": "

    foo <!-- not a comment -- two hyphens -->

    \n", + "example": 622, + "start_line": 9087, + "end_line": 9091, + "section": "Raw HTML", + "shouldFail": true + }, + { + "markdown": "foo foo -->\n\nfoo \n", + "html": "

    foo <!--> foo -->

    \n

    foo <!-- foo--->

    \n", + "example": 623, + "start_line": 9096, + "end_line": 9103, + "section": "Raw HTML", + "shouldFail": true + }, + { + "markdown": "foo \n", + "html": "

    foo

    \n", + "example": 624, + "start_line": 9108, + "end_line": 9112, + "section": "Raw HTML" + }, + { + "markdown": "foo \n", + "html": "

    foo

    \n", + "example": 625, + "start_line": 9117, + "end_line": 9121, + "section": "Raw HTML" + }, + { + "markdown": "foo &<]]>\n", + "html": "

    foo &<]]>

    \n", + "example": 626, + "start_line": 9126, + "end_line": 9130, + "section": "Raw HTML" + }, + { + "markdown": "foo \n", + "html": "

    foo

    \n", + "example": 627, + "start_line": 9136, + "end_line": 9140, + "section": "Raw HTML" + }, + { + "markdown": "foo \n", + "html": "

    foo

    \n", + "example": 628, + "start_line": 9145, + "end_line": 9149, + "section": "Raw HTML" + }, + { + "markdown": "\n", + "html": "

    <a href=""">

    \n", + "example": 629, + "start_line": 9152, + "end_line": 9156, + "section": "Raw HTML" + }, + { + "markdown": "foo \nbaz\n", + "html": "

    foo
    \nbaz

    \n", + "example": 630, + "start_line": 9166, + "end_line": 9172, + "section": "Hard line breaks" + }, + { + "markdown": "foo\\\nbaz\n", + "html": "

    foo
    \nbaz

    \n", + "example": 631, + "start_line": 9178, + "end_line": 9184, + "section": "Hard line breaks" + }, + { + "markdown": "foo \nbaz\n", + "html": "

    foo
    \nbaz

    \n", + "example": 632, + "start_line": 9189, + "end_line": 9195, + "section": "Hard line breaks" + }, + { + "markdown": "foo \n bar\n", + "html": "

    foo
    \nbar

    \n", + "example": 633, + "start_line": 9200, + "end_line": 9206, + "section": "Hard line breaks" + }, + { + "markdown": "foo\\\n bar\n", + "html": "

    foo
    \nbar

    \n", + "example": 634, + "start_line": 9209, + "end_line": 9215, + "section": "Hard line breaks" + }, + { + "markdown": "*foo \nbar*\n", + "html": "

    foo
    \nbar

    \n", + "example": 635, + "start_line": 9221, + "end_line": 9227, + "section": "Hard line breaks" + }, + { + "markdown": "*foo\\\nbar*\n", + "html": "

    foo
    \nbar

    \n", + "example": 636, + "start_line": 9230, + "end_line": 9236, + "section": "Hard line breaks" + }, + { + "markdown": "`code \nspan`\n", + "html": "

    code span

    \n", + "example": 637, + "start_line": 9241, + "end_line": 9246, + "section": "Hard line breaks" + }, + { + "markdown": "`code\\\nspan`\n", + "html": "

    code\\ span

    \n", + "example": 638, + "start_line": 9249, + "end_line": 9254, + "section": "Hard line breaks" + }, + { + "markdown": "
    \n", + "html": "

    \n", + "example": 639, + "start_line": 9259, + "end_line": 9265, + "section": "Hard line breaks" + }, + { + "markdown": "\n", + "html": "

    \n", + "example": 640, + "start_line": 9268, + "end_line": 9274, + "section": "Hard line breaks" + }, + { + "markdown": "foo\\\n", + "html": "

    foo\\

    \n", + "example": 641, + "start_line": 9281, + "end_line": 9285, + "section": "Hard line breaks" + }, + { + "markdown": "foo \n", + "html": "

    foo

    \n", + "example": 642, + "start_line": 9288, + "end_line": 9292, + "section": "Hard line breaks" + }, + { + "markdown": "### foo\\\n", + "html": "

    foo\\

    \n", + "example": 643, + "start_line": 9295, + "end_line": 9299, + "section": "Hard line breaks" + }, + { + "markdown": "### foo \n", + "html": "

    foo

    \n", + "example": 644, + "start_line": 9302, + "end_line": 9306, + "section": "Hard line breaks" + }, + { + "markdown": "foo\nbaz\n", + "html": "

    foo\nbaz

    \n", + "example": 645, + "start_line": 9317, + "end_line": 9323, + "section": "Soft line breaks" + }, + { + "markdown": "foo \n baz\n", + "html": "

    foo\nbaz

    \n", + "example": 646, + "start_line": 9329, + "end_line": 9335, + "section": "Soft line breaks" + }, + { + "markdown": "hello $.;'there\n", + "html": "

    hello $.;'there

    \n", + "example": 647, + "start_line": 9349, + "end_line": 9353, + "section": "Textual content" + }, + { + "markdown": "Foo χρῆν\n", + "html": "

    Foo χρῆν

    \n", + "example": 648, + "start_line": 9356, + "end_line": 9360, + "section": "Textual content" + }, + { + "markdown": "Multiple spaces\n", + "html": "

    Multiple spaces

    \n", + "example": 649, + "start_line": 9365, + "end_line": 9369, + "section": "Textual content" + } +] diff --git a/packages/markdown/marked/test/specs/commonmark/getSpecs.js b/packages/markdown/marked/test/specs/commonmark/getSpecs.js new file mode 100644 index 00000000..f22e00c0 --- /dev/null +++ b/packages/markdown/marked/test/specs/commonmark/getSpecs.js @@ -0,0 +1,24 @@ +const fetch = require('node-fetch'); +const marked = require('../../../'); +const htmlDiffer = require('../../helpers/html-differ.js'); +const fs = require('fs'); + +fetch('https://raw.githubusercontent.com/commonmark/commonmark.js/master/package.json') + .then(res => res.json()) + .then(pkg => pkg.version.replace(/^(\d+\.\d+).*$/, '$1')) + .then(version => + fetch(`https://spec.commonmark.org/${version}/spec.json`) + .then(res => res.json()) + .then(specs => { + specs.forEach(spec => { + const html = marked(spec.markdown, {headerIds: false}); + if (!htmlDiffer.isEqual(html, spec.html)) { + spec.shouldFail = true; + } + }); + fs.writeFileSync(`commonmark.${version}.json`, JSON.stringify(specs, null, 2) + '\n'); + }) + ) + .catch((err) => { + console.error(err); + }); diff --git a/packages/markdown/marked/test/specs/gfm/getSpecs.js b/packages/markdown/marked/test/specs/gfm/getSpecs.js new file mode 100644 index 00000000..2746bdbb --- /dev/null +++ b/packages/markdown/marked/test/specs/gfm/getSpecs.js @@ -0,0 +1,44 @@ +const fetch = require('node-fetch'); +const cheerio = require('cheerio'); +const marked = require('../../../'); +const htmlDiffer = require('../../helpers/html-differ.js'); +const fs = require('fs'); + +fetch('https://github.github.com/gfm/') + .then(res => res.text()) + .then(html => cheerio.load(html)) + .then($ => { + const version = $('.version').text().match(/\d+\.\d+/)[0]; + if (!version) { + throw new Error('No version found'); + } + const specs = []; + $('.extension').each((i, ext) => { + const section = $('.definition', ext).text().trim().replace(/^\d+\.\d+(.*?) \(extension\)[\s\S]*$/, '$1'); + $('.example', ext).each((j, exa) => { + const example = +$(exa).attr('id').replace(/\D/g, ''); + const markdown = $('.language-markdown', exa).text().trim(); + const html = $('.language-html', exa).text().trim(); + specs.push({ + section, + html, + markdown, + example + }); + }); + }); + + return [version, specs]; + }) + .then(([version, specs]) => { + specs.forEach(spec => { + const html = marked(spec.markdown, {gfm: true}); + if (!htmlDiffer.isEqual(html, spec.html)) { + spec.shouldFail = true; + } + }); + fs.writeFileSync(`gfm.${version}.json`, JSON.stringify(specs, null, 2) + '\n'); + }) + .catch((err) => { + console.error(err); + }); diff --git a/packages/markdown/marked/test/specs/gfm/gfm.0.29.json b/packages/markdown/marked/test/specs/gfm/gfm.0.29.json new file mode 100644 index 00000000..7d1d43e4 --- /dev/null +++ b/packages/markdown/marked/test/specs/gfm/gfm.0.29.json @@ -0,0 +1,147 @@ +[ + { + "section": "Tables", + "html": "\n\n\n\n\n\n\n\n\n\n\n\n\n
    foobar
    bazbim
    ", + "markdown": "| foo | bar |\n| --- | --- |\n| baz | bim |", + "example": 198 + }, + { + "section": "Tables", + "html": "\n\n\n\n\n\n\n\n\n\n\n\n\n
    abcdefghi
    barbaz
    ", + "markdown": "| abc | defghi |\n:-: | -----------:\nbar | baz", + "example": 199 + }, + { + "section": "Tables", + "html": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    f|oo
    b | az
    b | im
    ", + "markdown": "| f\\|oo |\n| ------ |\n| b `\\|` az |\n| b **\\|** im |", + "example": 200 + }, + { + "section": "Tables", + "html": "\n\n\n\n\n\n\n\n\n\n\n\n\n
    abcdef
    barbaz
    \n
    \n

    bar

    \n
    ", + "markdown": "| abc | def |\n| --- | --- |\n| bar | baz |\n> bar", + "example": 201 + }, + { + "section": "Tables", + "html": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    abcdef
    barbaz
    bar
    \n

    bar

    ", + "markdown": "| abc | def |\n| --- | --- |\n| bar | baz |\nbar\n\nbar", + "example": 202 + }, + { + "section": "Tables", + "html": "

    | abc | def |\n| --- |\n| bar |

    ", + "markdown": "| abc | def |\n| --- |\n| bar |", + "example": 203 + }, + { + "section": "Tables", + "html": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    abcdef
    bar
    barbaz
    ", + "markdown": "| abc | def |\n| --- | --- |\n| bar |\n| bar | baz | boo |", + "example": 204 + }, + { + "section": "Tables", + "html": "\n\n\n\n\n\n\n
    abcdef
    ", + "markdown": "| abc | def |\n| --- | --- |", + "example": 205 + }, + { + "section": "Task list items", + "html": "
      \n
    • foo
    • \n
    • bar
    • \n
    ", + "markdown": "- [ ] foo\n- [x] bar", + "example": 279 + }, + { + "section": "Task list items", + "html": "
      \n
    • foo\n
        \n
      • bar
      • \n
      • baz
      • \n
      \n
    • \n
    • bim
    • \n
    ", + "markdown": "- [x] foo\n - [ ] bar\n - [x] baz\n- [ ] bim", + "example": 280 + }, + { + "section": "Strikethrough", + "html": "

    Hi Hello, world!

    ", + "markdown": "~~Hi~~ Hello, world!", + "example": 491 + }, + { + "section": "Strikethrough", + "html": "

    This ~~has a

    \n

    new paragraph~~.

    ", + "markdown": "This ~~has a\n\nnew paragraph~~.", + "example": 492 + }, + { + "section": "Autolinks", + "html": "

    www.commonmark.org

    ", + "markdown": "www.commonmark.org", + "example": 621 + }, + { + "section": "Autolinks", + "html": "

    Visit www.commonmark.org/help for more information.

    ", + "markdown": "Visit www.commonmark.org/help for more information.", + "example": 622 + }, + { + "section": "Autolinks", + "html": "

    Visit www.commonmark.org.

    \n

    Visit www.commonmark.org/a.b.

    ", + "markdown": "Visit www.commonmark.org.\n\nVisit www.commonmark.org/a.b.", + "example": 623 + }, + { + "section": "Autolinks", + "html": "

    www.google.com/search?q=Markup+(business)

    \n

    (www.google.com/search?q=Markup+(business))

    ", + "markdown": "www.google.com/search?q=Markup+(business)\n\n(www.google.com/search?q=Markup+(business))", + "example": 624 + }, + { + "section": "Autolinks", + "html": "

    www.google.com/search?q=(business))+ok

    ", + "markdown": "www.google.com/search?q=(business))+ok", + "example": 625 + }, + { + "section": "Autolinks", + "html": "

    www.google.com/search?q=commonmark&hl=en

    \n

    www.google.com/search?q=commonmark&hl;

    ", + "markdown": "www.google.com/search?q=commonmark&hl=en\n\nwww.google.com/search?q=commonmark&hl;", + "example": 626 + }, + { + "section": "Autolinks", + "html": "

    www.commonmark.org/he<lp

    ", + "markdown": "www.commonmark.org/hehttp://commonmark.org

    \n

    (Visit https://encrypted.google.com/search?q=Markup+(business))

    \n

    Anonymous FTP is available at ftp://foo.bar.baz.

    ", + "markdown": "http://commonmark.org\n\n(Visit https://encrypted.google.com/search?q=Markup+(business))\n\nAnonymous FTP is available at ftp://foo.bar.baz.", + "example": 628 + }, + { + "section": "Autolinks", + "html": "

    foo@bar.baz

    ", + "markdown": "foo@bar.baz", + "example": 629 + }, + { + "section": "Autolinks", + "html": "

    hello@mail+xyz.example isn't valid, but hello+xyz@mail.example is.

    ", + "markdown": "hello@mail+xyz.example isn't valid, but hello+xyz@mail.example is.", + "example": 630 + }, + { + "section": "Autolinks", + "html": "

    a.b-c_d@a.b

    \n

    a.b-c_d@a.b.

    \n

    a.b-c_d@a.b-

    \n

    a.b-c_d@a.b_

    ", + "markdown": "a.b-c_d@a.b\n\na.b-c_d@a.b.\n\na.b-c_d@a.b-\n\na.b-c_d@a.b_", + "example": 631 + }, + { + "section": "Disallowed Raw HTML", + "html": "

    <title> <style>

    \n
    \n <xmp> is disallowed. <XMP> is also disallowed.\n
    ", + "markdown": " <style> <em>\n\n<blockquote>\n <xmp> is disallowed. <XMP> is also disallowed.\n</blockquote>", + "example": 653, + "shouldFail": true + } +] diff --git a/packages/markdown/marked/test/specs/original/specs-spec.js b/packages/markdown/marked/test/specs/original/specs-spec.js new file mode 100644 index 00000000..82d300a5 --- /dev/null +++ b/packages/markdown/marked/test/specs/original/specs-spec.js @@ -0,0 +1,12 @@ +var specTests = require('../../'); + +it('should run spec tests', () => { + // hide output + spyOn(console, 'log'); + if (!specTests(['', '', '--stop'])) { + // if tests fail rerun tests and show output + console.log.and.callThrough(); + specTests([]); + fail(); + } +}); diff --git a/packages/markdown/marked/test/specs/redos-spec.js b/packages/markdown/marked/test/specs/redos-spec.js new file mode 100644 index 00000000..1f94a42e --- /dev/null +++ b/packages/markdown/marked/test/specs/redos-spec.js @@ -0,0 +1,24 @@ +const path = require('path'); +const fs = require('fs'); + +const redosDir = path.resolve(__dirname, '../redos'); + +describe('ReDOS tests', () => { + const files = fs.readdirSync(redosDir); + files.forEach(file => { + if (!file.match(/\.js$/)) { + return; + } + + it(file, () => { + const spec = require(path.resolve(redosDir, file)); + const before = process.hrtime(); + expect(spec).toRender(spec.html); + const elapsed = process.hrtime(before); + if (elapsed[0] > 0) { + const s = (elapsed[0] + elapsed[1] * 1e-9).toFixed(3); + fail(`took too long: ${s}s`); + } + }); + }); +}); diff --git a/packages/markdown/marked/test/specs/run-spec.js b/packages/markdown/marked/test/specs/run-spec.js new file mode 100644 index 00000000..3af0aa45 --- /dev/null +++ b/packages/markdown/marked/test/specs/run-spec.js @@ -0,0 +1,52 @@ +function runSpecs(title, file, options) { + const json = require(file); + let longestName = 0; + let maxSpecs = 0; + const specs = json.reduce((obj, spec) => { + if (!obj[spec.section]) { + longestName = Math.max(spec.section.length, longestName); + obj[spec.section] = { + specs: [], + pass: 0, + total: 0 + }; + } + obj[spec.section].total++; + maxSpecs = Math.max(obj[spec.section].total, maxSpecs); + if (!spec.shouldFail) { + obj[spec.section].pass++; + } + obj[spec.section].specs.push(spec); + return obj; + }, {}); + + describe(title, () => { + const maxSpecsLen = ('' + maxSpecs).length; + const spaces = maxSpecsLen * 2 + longestName + 11; + console.log('-'.padEnd(spaces + 4, '-')); + console.log(`| ${title.padStart(Math.ceil((spaces + title.length) / 2)).padEnd(spaces)} |`); + console.log(`| ${' '.padEnd(spaces)} |`); + Object.keys(specs).forEach(section => { + console.log(`| ${section.padEnd(longestName)} ${('' + specs[section].pass).padStart(maxSpecsLen)} of ${('' + specs[section].total).padStart(maxSpecsLen)} ${(100 * specs[section].pass / specs[section].total).toFixed().padStart(4)}% |`); + describe(section, () => { + specs[section].specs.forEach((spec) => { + if (options) { + spec.options = Object.assign({}, options, (spec.options || {})); + } + (spec.only ? fit : it)('should ' + (spec.shouldFail ? 'fail' : 'pass') + ' example ' + spec.example, () => { + if (spec.shouldFail) { + expect(spec).not.toRender(spec.html); + } else { + expect(spec).toRender(spec.html); + } + }); + }); + }); + }); + console.log('-'.padEnd(spaces + 4, '-')); + console.log(); + }); +}; + +runSpecs('GFM 0.29', './gfm/gfm.0.29.json', {gfm: true}); +runSpecs('CommonMark 0.29', './commonmark/commonmark.0.29.json', {headerIds: false}); diff --git a/packages/markdown/marked/test/unit/marked-spec.js b/packages/markdown/marked/test/unit/marked-spec.js new file mode 100644 index 00000000..994c5dc8 --- /dev/null +++ b/packages/markdown/marked/test/unit/marked-spec.js @@ -0,0 +1,73 @@ +var marked = require('../../lib/marked.js'); + +describe('Test heading ID functionality', () => { + it('should add id attribute by default', () => { + var renderer = new marked.Renderer(); + var slugger = new marked.Slugger(); + var header = renderer.heading('test', 1, 'test', slugger); + expect(header).toBe('<h1 id="test">test</h1>\n'); + }); + + it('should NOT add id attribute when options set false', () => { + var renderer = new marked.Renderer({ headerIds: false }); + var header = renderer.heading('test', 1, 'test'); + expect(header).toBe('<h1>test</h1>\n'); + }); +}); + +describe('Test slugger functionality', () => { + it('should use lowercase slug', () => { + var slugger = new marked.Slugger(); + expect(slugger.slug('Test')).toBe('test'); + }); + + it('should be unique to avoid collisions 1280', () => { + var slugger = new marked.Slugger(); + expect(slugger.slug('test')).toBe('test'); + expect(slugger.slug('test')).toBe('test-1'); + expect(slugger.slug('test')).toBe('test-2'); + }); + + it('should be unique when slug ends with number', () => { + var slugger = new marked.Slugger(); + expect(slugger.slug('test 1')).toBe('test-1'); + expect(slugger.slug('test')).toBe('test'); + expect(slugger.slug('test')).toBe('test-2'); + }); + + it('should be unique when slug ends with hyphen number', () => { + var slugger = new marked.Slugger(); + expect(slugger.slug('foo')).toBe('foo'); + expect(slugger.slug('foo')).toBe('foo-1'); + expect(slugger.slug('foo 1')).toBe('foo-1-1'); + expect(slugger.slug('foo-1')).toBe('foo-1-2'); + expect(slugger.slug('foo')).toBe('foo-2'); + }); + + it('should allow non-latin chars', () => { + var slugger = new marked.Slugger(); + expect(slugger.slug('привет')).toBe('привет'); + }); + + it('should remove ampersands 857', () => { + var slugger = new marked.Slugger(); + expect(slugger.slug('This & That Section')).toBe('this--that-section'); + }); + + it('should remove periods', () => { + var slugger = new marked.Slugger(); + expect(slugger.slug('file.txt')).toBe('filetxt'); + }); +}); + +describe('Test paragraph token type', () => { + it('should use the "paragraph" type on top level', () => { + const md = 'A Paragraph.\n\n> A blockquote\n\n- list item\n'; + + const tokens = marked.lexer(md); + + expect(tokens[0].type).toBe('paragraph'); + expect(tokens[3].type).toBe('paragraph'); + expect(tokens[7].type).toBe('text'); + }); +}); diff --git a/packages/markdown/package.js b/packages/markdown/package.js new file mode 100755 index 00000000..ac725b8f --- /dev/null +++ b/packages/markdown/package.js @@ -0,0 +1,24 @@ +// Source: https://github.com/chjj/marked + +Package.describe({ + name: 'wekan-markdown', + summary: "GitHub flavored markdown parser for Meteor based on marked.js", + version: "1.0.7", + git: "https://github.com/wekan/markdown.git" +}); + +// Before Meteor 0.9? +if(!Package.onUse) Package.onUse = Package.on_use; + +Package.onUse(function (api) { + if(api.versionsFrom) api.versionsFrom('METEOR@0.9.0'); + + api.use('templating'); + + api.add_files('marked/lib/marked.js', ['server', 'client']); + api.add_files('markdown.js', ['server', 'client']); + api.export('Markdown', ['server', 'client']); + + api.use("ui", "client", {weak: true}); + api.add_files("template-integration.js", "client"); +}); diff --git a/packages/markdown/smart.json b/packages/markdown/smart.json new file mode 100755 index 00000000..dd443066 --- /dev/null +++ b/packages/markdown/smart.json @@ -0,0 +1,9 @@ +{ + "name": "markdown", + "description": "GitHub flavored markdown parser for Meteor based on marked.js", + "homepage": "https://github.com/wekan/markdown", + "author": "Petar Korponaic", + "version": "1.0.7", + "git": "https://github.com/wekan/markdown.git", + "packages": {} +} diff --git a/packages/markdown/template-integration.js b/packages/markdown/template-integration.js new file mode 100755 index 00000000..301bde31 --- /dev/null +++ b/packages/markdown/template-integration.js @@ -0,0 +1,16 @@ +if (Package.ui) { + var Template = Package.templating.Template; + var UI = Package.ui.UI; + var HTML = Package.htmljs.HTML; + var Blaze = Package.blaze.Blaze; // implied by `ui` + + UI.registerHelper('markdown', new Template('markdown', function () { + var self = this; + var text = ""; + if(self.templateContentBlock) { + text = Blaze._toText(self.templateContentBlock, HTML.TEXTMODE.STRING); + } + + return HTML.Raw(Markdown(text)); + })); +} diff --git a/packages/meteor-accounts-cas/.gitignore b/packages/meteor-accounts-cas/.gitignore new file mode 100644 index 00000000..bed7713f --- /dev/null +++ b/packages/meteor-accounts-cas/.gitignore @@ -0,0 +1,2 @@ +.build* +node_modules/ diff --git a/packages/meteor-accounts-cas/LICENSE b/packages/meteor-accounts-cas/LICENSE new file mode 100644 index 00000000..c2d69158 --- /dev/null +++ b/packages/meteor-accounts-cas/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2019 The Wekan Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/meteor-accounts-cas/README.md b/packages/meteor-accounts-cas/README.md new file mode 100644 index 00000000..3e246c4f --- /dev/null +++ b/packages/meteor-accounts-cas/README.md @@ -0,0 +1,88 @@ +This is a merged repository of useful forks of: atoy40:accounts-cas +=================== +([(https://atmospherejs.com/atoy40/accounts-cas](https://atmospherejs.com/atoy40/accounts-cas)) + +## Essential improvements by ppoulard to atoy40 and xaionaro versions + +* Added support of CAS attributes + +With this plugin, you can pick CAS attributes : https://github.com/joshchan/node-cas/wiki/CAS-Attributes + +Moved to Wekan GitHub org from from https://github.com/ppoulard/meteor-accounts-cas + +## Install + +``` +cd ~site +mkdir packages +cd packages +git clone https://github.com/wekan/meteor-accounts-cas +cd ~site +meteor add wekan:accounts-cas +``` + +## Usage + +Put CAS settings in Meteor.settings (for example using METEOR_SETTINGS env or --settings) like so: + +If casVersion is not defined, it will assume you use CAS 1.0. (note by xaionaro: option `casVersion` seems to be just ignored in the code, ATM). + +Server side settings: + +``` +Meteor.settings = { + "cas": { + "baseUrl": "https://cas.example.com/cas", + "autoClose": true, + "validateUrl":"https://cas.example.com/cas/p3/serviceValidate", + "casVersion": 3.0, + "attributes": { + "debug" : true + } + }, +} +``` + +CAS `attributes` settings : + +* `attributes`: by default `{}` : all default values below will apply +* * `debug` : by default `false` ; `true` will print to the server console the CAS attribute names to map, the CAS attributes values retrieved, if necessary the new user account created, and finally the user to use +* * `id` : by default, the CAS user is used for the user account, but you can specified another CAS attribute +* * `firstname` : by default `cas:givenName` ; but you can use your own CAS attribute +* * `lastname` : by default `cas:sn` (respectively) ; but you can use your own CAS attribute +* * `fullname` : by default unused, but if you specify your own CAS attribute, it will be used instead of the `firstname` + `lastname` +* * `mail` : by default `cas:mail` + +Client side settings: + +``` +Meteor.settings = { + "public": { + "cas": { + "loginUrl": "https://cas.example.com/login", + "serviceParam": "service", + "popupWidth": 810, + "popupHeight": 610, + "popup": true, + } + } +} +``` + +`proxyUrl` is not required. Setup [ROOT_URL](http://docs.meteor.com/api/core.html#Meteor-absoluteUrl) environment variable instead. + +Then, to start authentication, you have to call the following method from the client (for example in a click handler) : + +``` +Meteor.loginWithCas([callback]); +``` + +It must open a popup containing you CAS login form or redirect to the CAS login form (depending on "popup" setting). + +If popup is disabled (== false), then it's required to execute `Meteor.initCas([callback])` in `Meteor.startup` of the client side. ATM, `Meteor.initCas()` completes authentication. + +## Examples + +* [https://devel.mephi.ru/dyokunev/start-mephi-ru](https://devel.mephi.ru/dyokunev/start-mephi-ru) + + diff --git a/packages/meteor-accounts-cas/cas_client.js b/packages/meteor-accounts-cas/cas_client.js new file mode 100644 index 00000000..bd94be6b --- /dev/null +++ b/packages/meteor-accounts-cas/cas_client.js @@ -0,0 +1,112 @@ + +function addParameterToURL(url, param){ + var urlSplit = url.split('?'); + return url+(urlSplit.length>0 ? '?':'&') + param; +} + +Meteor.initCas = function(callback) { + const casTokenMatch = window.location.href.match(/[?&]casToken=([^&]+)/); + if (casTokenMatch == null) { + return; + } + + window.history.pushState('', document.title, window.location.href.replace(/([&?])casToken=[^&]+[&]?/, '$1').replace(/[?&]+$/g, '')); + + Accounts.callLoginMethod({ + methodArguments: [{ cas: { credentialToken: casTokenMatch[1] } }], + userCallback: function(err){ + if (err == null) { + // should we do anything on success? + } + if (callback != null) { + callback(err); + } + } + }); +} + +Meteor.loginWithCas = function(options, callback) { + + var credentialToken = Random.id(); + + if (!Meteor.settings.public && + !Meteor.settings.public.cas && + !Meteor.settings.public.cas.loginUrl) { + return; + } + + var settings = Meteor.settings.public.cas; + + var backURL = window.location.href.replace('#', ''); + if (options != null && options.redirectUrl != null) + backURL = options.redirectUrl; + + var serviceURL = addParameterToURL(backURL, 'casToken='+credentialToken); + + var loginUrl = settings.loginUrl + + "?" + (settings.serviceParam || "service") + "=" + + encodeURIComponent(serviceURL) + + if (settings.popup == false) { + window.location = loginUrl; + return; + } + + var popup = openCenteredPopup( + loginUrl, + settings.width || 800, + settings.height || 600 + ); + + var checkPopupOpen = setInterval(function() { + try { + if(popup && popup.document && popup.document.getElementById('popupCanBeClosed')) { + popup.close(); + } + // Fix for #328 - added a second test criteria (popup.closed === undefined) + // to humour this Android quirk: + // http://code.google.com/p/android/issues/detail?id=21061 + var popupClosed = popup.closed || popup.closed === undefined; + } catch (e) { + // For some unknown reason, IE9 (and others?) sometimes (when + // the popup closes too quickly?) throws "SCRIPT16386: No such + // interface supported" when trying to read 'popup.closed'. Try + // again in 100ms. + return; + } + + if (popupClosed) { + clearInterval(checkPopupOpen); + + // check auth on server. + Accounts.callLoginMethod({ + methodArguments: [{ cas: { credentialToken: credentialToken } }], + userCallback: callback + }); + } + }, 100); +}; + +var openCenteredPopup = function(url, width, height) { + var screenX = typeof window.screenX !== 'undefined' + ? window.screenX : window.screenLeft; + var screenY = typeof window.screenY !== 'undefined' + ? window.screenY : window.screenTop; + var outerWidth = typeof window.outerWidth !== 'undefined' + ? window.outerWidth : document.body.clientWidth; + var outerHeight = typeof window.outerHeight !== 'undefined' + ? window.outerHeight : (document.body.clientHeight - 22); + // XXX what is the 22? + + // Use `outerWidth - width` and `outerHeight - height` for help in + // positioning the popup centered relative to the current window + var left = screenX + (outerWidth - width) / 2; + var top = screenY + (outerHeight - height) / 2; + var features = ('width=' + width + ',height=' + height + + ',left=' + left + ',top=' + top + ',scrollbars=yes'); + + var newwindow = window.open(url, '_blank', features); + if (newwindow.focus) + newwindow.focus(); + return newwindow; +}; diff --git a/packages/meteor-accounts-cas/cas_client_cordova.js b/packages/meteor-accounts-cas/cas_client_cordova.js new file mode 100644 index 00000000..c7f95b50 --- /dev/null +++ b/packages/meteor-accounts-cas/cas_client_cordova.js @@ -0,0 +1,71 @@ + +Meteor.loginWithCas = function(callback) { + + var credentialToken = Random.id(); + + if (!Meteor.settings.public && + !Meteor.settings.public.cas && + !Meteor.settings.public.cas.loginUrl) { + return; + } + + var settings = Meteor.settings.public.cas; + + var loginUrl = settings.loginUrl + + "?" + (settings.service || "service") + "=" + + Meteor.absoluteUrl('_cas/') + + credentialToken; + + + var fail = function (err) { + Meteor._debug("Error from OAuth popup: " + JSON.stringify(err)); + }; + + // When running on an android device, we sometimes see the + // `pageLoaded` callback fire twice for the final page in the OAuth + // popup, even though the page only loads once. This is maybe an + // Android bug or maybe something intentional about how onPageFinished + // works that we don't understand and isn't well-documented. + var oauthFinished = false; + + var pageLoaded = function (event) { + if (oauthFinished) { + return; + } + + if (event.url.indexOf(Meteor.absoluteUrl('_cas')) === 0) { + + oauthFinished = true; + + // On iOS, this seems to prevent "Warning: Attempt to dismiss from + // view controller <MainViewController: ...> while a presentation + // or dismiss is in progress". My guess is that the last + // navigation of the OAuth popup is still in progress while we try + // to close the popup. See + // https://issues.apache.org/jira/browse/CB-2285. + // + // XXX Can we make this timeout smaller? + setTimeout(function () { + popup.close(); + // check auth on server. + Accounts.callLoginMethod({ + methodArguments: [{ cas: { credentialToken: credentialToken } }], + userCallback: callback + }); + }, 100); + } + }; + + var onExit = function () { + popup.removeEventListener('loadstop', pageLoaded); + popup.removeEventListener('loaderror', fail); + popup.removeEventListener('exit', onExit); + }; + + var popup = window.open(loginUrl, '_blank', 'location=no,hidden=no'); + popup.addEventListener('loadstop', pageLoaded); + popup.addEventListener('loaderror', fail); + popup.addEventListener('exit', onExit); + popup.show(); + +}; \ No newline at end of file diff --git a/packages/meteor-accounts-cas/cas_server.js b/packages/meteor-accounts-cas/cas_server.js new file mode 100644 index 00000000..15c1b174 --- /dev/null +++ b/packages/meteor-accounts-cas/cas_server.js @@ -0,0 +1,281 @@ +"use strict"; + +const Fiber = Npm.require('fibers'); +const https = Npm.require('https'); +const url = Npm.require('url'); +const xmlParser = Npm.require('xml2js'); + +// Library +class CAS { + constructor(options) { + options = options || {}; + + if (!options.validate_url) { + throw new Error('Required CAS option `validateUrl` missing.'); + } + + if (!options.service) { + throw new Error('Required CAS option `service` missing.'); + } + + const cas_url = url.parse(options.validate_url); + if (cas_url.protocol != 'https:' ) { + throw new Error('Only https CAS servers are supported.'); + } else if (!cas_url.hostname) { + throw new Error('Option `validateUrl` must be a valid url like: https://example.com/cas/serviceValidate'); + } else { + this.hostname = cas_url.host; + this.port = 443;// Should be 443 for https + this.validate_path = cas_url.pathname; + } + + this.service = options.service; + } + + validate(ticket, callback) { + const httparams = { + host: this.hostname, + port: this.port, + path: url.format({ + pathname: this.validate_path, + query: {ticket: ticket, service: this.service}, + }), + }; + + https.get(httparams, (res) => { + res.on('error', (e) => { + console.log('error' + e); + callback(e); + }); + + // Read result + res.setEncoding('utf8'); + let response = ''; + res.on('data', (chunk) => { + response += chunk; + }); + + res.on('end', (error) => { + if (error) { + console.log('error callback'); + console.log(error); + callback(undefined, false); + } else { + xmlParser.parseString(response, (err, result) => { + if (err) { + console.log('Bad response format.'); + callback({message: 'Bad response format. XML could not parse it'}); + } else { + if (result['cas:serviceResponse'] == null) { + console.log('Empty response.'); + callback({message: 'Empty response.'}); + } + if (result['cas:serviceResponse']['cas:authenticationSuccess']) { + var userData = { + id: result['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:user'][0].toLowerCase(), + } + const attributes = result['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:attributes'][0]; + for (var fieldName in attributes) { + userData[fieldName] = attributes[fieldName][0]; + }; + callback(undefined, true, userData); + } else { + callback(undefined, false); + } + } + }); + } + }); + }); + } +} +////// END OF CAS MODULE + +let _casCredentialTokens = {}; +let _userData = {}; + +//RoutePolicy.declare('/_cas/', 'network'); + +// Listen to incoming OAuth http requests +WebApp.connectHandlers.use((req, res, next) => { + // Need to create a Fiber since we're using synchronous http calls and nothing + // else is wrapping this in a fiber automatically + + Fiber(() => { + middleware(req, res, next); + }).run(); +}); + +const middleware = (req, res, next) => { + // Make sure to catch any exceptions because otherwise we'd crash + // the runner + try { + urlParsed = url.parse(req.url, true); + + // Getting the ticket (if it's defined in GET-params) + // If no ticket, then request will continue down the default + // middlewares. + const query = urlParsed.query; + if (query == null) { + next(); + return; + } + const ticket = query.ticket; + if (ticket == null) { + next(); + return; + } + + const serviceUrl = Meteor.absoluteUrl(urlParsed.href.replace(/^\//g, '')).replace(/([&?])ticket=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, ''); + const redirectUrl = serviceUrl;//.replace(/([&?])casToken=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, ''); + + // get auth token + const credentialToken = query.casToken; + if (!credentialToken) { + end(res, redirectUrl); + return; + } + + // validate ticket + casValidate(req, ticket, credentialToken, serviceUrl, () => { + end(res, redirectUrl); + }); + + } catch (err) { + console.log("account-cas: unexpected error : " + err.message); + end(res, redirectUrl); + } +}; + +const casValidate = (req, ticket, token, service, callback) => { + // get configuration + if (!Meteor.settings.cas/* || !Meteor.settings.cas.validate*/) { + throw new Error('accounts-cas: unable to get configuration.'); + } + + const cas = new CAS({ + validate_url: Meteor.settings.cas.validateUrl, + service: service, + version: Meteor.settings.cas.casVersion + }); + + cas.validate(ticket, (err, status, userData) => { + if (err) { + console.log("accounts-cas: error when trying to validate " + err); + console.log(err); + } else { + if (status) { + console.log(`accounts-cas: user validated ${userData.id} + (${JSON.stringify(userData)})`); + _casCredentialTokens[token] = { id: userData.id }; + _userData = userData; + } else { + console.log("accounts-cas: unable to validate " + ticket); + } + } + callback(); + }); + + return; +}; + +/* + * Register a server-side login handle. + * It is call after Accounts.callLoginMethod() is call from client. + */ + Accounts.registerLoginHandler((options) => { + if (!options.cas) + return undefined; + + if (!_hasCredential(options.cas.credentialToken)) { + throw new Meteor.Error(Accounts.LoginCancelledError.numericError, + 'no matching login attempt found'); + } + + const result = _retrieveCredential(options.cas.credentialToken); + + const attrs = Meteor.settings.cas.attributes || {}; + // CAS keys + const fn = attrs.firstname || 'cas:givenName'; + const ln = attrs.lastname || 'cas:sn'; + const full = attrs.fullname; + const mail = attrs.mail || 'cas:mail'; // or 'email' + const uid = attrs.id || 'id'; + if (attrs.debug) { + if (full) { + console.log(`CAS fields : id:"${uid}", fullname:"${full}", mail:"${mail}"`); + } else { + console.log(`CAS fields : id:"${uid}", firstname:"${fn}", lastname:"${ln}", mail:"${mail}"`); + } + } + const name = full ? _userData[full] : _userData[fn] + ' ' + _userData[ln]; + // https://docs.meteor.com/api/accounts.html#Meteor-users + options = { + // _id: Meteor.userId() + username: _userData[uid], // Unique name + emails: [ + { address: _userData[mail], verified: true } + ], + createdAt: new Date(), + profile: { + // The profile is writable by the user by default. + name: name, + fullname : name, + email : _userData[mail] + }, + active: true, + globalRoles: ['user'] + }; + if (attrs.debug) { + console.log(`CAS response : ${JSON.stringify(result)}`); + } + let user = Meteor.users.findOne({ 'username': options.username }); + if (! user) { + if (attrs.debug) { + console.log(`Creating user account ${JSON.stringify(options)}`); + } + const userId = Accounts.insertUserDoc({}, options); + user = Meteor.users.findOne(userId); + } + if (attrs.debug) { + console.log(`Using user account ${JSON.stringify(user)}`); + } + return { userId: user._id }; +}); + +const _hasCredential = (credentialToken) => { + return _.has(_casCredentialTokens, credentialToken); +} + +/* + * Retrieve token and delete it to avoid replaying it. + */ +const _retrieveCredential = (credentialToken) => { + const result = _casCredentialTokens[credentialToken]; + delete _casCredentialTokens[credentialToken]; + return result; +} + +const closePopup = (res) => { + if (Meteor.settings.cas && Meteor.settings.cas.popup == false) { + return; + } + res.writeHead(200, {'Content-Type': 'text/html'}); + const content = '<html><body><div id="popupCanBeClosed"></div></body></html>'; + res.end(content, 'utf-8'); +} + +const redirect = (res, whereTo) => { + res.writeHead(302, {'Location': whereTo}); + const content = '<html><head><meta http-equiv="refresh" content="0; url='+whereTo+'" /></head><body>Redirection to <a href='+whereTo+'>'+whereTo+'</a></body></html>'; + res.end(content, 'utf-8'); + return +} + +const end = (res, whereTo) => { + if (Meteor.settings.cas && Meteor.settings.cas.popup == false) { + redirect(res, whereTo); + } else { + closePopup(res); + } +} diff --git a/packages/meteor-accounts-cas/package.js b/packages/meteor-accounts-cas/package.js new file mode 100644 index 00000000..670fe687 --- /dev/null +++ b/packages/meteor-accounts-cas/package.js @@ -0,0 +1,29 @@ +Package.describe({ + summary: "CAS support for accounts", + version: "0.1.0", + name: "wekan:accounts-cas", + git: "https://github.com/wekan/meteor-accounts-cas" +}); + +Package.onUse(function(api) { + api.versionsFrom('METEOR@1.3.5.1'); + api.use('routepolicy', 'server'); + api.use('webapp', 'server'); + api.use('accounts-base', ['client', 'server']); + // Export Accounts (etc) to packages using this one. + api.imply('accounts-base', ['client', 'server']); + api.use('underscore'); + api.add_files('cas_client.js', 'web.browser'); + api.add_files('cas_client_cordova.js', 'web.cordova'); + api.add_files('cas_server.js', 'server'); + +}); + +Npm.depends({ + xml2js: "0.4.17", + cas: "https://github.com/anrizal/node-cas/tarball/2baed530842e7a437f8f71b9346bcac8e84773cc" +}); + +Cordova.depends({ + 'cordova-plugin-inappbrowser': '1.2.0' +}); diff --git a/packages/meteor-useraccounts-core/.editorconfig b/packages/meteor-useraccounts-core/.editorconfig new file mode 100644 index 00000000..6667b413 --- /dev/null +++ b/packages/meteor-useraccounts-core/.editorconfig @@ -0,0 +1,18 @@ +#.editorconfig +# Meteor adapted EditorConfig, http://EditorConfig.org +# By RaiX 2013 + +root = true + +[*.js] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 2 +trim_trailing_whitespace = true +charset = utf-8 +max_line_length = 80 +indent_brace_style = 1TBS +spaces_around_operators = true +quote_type = auto +# curly_bracket_next_line = true diff --git a/packages/meteor-useraccounts-core/.gitignore b/packages/meteor-useraccounts-core/.gitignore new file mode 100644 index 00000000..0f1edf50 --- /dev/null +++ b/packages/meteor-useraccounts-core/.gitignore @@ -0,0 +1,2 @@ +.build* +versions.json diff --git a/packages/meteor-useraccounts-core/.jshintignore b/packages/meteor-useraccounts-core/.jshintignore new file mode 100644 index 00000000..810f9466 --- /dev/null +++ b/packages/meteor-useraccounts-core/.jshintignore @@ -0,0 +1,2 @@ +client/compatibility +packages \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/.jshintrc b/packages/meteor-useraccounts-core/.jshintrc new file mode 100644 index 00000000..7a0c90b0 --- /dev/null +++ b/packages/meteor-useraccounts-core/.jshintrc @@ -0,0 +1,132 @@ +//.jshintrc +{ + // JSHint Meteor Configuration File + // Match the Meteor Style Guide + // + // By @raix with contributions from @aldeed and @awatson1978 + // Source https://github.com/raix/Meteor-jshintrc + // + // See http://jshint.com/docs/ for more details + + "maxerr" : 50, // {int} Maximum error before stopping + + // Enforcing + "bitwise" : true, // true: Prohibit bitwise operators (&, |, ^, etc.) + "camelcase" : true, // true: Identifiers must be in camelCase + "curly" : true, // true: Require {} for every new block or scope + "eqeqeq" : true, // true: Require triple equals (===) for comparison + "forin" : true, // true: Require filtering for..in loops with obj.hasOwnProperty() + "immed" : false, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` + "indent" : 2, // {int} Number of spaces to use for indentation + "latedef" : false, // true: Require variables/functions to be defined before being used + "newcap" : false, // true: Require capitalization of all constructor functions e.g. `new F()` + "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` + "noempty" : true, // true: Prohibit use of empty blocks + "nonew" : false, // true: Prohibit use of constructors for side-effects (without assignment) + "plusplus" : false, // true: Prohibit use of `++` & `--` + "quotmark" : false, // Quotation mark consistency: + // false : do nothing (default) + // true : ensure whatever is used is consistent + // "single" : require single quotes + // "double" : require double quotes + "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) + "unused" : true, // true: Require all defined variables be used + "strict" : true, // true: Requires all functions run in ES5 Strict Mode + "trailing" : true, // true: Prohibit trailing whitespaces + "maxparams" : false, // {int} Max number of formal params allowed per function + "maxdepth" : false, // {int} Max depth of nested blocks (within functions) + "maxstatements" : false, // {int} Max number statements per function + "maxcomplexity" : false, // {int} Max cyclomatic complexity per function + "maxlen" : 80, // {int} Max number of characters per line + + // Relaxing + "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) + "boss" : false, // true: Tolerate assignments where comparisons would be expected + "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. + "eqnull" : false, // true: Tolerate use of `== null` + "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) + "esnext" : false, // true: Allow ES.next (ES6) syntax (ex: `const`) + "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) + // (ex: `for each`, multiple try/catch, function expression…) + "evil" : false, // true: Tolerate use of `eval` and `new Function()` + "expr" : false, // true: Tolerate `ExpressionStatement` as Programs + "funcscope" : false, // true: Tolerate defining variables inside control statements" + "globalstrict" : true, // true: Allow global "use strict" (also enables 'strict') + "iterator" : false, // true: Tolerate using the `__iterator__` property + "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block + "laxbreak" : false, // true: Tolerate possibly unsafe line breakings + "laxcomma" : false, // true: Tolerate comma-first style coding + "loopfunc" : false, // true: Tolerate functions being defined in loops + "multistr" : false, // true: Tolerate multi-line strings + "proto" : false, // true: Tolerate using the `__proto__` property + "scripturl" : false, // true: Tolerate script-targeted URLs + "smarttabs" : false, // true: Tolerate mixed tabs/spaces when used for alignment + "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` + "sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation + "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` + "validthis" : false, // true: Tolerate using this in a non-constructor function + + // Environments + "browser" : true, // Web Browser (window, document, etc) + "couch" : false, // CouchDB + "devel" : true, // Development/debugging (alert, confirm, etc) + "dojo" : false, // Dojo Toolkit + "jquery" : false, // jQuery + "mootools" : false, // MooTools + "node" : false, // Node.js + "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) + "prototypejs" : false, // Prototype and Scriptaculous + "rhino" : false, // Rhino + "worker" : false, // Web Workers + "wsh" : false, // Windows Scripting Host + "yui" : false, // Yahoo User Interface + //"meteor" : false, // Meteor.js + + // Legacy + "nomen" : false, // true: Prohibit dangling `_` in variables + "onevar" : false, // true: Allow only one `var` statement per function + "passfail" : false, // true: Stop on first error + "white" : false, // true: Check against strict whitespace and indentation rules + + // Custom globals, from http://docs.meteor.com, in the order they appear there + "globals" : { + "Meteor": false, + "DDP": false, + "Mongo": false, //Meteor.Collection renamed to Mongo.Collection + "Session": false, + "Accounts": false, + "Template": false, + "Blaze": false, //UI is being renamed Blaze + "UI": false, + "Match": false, + "check": false, + "Tracker": false, //Deps renamed to Tracker + "Deps": false, + "ReactiveVar": false, + "EJSON": false, + "HTTP": false, + "Email": false, + "Assets": false, + "Handlebars": false, // https://github.com/meteor/meteor/wiki/Handlebars + "Package": false, + + // Meteor internals + "DDPServer": false, + "global": false, + "Log": false, + "MongoInternals": false, + "process": false, + "WebApp": false, + "WebAppInternals": false, + + // globals useful when creating Meteor packages + "Npm": false, + "Tinytest": false, + + // common Meteor packages + "Random": false, + "_": false, // Underscore.js + "$": false, // jQuery + "Router": false // iron-router + } +} diff --git a/packages/meteor-useraccounts-core/.travis.yml b/packages/meteor-useraccounts-core/.travis.yml new file mode 100644 index 00000000..7846a282 --- /dev/null +++ b/packages/meteor-useraccounts-core/.travis.yml @@ -0,0 +1,8 @@ +sudo: required +language: node_js +node_js: + - "0.10" +before_install: + - "curl -L http://git.io/ejPSng | /bin/sh" +env: + - TEST_COMMAND=meteor diff --git a/packages/meteor-useraccounts-core/Guide.md b/packages/meteor-useraccounts-core/Guide.md new file mode 100644 index 00000000..c84b3f8b --- /dev/null +++ b/packages/meteor-useraccounts-core/Guide.md @@ -0,0 +1,1433 @@ +User Accounts +============= + +User Accounts is a suite of packages for the [Meteor.js](https://www.meteor.com/) platform. It provides highly customizable user accounts UI templates for many different front-end frameworks. At the moment it includes forms for sign in, sign up, forgot password, reset password, change password, enroll account, and link or remove of many 3rd party services. + +<a name="documentation"/> +# Documentation + +* [Features](#features) +* [Quick Start](#quickstart) + * [Available Versions](#available-versions) + * [Boilerplates](#boilerplates) + * [Setup](#setup) + * [Routing](#routing) + * [Templates](#templates) +* [Basic Customization](#basic-customization) + * [I18n Support](#i18n) + * [Configuration API](#configuration-api) + * [Options](#options) + * [logout](#logout) + * [Internal States](#internal-states) + * [Content Protection](#content-protection) + * [reCaptcha Setup](#reCaptcha-setup) + * [Detect reactively when a form is being processed](#detect-reactively-when-a-form-is-being-processed) +* [Advanced Customization](#advanced-customization) + * [Configuring Texts](#configuring-texts) + * [Form Title](#form-title) + * [Button Text](#button-text) + * [Social Button Icons](#social-button-icons) + * [Info Text](#info-text) + * [Errors Text](#errors-text) + * [Disabling Client-side Accounts Creation](#disabling-client-side-accounts-creation) + * [Form Fields Configuration](#form-fields-configuration) + * [Extending Templates](#extending-templates) + * [Grouping Fields](#grouping-fields) + * [CSS Rules](#css-rules) +* [Wrapping Up for Famo.us](#wrapping-up-for-famo.us) +* [Side Notes](#side-notes) + * [3rd Party Login Services Configuration](#3rd-party-login-services-configuration) + + +<a name="features"/> +## Features + +* fully customizable +* security aware +* internationalization support thanks to [accounts-t9n](https://github.com/softwarerero/meteor-accounts-t9n) +* custom sign-up fields +* robust server side sign-up field validation +* easy content protection +* return to previous route after sign-in (even for random sign in choice and not only after required sign-in) +* fully reactive, Blaze fast! +* no use of `Session` object +* very easily stylizable for different font-end frameworks +* ...[wrap it up for famo.us](#wrapping-up-for-famo.us) with a simple meteor line! + + + +<a name="quickstart"/> +## Quick Start + + +<a name="available-versions"/> +### Available Versions + +* [useraccounts:bootstrap](https://atmospherejs.com/useraccounts/bootstrap) styled for [Twitter Bootstrap](http://getbootstrap.com/) +* [useraccounts:foundation](https://atmospherejs.com/useraccounts/foundation) styled for [Zurb Foundation](http://foundation.zurb.com/) +* [useraccounts:ionic](https://atmospherejs.com/useraccounts/ionic) styled for [Ionic](http://ionicframework.com/) +* [useraccounts:materialize](https://atmospherejs.com/useraccounts/materialize) styled for [Materialize](http://materializecss.com/) +* [useraccounts:polymer](https://atmospherejs.com/useraccounts/polymer) styled for [Polymer](https://www.polymer-project.org/) (WIP) +* [useraccounts:ratchet](https://atmospherejs.com/useraccounts/ratchet) styled for [Ratchet](http://goratchet.com/) +* [useraccounts:semantic-ui](https://atmospherejs.com/useraccounts/semantic-ui) styled for [Semantic UI](http://semantic-ui.com) +* [useraccounts:unstyled](https://atmospherejs.com/useraccounts/unstyled) with plain html and no CSS rules +* plus others coming soon... + + +<a name="boilerplates"/> +### Boilerplates + +For a very very quick start you can find some boilerplate examples inside [this repository](https://github.com/meteor-useraccounts/boilerplates). + +We'll try to make them richer and richer, while still keeping them as general as possible. + +<a name="setup"/> +### Setup + +Just choose one of the packages among the [available styled versions](#available-versions) and install it: + +```Shell +meteor add useraccounts:bootstrap +meteor add <your preferred bootstrap package> +``` + +**Note 1:** no additional packages nor CSS/LESS/SASS files providing styles are included by useraccounts packages. This is to let you choose your preferred way to include them! + +**Note 2:** You don't have to add `useraccounts:core` to your app! It is automatically added when you add `useraccounts:<something>`... + +Then add at least one login service: + +```Shell +meteor add accounts-password +meteor add accounts-facebook +meteor add accounts-google +... +``` + +**Note**: 3rd party services need to be configured... more about this [here](http://docs.meteor.com/#meteor_loginwithexternalservice) + +And that's it! + +...but don't expect to see much without doing something more ;-) +This is to let you configure your app exactly the way you wish, without imposing anything beforehand! + + +<a name="routing"/> +### Routing + +If you'd like to easily configure specific routes to deal with accounts management, you might be interested to check out +[useraccounts:iron-routing](https://github.com/meteor-useraccounts/iron-routing) and [useraccounts:flow-routing](https://github.com/meteor-useraccounts/flow-routing) packages. +They provide very easy routes set-up via the `AccountsTemplates.configureRoute` method. + + +<a name="templates"/> +### Templates + +There is **only one template** which is used to reactively draw appropriate sign in, sign up, forgot password, reset password, change password, and enroll account forms! + +It is `atForm` and can be used anywhere you wish like this: + +```html +{{> atForm}} +``` + +Its design is as *transparent* as possible, making it play nicely with themes and your CSS customizations! Also, it is not wrapped inside any *container* so that you can put it anywhere, including complex multi-column layouts. + +In case you wish to *lock* the template to a particular state, you can specify that via the `state` parameter: + +```html +{{> atForm state='signUp'}} +``` + +This will prevent the template from changing its content. See [internal states](#internal-states) for more details... + + +Well, actually there is many, used inside `atForm`... + +...plus one another: `atNavButton` which can be used inside navbars to get a basic sign-in sign-out button which changes text and behaviour based on the user status (to get it working you should set up at least a `signIn` route). + + +<a name="basic-customization"/> +## Basic Customization + + +<a name="i18n"/> +### I18n Support + +i18n is achieved using [accounts-t9n](https://atmospherejs.com/softwarerero/accounts-t9n). The only thing you have to do is ensure + +```javascript +T9n.setLanguage('<lang>'); +``` + +is called somewhere, whenever you want to switch language. + + +<a name="configuration-api"/> +### Configuration API + +There are basically two different ways to interact with AccountsTemplates for basic configuration: + +* AccountsTemplates.configureRoute(route_code, options); +* AccountsTemplates.configure(options); + +**These functions should be called in top-level code, not inside `Meteor.startup()`.** + +There is no specific order for the above calls to be effective, and you can call them more than once, possibly in different files. + +**The only other requirement is to make exactly the same calls on both the server and the client.** The best thing is to put everything inside a file shared between both. I suggest you use something like `lib/config/at_config.js` + + +<a name="options"/> +#### Options + +By calling `AccountsTemplates.configure(options)` you can specify a bunch of choices regarding both visual appearance and behavior. + +The following is an almost complete example of options configuration (with fields in alphabetical order): + +```javascript +AccountsTemplates.configure({ + // Behavior + confirmPassword: true, + enablePasswordChange: true, + forbidClientAccountCreation: false, + overrideLoginErrors: true, + sendVerificationEmail: false, + lowercaseUsername: false, + focusFirstInput: true, + + // Appearance + showAddRemoveServices: false, + showForgotPasswordLink: false, + showLabels: true, + showPlaceholders: true, + showResendVerificationEmailLink: false, + + // Client-side Validation + continuousValidation: false, + negativeFeedback: false, + negativeValidation: true, + positiveValidation: true, + positiveFeedback: true, + showValidating: true, + + // Privacy Policy and Terms of Use + privacyUrl: 'privacy', + termsUrl: 'terms-of-use', + + // Redirects + homeRoutePath: '/home', + redirectTimeout: 4000, + + // Hooks + onLogoutHook: myLogoutFunc, + onSubmitHook: mySubmitFunc, + preSignUpHook: myPreSubmitFunc, + postSignUpHook: myPostSubmitFunc, + + // Texts + texts: { + button: { + signUp: "Register Now!" + }, + socialSignUp: "Register", + socialIcons: { + "meteor-developer": "fa fa-rocket" + }, + title: { + forgotPwd: "Recover Your Password" + }, + }, +}); +``` + +Details for each of them follow. + +| Option | Type | Default | Description | +| --------------------------- | -------- | --------- | ----------- | +| **Behavior** | | | | +| confirmPassword | Boolean | true | Specifies whether to ask the password twice for confirmation. This has no effect on the sign in form. | +| defaultState | String | "signIn" | Specifies the state to be used initially when atForm is rendered. This is not considered when rendering atForm on configured routes. | +| enablePasswordChange | Boolean | false | Specifies whether to allow to show the form for password change. Note: In case the `changePwd` route is not configured, this is to be done *manually* inside some custom template. | +| enforceEmailVerification | Boolean | false | When set to true together with sendVerificationEmail, forbids user login unless the email address is verified. **Warning: experimental! Use it only if you have accounts-password as the only service!!!** | +| focusFirstInput | Boolean | !Meteor.isCordova | When set to true, asks to autofocus the first input of atForm when the template is rendered. Note: have a look at [this issue](https://github.com/meteor-useraccounts/core/issues/594) in case you're getting problems with cordova apps. | +| forbidClientAccountCreation | Boolean | false | Specifies whether to forbid user registration from the client side. In case it is set to true, neither the link for user registration nor the sign up form will be shown. | +| overrideLoginErrors | Boolean | true | Asks to show a general `Login Forbidden` on a login failure, without specifying whether it was for a wrong email or for a wrong password. | +| sendVerificationEmail | Boolean | false | Specifies whether to send the verification email after successful registration. | +| redirectTimeout | Number | 2000 | Specifies a timeout time for the redirect after successful form submit on `enrollAccount`, `forgotPwd`, `resetPwd`, and `verifyEmail` routes. | +| socialLoginStyle | String | "popup" | Specifies the login style for 3rd party services login. Valid values are `popup` or `redirect`. See `loginStyle` option of [Meteor.loginWith<ExternalService>](http://docs.meteor.com/#/full/meteor_loginwithexternalservice) for more information. | +| lowercaseUsername | Boolean | false | Possibly asks to transform `username` field for user objects at registration time to be always in lowercase with no spaces. The original `username` value will be added to the `user.profile` field for later use. | +| **Appearance** | | | | +| hideSignInLink | Boolean | false | When set to true, asks to never show the link to the sign in page | +| hideSignUpLink | Boolean | false | When set to true, asks to never show the link to the sign up page | +| showAddRemoveServices | Boolean | false | Tells whether to show social account buttons also when the user is signed in. In case it is set to true, the text of buttons will change from 'Sign in With XXX' to 'Add XXX' or 'Remove XXX' when the user signs in. 'Add' will be used if that particular service is still not associated with the current account, while 'Remove' is used only in case a particular service is already used by the user **and** there are at least two services available for sign in operations. Clicks on 'Add XXX' trigger the call to `Meteor.loginWithXXX`, as usual, while click on 'Remove XXX' will call the method `ATRemoveService` provided by AccountsTemplates. This means you need to have some additional logic to deal with the call `Meteor.loginWithXXX` in order to actually add the service to the user account. One solution to this is to use the package [accounts-meld](https://atmospherejs.com/package/accounts-meld) which was build exactly for this purpose. | +| showForgotPasswordLink | Boolean | false | Specifies whether to display a link to the forgot password page/form | +| showLabels | Boolean | true | Specifies whether to display text labels above input elements. | +| showPlaceholders | Boolean | true | Specifies whether to display place-holder text inside input elements. | +| showResendVerificationEmailLink | Boolean | false | Specifies whether to display a link to the resend verification email page/form | +| **Texts** | | | | +| texts | Object | | Permits to specify texts to be shown on the atForm for each of its states (see [below](#configuring-texts)). | +| **Client-side Validation** | | | | +| continuousValidation | Boolean | false | Specifies whether to continuously validate fields' value while the user is typing. *It is performed client-side only to save round trips with the server*. | +| negativeValidation | Boolean | false | Specifies whether to highlight input elements in case of negative validation. | +| positiveValidation | Boolean | false | Specifies whether to highlight input elements in case of positive validation. | +| negativeFeedback | Boolean | false | Specifies whether to display negative validation feed-back inside input elements. | +| positiveFeedback | Boolean | false | Specifies whether to display positive validation feed-back inside input elements. | +| showValidating | Boolean | false | Specifies whether to display a loading icon inside input elements while the validation process is in progress. | +| **Links** | | | | +| homeRoutePath | String | '/' | Path for the home route, to be possibly used for redirects after successful form submission. | +| privacyUrl | String | undefined | Path for the route displaying the privacy document. In case it is specified, a link to the page will be displayed at the bottom of the form (when appropriate). | +| termsUrl | String | undefined | Path for the route displaying the document about terms of use. In case it is specified, a link to the page will be displayed at the bottom of the form (when appropriate). | +| **Hooks** | | | | +| onLogoutHook | Function | | Called on `AccountsTemplates.logout` invocation: allows for custom redirects or whatever custom action to be taken on user logout. | +| onSubmitHook | Function | | `func(error, state)` Called when the `pwdForm` is being submitted: allows for custom actions to be taken on form submission. `error` contains possible errors occurred during the submission process, `state` specifies the `atForm` internal state from which the submission was triggered. A nice use case might be closing the modal or side-menu showing `atForm` | +| preSignUpHook | Function | | `func(password, info)` Called just before submitting the `pwdForm` for sign-up: allows for custom actions on the data being submitted. A nice use could be extending the user profile object accessing `info.profile`. to be taken on form submission. The plain text `password` is also provided for any reasonable use. | +| postSignUpHook | Function | | `func(userId, info)` Called, **server side only**, just after a successfull user account creation, post submitting the `pwdForm` for sign-up: allows for custom actions on the data being submitted ___after___ we are sure a new user was ___successfully___ created. A common use might be applying roles to the user, as this is only possible after fully completing user creation in alanning:roles. The `userId` is available as the first parameter, so that user user object may be retrieved. The `password` is not available as it's already encrypted, though the encrypted password may be found in `info` if of use. | + +##### onSubmitHook + +A straightforward configuration about how to detect when a user logs in or registers might look like the following: + +```javascript +var mySubmitFunc = function(error, state){ + if (!error) { + if (state === "signIn") { + // Successfully logged in + // ... + } + if (state === "signUp") { + // Successfully registered + // ... + } + } +}; + +AccountsTemplates.configure({ + onSubmitHook: mySubmitFunc +}); +``` + +<a name="logout"/> +##### AccountsTemplates.logout() + +Should be used in place of `Meteor.logout()`. This function invokes the `onLogoutHook` specified in the optional configuration. +Also note that `AccountsTemplates.logout()` is invoked when logging out using the `atNavButton`. + + +```javascript +//Use in place of Meteor.logout() in your client code. Also called automatically by atNavButton when clicking Sign Off +AccountsTemplates.logout(); + +``` + + +```javascript +var myPostLogout = function(){ + //example redirect after logout + Router.go('/home'); +}; + +AccountsTemplates.configure({ + onLogoutHook: myPostLogout +}); +``` + +<a name="internal-states"/> +### Internal States + +The `atForm` template changes reactively based on the current internal state of AccountsTemplates. +The current internal state can be queried with `AccountsTemplates.getState()` and set with `AccountsTemplates.setState(new_state)` + + +Currently available states are: + +| Internal State | What's shown | +| ----------------------- | ------------------------------------------------------------------------------------- | +| changePwd | Change password form asking to set a new password | +| enrollAccount | Account Enrollment form asking to set a password | +| forgotPwd | Forgot Password form asking for the email address where to send a reset password link | +| hide | None at all... | +| resendVerificationEmail | Login form with an additional button to get another verification email | +| resetPwd | Reset Password form asking to set a password | +| signIn | Login form | +| signUp | Registration form | +| verifyEmail | Only the result about email verification | + + + +<a name="content-protection"/> +### Content Protection + + +If you want to secure a specific template, you could add that template like this: + +```handlebars +{{> ensureSignedIn template="myTemplate"}} +``` +and that will render the default `fullPageAtForm` template from your chosen User Accounts templates package (bootstrap, materialize, etc). Once signed in, it'll render `myTemplate` instead of the accounts form. + +If you want to declare a custom sign in template instead of `fullPageAtForm`, you would do this: + +```handlebars +{{> ensureSignedIn template="myTemplate" auth="myLoginForm"}} +``` +That custom auth template just needs to include `{{> atForm}}` somewhere in it. The only reason you'd use this optional feature is if you wanted to modify the layout around the `atForm` template (like +`fullPageAtForm` does). + + +In case you're using one of the routing packages [useraccounts:iron-routing](https://github.com/meteor-useraccounts/iron-routing) +or [useraccounts:flow-routing](https://github.com/meteor-useraccounts/flow-routing) refer to their documentation for more possibilities. + + +<a name="reCaptcha-setup"/> +### reCaptcha Setup +To set up [reCaptcha](https://www.google.com/recaptcha/intro/index.html), you need to first obtain API keys. + +Then, a recommended setup is as follows. + +A [Meteor settings file](http://docs.meteor.com/#/full/meteor_settings) with the keys: + +```javascript +{ + "public": { + "reCaptcha": { + "siteKey": YOUR SITE KEY + } + }, + "reCaptcha": { + "secretKey": YOUR SECRET KEY + } +} +``` + +and configuration to show the reCaptcha widget: + +```javascript +AccountsTemplates.configure({ + showReCaptcha: true +}); +``` + +The reCaptcha plugin can likewise be set up with the following complete example: + + +```javascript +AccountsTemplates.configure({ + reCaptcha: { + siteKey: YOUR SITE KEY, + theme: "light", + data_type: "image" + }, + showReCaptcha: true +}); +``` + +And, in a separate file in the `/server` folder: + +```javascript +AccountsTemplates.configure({ + reCaptcha: { + secretKey: YOUR SECRET KEY. + }, +}); +``` + +Each option is described below: + +| Option | Type | Default | Description | +| --------------------------- | -------- | --------- | ----------- | +| siteKey | String | none | The site key needed to create the reCaptcha widget. This can be specified in just the Meteor settings file. | +| secretKey | String | none | The secret key needed to verify the reCaptcha response. ***Warning: Only set this in a file in `/server` or in a Meteor settings file. Otherwise, your private key can be read by anyone!*** | +| theme | String | "light" | Sets the reCaptcha theme color. The options are "light" and "dark". | +| data_type | String | "image" | Sets the verification method. Options are "image" or "audio". | +| showReCaptcha | Boolean | false | Whether to show the reCaptcha widget on sign in or not. No reCaptcha validation will occur if set to false. | + +<a name="detect-reactively-when-a-form-is-being-processed"/> +### Detect reactively when a form is being processed + +`AccountsTemplates.disabled()` returns `true` when a submitted form is being processed and `false` once the submission process has been completed (successfully or not). `AccountsTemplate.disabled()` is reactive and can be used to trigger UI events, such as spinners, "Please wait" messages or to disable input elements, while the form is being processed. The function works irrespectively of form status (signIn, signUp, pwdReset etc.). A typical use-case would be in a template helper: + +```html +<template name="myLogin"> + {{#if atDisabled}} + Please wait... + {{/if}} + <div class="{{atClass}}"> + {{> atForm}} + </div> +</template> +``` + +```js +Template.myLogin.helpers({ + atDisabled: function() { + return AccountsTemplates.disabled(); + }, + atClass: function() { + return AccountsTemplates.disabled() ? 'disabled' : 'active'; + } +}); +``` + +<a name="advanced-customization"/> +## Advanced Customization + + +<a name="configuring-texts"/> +### Configuring Texts + +In case you wish to change texts on atForm, you can call: + +```javascript +AccountsTemplates.configure({ + texts: { + navSignIn: "signIn", + navSignOut: "signOut", + optionalField: "optional", + pwdLink_pre: "", + pwdLink_link: "forgotPassword", + pwdLink_suff: "", + resendVerificationEmailLink_pre: "Verification email lost?", + resendVerificationEmailLink_link: "Send again", + resendVerificationEmailLink_suff: "", + sep: "OR", + signInLink_pre: "ifYouAlreadyHaveAnAccount", + signInLink_link: "signin", + signInLink_suff: "", + signUpLink_pre: "dontHaveAnAccount", + signUpLink_link: "signUp", + signUpLink_suff: "", + socialAdd: "add", + socialConfigure: "configure", + socialIcons: { + "meteor-developer": "fa fa-rocket", + }, + socialRemove: "remove", + socialSignIn: "signIn", + socialSignUp: "signUp", + socialWith: "with", + termsPreamble: "clickAgree", + termsPrivacy: "privacyPolicy", + termsAnd: "and", + termsTerms: "terms", + } +}); +``` + +the above example asks to change some of the available text configurations. You can specify only a subsets of them leaving default values unchanged. +To learn how to change title, button, social buttons' icon, info, and errors text read below. + + +<a name="form-title"/> +#### Form Title + +In case you wish to change form titles, you can call: + +```javascript +AccountsTemplates.configure({ + texts: { + title: { + changePwd: "Password Title", + enrollAccount: "Enroll Title", + forgotPwd: "Forgot Pwd Title", + resetPwd: "Reset Pwd Title", + signIn: "Sign In Title", + signUp: "Sign Up Title", + verifyEmail: "Verify Email Title", + } + } +}); +``` + +the above example asks to change the title for all possible form states, but you can specify only a subset of them leaving default values unchanged. + +You can also *hide* a title by setting it to an empty string. For example with: + +``` +AccountsTemplates.configure({ + texts: { + title: { + signIn: "", + } + } +}); +``` + +no title will be shown on the sign in form. + + +<a name="button-text"/> +#### Button Text + +In case you wish to change the text appearing inside the submission button, you can call: + +```javascript +AccountsTemplates.configure({ + texts: { + button: { + changePwd: "Password Text", + enrollAccount: "Enroll Text", + forgotPwd: "Forgot Pwd Text", + resetPwd: "Reset Pwd Text", + signIn: "Sign In Text", + signUp: "Sign Up Text", + } + } +}); +``` + +the above example asks to change the button text for all possible form states, but you can specify only a subset of them leaving default values unchanged. + +<a name="social-button-icons"/> +#### Social Button Icons + +In case you wish to change the icon appearing on the left of social login buttons, you can call: + +```javascript +AccountsTemplates.configure({ + texts: { + socialIcons: { + google: "myGoogleIcon", + "meteor-developer": "myMeteorIcon", + } + } +}); +``` + +to specify a different icon classes to be used for services. By default the icon class is set to `fa fa-*service*`, +but for the "meteor-developer" service for which `fa fa-rocket` is used. An exception is made for `useaccounts:semantic-ui` +which sets them simply to `*service*`, which is the correct way to go. + +<a name="info-text"/> +#### Info Text + +In case you wish to change the info text appearing inside the results box, you can call: + +```javascript +AccountsTemplates.configure({ + texts: { + info: { + emailSent: "info.emailSent", + emailVerified: "info.emailVerified", + pwdChanged: "info.passwordChanged", + pwdReset: "info.passwordReset", + pwdSet: "info.passwordReset", + signUpVerifyEmail: "Successful Registration! Please check your email and follow the instructions.", + verificationEmailSent: "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.", + } + } +}); +``` + +The above calls simply set all values as the current default ones. + +<a name="input-icons"/> +#### Input Field Icons + +In case you wish to change the icon appearing on the right side of input fields to show their validation status, you can call: + +```javascript +AccountsTemplates.configure({ + texts: { + inputIcons: { + isValidating: "fa fa-spinner fa-spin", + hasSuccess: "fa fa-check", + hasError: "fa fa-times", + } + } +}); +``` + +<a name="errors-text"/> +#### Errors Text + +In case you wish to change the text for errors appearing inside the error box, you can call: + +```javascript +AccountsTemplates.configure({ + texts: { + errors: { + accountsCreationDisabled: "Client side accounts creation is disabled!!!", + cannotRemoveService: "Cannot remove the only active service!", + captchaVerification: "Captcha verification failed!", + loginForbidden: "error.accounts.Login forbidden", + mustBeLoggedIn: "error.accounts.Must be logged in", + pwdMismatch: "error.pwdsDontMatch", + validationErrors: "Validation Errors", + verifyEmailFirst: "Please verify your email first. Check the email and follow the link!", + } + } +}); +``` + +The above calls simply set all values as the current default ones. +*Note:* The above list of errors refers to those set directly by AccountsTemplates only! +Errors which comes from the Accounts packages cannot be overwritten (at least not easily...) +Please have a look at [Form Fields Configuration](#form-fields-configuration) to learn how to set validation errors on a field basis. + + +<a name="disabling-client-side-accounts-creation"/> +### Disabling Client-side Accounts Creation + +AccountsTemplates disables by default accounts creation on the client. This is done to use a dedicated method called `ATCreateUserServer` **(sending the password on the wire already hashed as usual...)** to create the new users server-side. +This way a bulletproof profile fields full validation can be performed. +But there is one more parameter to set in case you'd like to forbid client-side accounts creation, which is the following: + +* `forbidClientAccountCreation` - (Boolean, default false) Specifies whether to forbid accounts creation from the client. + +it is exactly the same provided by the Accounts object, so this means you need to do: + +```javascript +AccountsTemplates.configure({ + forbidClientAccountCreation: true +}); +``` + +instead of the usual: + +```javascript +Accounts.config({ + forbidClientAccountCreation : true +}); +``` + + +<a name="form-fields-configuration"/> +### Form Fields Configuration + +Every input field appearing inside AccountsTemplates forms can be easily customized both for appearance and validation behaviour. Additional (custom) fields can be added to the sign up and registration forms, and the properties of built-in fields, like `email` and `password` can be overridden (see [Remove fields](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#remove-fields)) + +Each field object is represented by the following properties: + +| Property | Type | Required | Description | +| -------------------- | -----------------|:--------:| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| _id | String | X | A unique field's id/name (internal use only) to be also used as attribute name into `Meteor.user().profile` in case it identifies an additional sign up field. Usually all lowercase letters. | +| type | String | X | Specifies the input element type. At the moment supported inputs are: `password`, `email`, `text`, `tel`, `url`, `checkbox`, `select`, `radio`, `hidden`. | +| required | Boolean | | When set to true the corresponding field cannot be left blank | +| displayName | String or Object | | The field name to be shown as text label above the input element. In case nothing is specified, the capitalized `_id` is used. The text label is shown only if `showLabels` options is set to true. | +| placeholder | String or Object | | The placeholder text to be shown inside the input element. In case nothing is specified, the capitalized `_id` will be used. The place-holder is shown only if `showPlaceholders` option is set to true. | +| select | [Object] | | Lets you specify an array of choices to be displayed for select and radio inputs. See example below. | +| minLength | Integer | | If specified, requires the content of the field to be at least `minLength` characters. | +| maxLength | Integer | | If specified, require the content of the field to be at most `maxLength` characters. | +| re | RegExp | | Possibly specifies the regular expression to be used for the field's content validation. Validation is performed both client-side (at every input change if `continuousValidation` option is set to true) and server-side on form submit. | +| func | Function | | Custom function to be used for validation. | +| errStr | String | | Error message to be displayed in case re or func validation fail. | +| trim | Boolean | | Trim the input value. | +| lowercase | Boolean | | Convert the input value to lowercase. | +| uppercase | Boolean | | Convert the input value to uppercase. | +| transform | Function | | Custom function to transform the input value. | +| continuousValidation | Boolean | | Continuously validate fields' value while the user is typing. *It is performed client-side only to save round trips with the server*. | +| negativeValidation | Boolean | | Highlight input elements in case of negative validation. | +| positiveValidation | Boolean | | Highlight input elements in case of positive validation. | +| negativeFeedback | Boolean | | Display negative validation feedback inside input elements. | +| positiveFeedback | Boolean | | Display positive validation feedback inside input elements. | +| showValidating | Boolean | | Display a loading icon inside input elements while the validation process is in progress. | +| options | Object | | Allows to pass in additional custom options to be possibly used to extend input templates (see [Extending Templates](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#extending-templates)) | +| template | String | | The name of a custom template to be used in place of the default one. | + + +`displayName`, `placeholder`, and `errStr` can also be an [accounts-t9n](https://atmospherejs.com/softwarerero/accounts-t9n) registered key, in which case it will be translated based on the currently selected language. +In case you'd like to specify a key which is not already provided by accounts-t9n you can always map your own keys. To learn how to register new labels, please refer to the official [documentation](https://github.com/softwarerero/meteor-accounts-t9n#define-translations). + +`continuousValidation`, `negativeFeedback`, `negativeValidation`, `positiveValidation`, `positiveFeedback`, `showValidating` can be used to override global settings (see [Form Fields Configuration](#form-fields-configuration)) on a per field basis. + +Furthermore, you can pass an object for `displayName`, `placeholder` to specify different texts for different form states. The matched pattern is: + +```javascript +{ + default: Match.Optional(String), + changePwd: Match.Optional(String), + enrollAccount: Match.Optional(String), + forgotPwd: Match.Optional(String), + resetPwd: Match.Optional(String), + signIn: Match.Optional(String), + signUp: Match.Optional(String), +} +``` + +which permits to specify a different text for each different state, or a default value to be used for states which are not explicitly provided. For example: + +```javascript +AccountsTemplates.addField({ + _id: 'password', + type: 'password', + placeholder: { + signUp: "At least six characters" + }, + required: true, + minLength: 6, + re: /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/, + errStr: 'At least 1 digit, 1 lowercase and 1 uppercase', +}); +``` + +asks AccountsTemplates to display "At least six characters" as the placeholder for the password field when the sign up form is display, and to display "Password" (the capitalized *_id*_) in any other case. + +##### Custom validation +Custom validation can be achieved by providing a regular expression or a function. In case you go for the function solution, this: + +```javascript +AccountsTemplates.addField({ + _id: 'name', + type: 'text', + displayName: "Name", + func: function(value){return value !== 'Full Name';}, + errStr: 'Only "Full Name" allowed!', +}); +``` + +will require the name input to be exactly "Full Name" (though this might not be that interesting...). +If instead you do something along the following line: + +```javascript +AccountsTemplates.addField({ + _id: 'phone', + type: 'tel', + displayName: "Phone", + required: true, + func: function (number) { + if (Meteor.isServer){ + if (isValidPhone(number)) + return false; // meaning no error! + return true; // Validation error! + } + }, + errStr: 'Invalid Phone number!', +}); +``` + +supposing `isValidPhone` is available only server-side, you will be validating the field only server-side, on form submission. + +If, differently, you do something like this: + +```javascript +if (Meteor.isServer){ + Meteor.methods({ + "userExists": function(username){ + return !!Meteor.users.findOne({username: username}); + }, + }); +} + +AccountsTemplates.addField({ + _id: 'username', + type: 'text', + required: true, + func: function(value){ + if (Meteor.isClient) { + console.log("Validating username..."); + var self = this; + Meteor.call("userExists", value, function(err, userExists){ + if (!userExists) + self.setSuccess(); + else + self.setError(userExists); + self.setValidating(false); + }); + return; + } + // Server + return Meteor.call("userExists", value); + }, +}); +``` + +you can achieve also client-side and server-side validation calling a server method +During the waiting time a loading icon will be displayed (if you configure `showValidating` to be true). +To configure the loading icon see [Input Field Icons](#input-icons). + +*Note:* `field.setError(err)`, `field.setSuccess()`, and `field.setValidating()` are methods used to deal with inputs' validation states. A `null` value means non-validated, `false` means correctly validated, no error, and any other value evaluated as true (usually strings specifying the reason for the validation error), are finally interpreted as error and displayed where more appropriate. + +#### Checkboxes, Selects, Radios, and Hidden + +This is an example about how to add Checkboxes, Selects, and Radios to the sign up fields: + +```javascript +AccountsTemplates.addField({ + _id: "gender", + type: "select", + displayName: "Gender", + select: [ + { + text: "Male", + value: "male", + }, + { + text: "Female", + value: "female", + }, + ], +}); + +AccountsTemplates.addField({ + _id: "fruit", + type: "radio", + displayName: "Preferred Fruit", + select: [ + { + text: "Apple", + value: "aa", + }, { + text: "Banana", + value: "bb", + }, { + text: "Carrot", + value: "cc", + }, + ], +}); + +AccountsTemplates.addField({ + _id: "mailing_list", + type: "checkbox", + displayName: "Subscribe me to mailing List", +}); + +AccountsTemplates.addField({ + _id: 'reg_code', + type: 'hidden' +}); +``` + +please note the `select` list which lets you specify the values for the choice. +The `value` value of corresponding selected `text` will be picked up and added into the `profile` field of the user object. + +Hidden inputs might be of help in case you want to consider to link to your registration page from around the web (emails, ads, discount campaigns, etc...) with links like this: + +``` +http://my.splendido.site/sign-up?email=giorgio@example.com®_code=123 +``` + +exploiting the ability of AccountsTemplates to pick-up query parameters having the same key as field ids, this would permit to get `reg_code: "123"` under the `profile` field of the user object. +**Please use this with caution!** ..never ever do something like: +``` +http://my.splendido.site/sign-up?role=admin +``` +and then set the role of the new user based on the hidden `role` field. I guess you can appreciate the security hole there ;-) + +#### Special Field's Ids + +There are a number of special ids used for basic input fields. These are: + +* current_password +* email +* password +* password_again +* username +* username_and_email + +Any other id will be interpreted as an additional sign up field. +In case a special field is not explicitly added, it will be automatically inserted at initialization time (with appropriate default properties). To customize special fields see [Remove fields](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#remove-fields) + +#### Add a field + +You can use `AccountsTemplates.addField(options)` to configure an input field. This apply for both special fields and custom ones. +For example you can do: + +```javascript +AccountsTemplates.addField({ + _id: 'phone', + type: 'tel', + displayName: "Landline Number", +}); +``` + +The above snippet asks `AccountsTemplates` to draw an additional input element within the sign-up form. + +#### Add many fields at once + +Another possibility is to add many additional fields at once using `addFields`: + +```javascript +AccountsTemplates.addFields([ + { + _id: 'phone', + type: 'tel', + displayName: "Landline Number", + }, + { + _id: 'fax', + type: 'tel', + displayName: "Fax Number", + } +]); +``` + +#### Remove fields + +There is also a `removeField` method which can be used to remove predefined required fields and adding them again specify different options. + +```javascript +AccountsTemplates.removeField('password'); +AccountsTemplates.addField({ + _id: 'password', + type: 'password', + required: true, + minLength: 6, + re: /(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/, + errStr: 'At least 1 digit, 1 lower-case and 1 upper-case', +}); +``` + +#### Login with Username or Email + +In order to let the user register with both a `username` and an `email` address and let him the possibility to log in using one of them, both the `username` and `email` fields must be added. +This is an example about how to configure such a behaviour: + +```javascript +var pwd = AccountsTemplates.removeField('password'); +AccountsTemplates.removeField('email'); +AccountsTemplates.addFields([ + { + _id: "username", + type: "text", + displayName: "username", + required: true, + minLength: 5, + }, + { + _id: 'email', + type: 'email', + required: true, + displayName: "email", + re: /.+@(.+){2,}\.(.+){2,}/, + errStr: 'Invalid email', + }, + pwd +]); +``` + +This will trigger the automatic insertion of the special field `username_and_email` to be used for the sign in form. +If you wish to further customize the `username_and_email` field you can add it together with the other two: + +```javascript +var pwd = AccountsTemplates.removeField('password'); +AccountsTemplates.removeField('email'); +AccountsTemplates.addFields([ + { + _id: "username", + type: "text", + displayName: "username", + required: true, + minLength: 5, + }, + { + _id: 'email', + type: 'email', + required: true, + displayName: "email", + re: /.+@(.+){2,}\.(.+){2,}/, + errStr: 'Invalid email', + }, + { + _id: 'username_and_email', + type: 'text', + required: true, + displayName: "Login", + }, + pwd +]); +``` + + +<a name="extending-templates"/> +### Extending Templates + +With the [aldeed:template-extension](https://github.com/aldeed/meteor-template-extension) package, the built-in templates or sub-templates of any `user-accounts` UI package may be replaced by custom templates. The purpose is to create more sophisticated or specialized layouts or styling. + +In case of input fields the option `template` (see [Form Fields Configuration](#form-fields-configuration)) can be directly used without the need to rely on `aldeed:template-extension` package. + +Here is a simple example of a template you can use for a field of type 'select': + +```html +<template name="customSelectTemplate"> + <select id="at-field-{{_id}}" name="at-field-{{_id}}" data-something="{{options.someOption}}"> + {{#each select}} + <option value="{{value}}">{{text}}</option> + {{/each}} + </select> +</template> +``` + +Custom properties that hold information about the look of the form may be attached to the `options` object of a field. It may then be used to change the output while looping the fields. Adding a divider might look like this: + +```javascript +AccountsTemplates.addField({ + _id: "address", + type: "text", + + // Options object with custom properties for my layout. At the moment, there are + // no special properties; it is up the developer to invent them + options: { + // Put a divider before this field + dividerBefore: true + } +}); +``` + +```html +<template name="appAtInput"> + {{#if options.dividerBefore}}<hr>{{/if}} + + {{> Template.dynamic template=templateName}} +</template> +``` + +```javascript +Template.appAtInput.replaces("atInput"); +``` + + +<a name="grouping-fields"/> +#### Grouping fields + +Grouping fields together is a special problem in regard to layout. The issue is creating some container markup *while* iterating over the fields (the templating engine of Meteor doesn't allow outputting an opening tag inside a loop without closing it in the same iteration). + +A solution to the problem is demonstrated in [this gist](https://gist.github.com/dalgard/a844f6569d8f471db9a7) (Semantic UI version). + + +<a name="css-rules"/> +### CSS Rules + +The main atForm is build up of several pieces, appearing and disappearing based on configuration options as well as the current internal status. +Each of these blocks is wrapped inside a `div` with class `at-<something>`: this should made your life easier if you're trying to write your own CSS rules to change templates' appearance. + +Social login buttons (`button.at-social-btn`) have an `id` in the form `at-<servicename>` and name `<servicename>`. + +Input fields for the password service form are wrapped inside a div with class `at-input`. The same div gets classes `has-error`, `has-success`, and `has-feedback` in case of negative validation result, positive validation and validation with feedback respectively. +The input element itself has id and name in the form `at-field-<field_id>`. +**Note:** `has-error`, `has-success`, and `has-feedback` names might change from framework to framework. These are valid for the *unstyled* and *bootstrap* versions... + + +Below is a html snapshot of an over-complete `atForm` taken from the unstyled version in which you can find all elements possibly shown under different configurations and circumstances. + +```html +<div class="at-form"> + <!-- Title --> + <div class="at-title"> + <h3>Create an Account</h3> + </div> + <!-- Social Buttons for Oauth Sign In / Sign Up--> + <div class="at-oauth"> + <button class="at-social-btn" id="at-facebook" name="facebook"> + <i class="fa fa-facebook"></i> Sign in with Facebook + </button> + <button class="at-social-btn" id="at-twitter" name="twitter"> + <i class="fa fa-twitter"></i> Sign in with Twitter + </button> + </div> + <!-- Services Separator --> + <div class="at-sep"> + <strong>OR</strong> + </div> + <!-- Global Error --> + <div class="at-error"> + <p>Login forbidden</p> + </div> + <!-- Global Resutl --> + <div class="at-result"> + <p>Email Sent!</p> + </div> + <!-- Password Service --> + <div class="at-pwd-form"> + <form role="form" id="at-pwd-form" novalidate=""> + <!-- Input --> + <div class="at-input"> + <label for="at-field-username"> + Username + </label> + <input type="text" id="at-field-username" name="at-field-username" placeholder="Username" autocapitalize="none" autocorrect="off"> + </div> + <!-- Input with Validation Error --> + <div class="at-input has-error"> + <label for="at-field-email"> + Email + </label> + <input type="email" id="at-field-email" name="at-field-email" placeholder="Email" autocapitalize="none" autocorrect="off"> + <span>Invalid email</span> + </div> + <!-- Input with Successful Validation --> + <div class="at-input has-success"> + <label for="at-field-password"> + Password + </label> + <input type="password" id="at-field-password" name="at-field-password" placeholder="Password" autocapitalize="none" autocorrect="off"> + </div> + <!-- Forgot Password Link --> + <div class="at-pwd-link"> + <p> + <a href="/forgot-password" id="at-forgotPwd" class="at-link at-pwd">Forgot your password?</a> + </p> + </div> + <!-- Form Submit Button --> + <button type="submit" class="at-btn submit disabled" id="at-btn"> + Register + </button> + </form> + </div> + <!-- Link to Sign In --> + <div class="at-signin-link"> + <p> + If you already have an account + <a href="/sign-in" id="at-signIn" class="at-link at-signin">sign in</a> + </p> + </div> + <!-- Link to Sign Up --> + <div class="at-signup-link"> + <p> + Don't have an account? + <a href="/sign-up" id="at-signUp" class="at-link at-signup">Register</a> + </p> + </div> + <!-- Link to Privacy Policy and Terms of use --> + <div class="at-terms-link"> + <p> + By clicking Register, you agree to our + <a href="/privacyPolicy">Privacy Policy</a> + and + <a href="/termsOfUse">Terms of Use</a> + </p> + </div> +</div> +``` + + + +<a name="wrapping-up-for-famo.us"/> +## Wrapping Up for Famo.us + +By simply typing + +```shell +meteor add useraccounts:famous-wrapper +``` + +you'll be able to turn your preferred flavour of accounts templates into a package ready to be used within a [famous-views](https://atmospherejs.com/gadicohen/famous-views) + [Famo.us](http://famo.us) application. + +This means you can get an animated version of the `atForm` template without any effort! :-) + +To learn how to make animations you might want to check the following links: + +* http://famous-views.meteor.com +* http://famous-views.meteor.com/examples/animate +* http://famo.us/university/lessons/#/famous-101/animating/1 +* http://famo.us/guides/layout +* http://famo.us/guides/animations +* http://famo.us/docs/modifiers/StateModifier +* http://famo.us/docs/transitions/Transitionable + +### configureAnimations + +...well, actually it might be that you don't like the default animations so you might consider to use `AccountsTemplates.configureAnimations` (provided by the wrapper...) to specify your custom animation functions. +This is an example showing how to do it: + +```javascript +var Transform; +var Easing; +if (Meteor.isClient){ + FView.ready(function(require) { + Transform = famous.core.Transform; + Easing = famous.transitions.Easing; + }); +} + +var slideLeftDestroy = function(fview){ + fview.modifier.setTransform( + Transform.translate(-$(window).width(),0), + { duration : 250, curve: Easing.easeOutSine }, + function() { fview.destroy();} + ); +}; + + +AccountsTemplates.configureAnimations({ + destroy: { + atSignupLink: slideLeftDestroy, + } +}); +``` + +this asks AT to use `slideLeftDestroy` to animate the template `atSignupLink` when it is to be destroyed. + +As you've just seen `configureAnimations` take an `options` object as parameter: + +```javascript +AccountsTemplates.configureAnimations(options); +``` + +this options object can have three different keys at the first level: + +```javascript +var options = { + render: { + // more stuff here... + }, + destroy: { + // more stuff here... + }, + state_change: { + // more stuff here... + }, + animQueueDelay: 100, + animQueueStartDelay: 200, + setStateDelay: 300, + +}; +AccountsTemplates.configureAnimations(options); +``` + +they are `render`, `destroy`, `state_change`, `animQueueDelay`, `animQueueStartDelay`, and `setStateDelay`. +The first three, what a surprise, they let you specify what to do when one of the templates building up the `atForm` is rendered, destroyed or when the form's state changes (respectively). + +...at the second level you can specify which animation has to be applied to which template: + +```javascript +var options = { + render: { + default: animA, + atTitle: animB, + atSocial: animC, + atSep: animC, + atError: animB, + atResult: animB, + atPwdForm: null, + atSigninLink: null, + atSignupLink: animB, + atTermsLink: animD, + }, + // ... +}; +``` + +the above one is the full list of available animated templates... +The value you specify can be `null` (to remove a default animation...) or a function. +If you specify a function it should be like the following: + +```javascript +var animFunc = function(fview){ + fview.modifier.setTransform( + Transform.<some_transform>( ... ), + { duration : <millisecs>, curve: Easing.<some_curve> } + ); +}; +``` + +the `fview` parameter actually let you access the famous view associated with the template (so feel free to do whatever you wish with it...). + +**Warning:** when you specify an animation to be used on `destroy` you must take care of the actual destroy! +...usually it is enough to call `fview.destroy()` when the animation completes: + +```javascript +var animFunc = function(fview){ + fview.modifier.setTransform( + Transform.<some_transform>( ... ), + { duration : <millisecs>, curve: Easing.<some_curve> }, + function(){ fview.destroy();} + ); +}; +``` + +**Warning2:** At the moment the animation for the state change is supposed to last for double the `setStateDelay` duration, and the state change is actually postponed by `setStateDelay` milliseconds. This let you divide your animation in two different part (so, e.g., you can hide things and show them again with the new content...). +The following is the default animations used on state change: + +```javascript +vFlip = function(fview){ + fview.modifier.setTransform( + Transform.rotate(Math.PI-0.05,0,0), + { + duration : AccountsTemplates.animations.setStateDelay, + curve: "easeIn", + }, + function() { + fview.modifier.setTransform( + Transform.rotate(-0.1,0,0), + { + duration : AccountsTemplates.animations.setStateDelay, + curve: "easeOut", + } + ); + } + ); +}; +``` + +and as you can see schedules two different animations, one after the another, lasting `setStateDelay` ms each. + + +### pushToAnimationQueue + +In case you're interested in sequence animation, AT also provides an experimental animation cue you can use to schedule your animation with a bit of delay between them. +To use it simply wrap the `modifier.setTransform` within an `AccountsTemplates.pushToAnimationQueue` call, like this: + +```jacascript +var fallFromTop = function(fview){ + fview.modifier.setTransform(Transform.translate(0, -$(window).height())); + AccountsTemplates.pushToAnimationQueue(function() { + fview.modifier.setTransform( + Transform.translate(0,0), + { duration : 450, curve: Easing.easeOutSine } + ); + }); +}; +``` + +the full signature for it is: + +```javascript +AccountsTemplates.pushToAnimationQueue(func, at_begin); +``` + +and if pass `true` for `at_begin`, the function will be pushed to the begin of the cue rather than at the end. + +The first animation is started after `animQueueStartDelay` milliseconds from the first insertion and a delay of `animQueueStartDelay` milliseconds is applied between start of animations (you can configure these two values with `configureAnimations` function as listed above...). + +And that's it! +Enjoy ;-) + + +<a name="side-notes"/> +## Side Notes + + +<a name="3rd-party-login-services-configuration"/> +### 3rd Party Login Services Configuration + +Normally, if you have not configured a social account with, e.g., + +```javascript +// Set up login services +Meteor.startup(function() { + // Add Facebook configuration entry + ServiceConfiguration.configurations.update( + { "service": "facebook" }, + { + $set: { + "appId": "XXXXXXXXXXXXXXX", + "secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + } + }, + { upsert: true } + ); + + // Add GitHub configuration entry + ServiceConfiguration.configurations.update( + { "service": "github" }, + { + $set: { + "clientId": "XXXXXXXXXXXXXXXXXXXX", + "secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + } + }, + { upsert: true } + ); +}); +``` + +3rd party login buttons are not shown. To allow display buttons with, e.g., 'Configure Foobook', simply add the packages `service-configuration` and `accounts-ui` with: + +```Shell +meteor add service-configuration +meteor add accounts-ui +``` + +**Warning**: At the moment the UI for service configuration is not supported and the one provided by `accounts-ui` will be shown! diff --git a/packages/meteor-useraccounts-core/History.md b/packages/meteor-useraccounts-core/History.md new file mode 100644 index 00000000..61bcfaf9 --- /dev/null +++ b/packages/meteor-useraccounts-core/History.md @@ -0,0 +1,353 @@ +## Master + +## v1.14.2 + +* [flow-routing] fixed dependency on kadira:flow-router: now using the last non-Meteor@1.3 one + +## v1.14.1 + +* fixed automatic update of weak dependencies on routing packages when publishing new versions + +## v1.14.0 + +* [bulma] *new* `useraccounts:bulma` package to get UI templates styled for [Bulma](http://bulma.io/) (thanks to @dominikmayer) +* [flow-routing] better error management (merged https://github.com/meteor-useraccounts/flow-routing/pull/23 thanks @stubailo) +* [flow-routing] added support for FlowRouter 3 (merged https://github.com/meteor-useraccounts/flow-routing/pull/26 thanks @timothyarmes) +* [foundation-sites] *new* `useraccounts:foundation-sites` package to get UI templates styled for [Foundation for Sites 6](http://foundation.zurb.com/sites.html) (thanks to @venetianthief) +* [materialize] Added row around recaptcha (thanks @qwIvan) +* some minor fixed to the Guide + +## v1.13.1 + +* added language support to recaptcha (fixed https://github.com/meteor-useraccounts/core/issues/561 tnx @canesin) +* fixed validation trigger for select inputs (see discussion within https://github.com/meteor-useraccounts/core/issues/569 tnx @cunneen) +* change default value for `focusFirstInput` to get it disabled when running on Cordova (see https://github.com/meteor-useraccounts/core/issues/594 tnx @derwaldgeist) +* fixed regression about reCaptcha reset due to https://github.com/meteor-useraccounts/core/pull/565 (merged https://github.com/meteor-useraccounts/core/pull/597 tnx @jebh) + +## v1.13.0 + +* [mdl] *new* `useraccounts:mdl` package to get UI templates styled for [Material Design Lite](http://www.getmdl.io/) (kudos to @kctang and @liquidautumn, thank you guys!). +* [flow-routing] added support for React-based layouts (merged https://github.com/meteor-useraccounts/flow-routing/pull/20 tnx @timothyarmes). +* [materialize] fixed offset problem for fullPageAtForm on medium screens. +* [materialize] fixed some margins (see https://github.com/meteor-useraccounts/materialize/issues/19). +* [iron-routing] fixed a problem with route paths (merged https://github.com/meteor-useraccounts/iron-routing/pull/8 tnx @trave7er). +* [core] updated dependency to softwarerero:accounts-t9n@1.1.7 +* [core] fixed a bug with reCaptcha (merged https://github.com/meteor-useraccounts/core/pull/565 tnx @scsirdx). +* [core] added missing dependency on JQuery (merged https://github.com/meteor-useraccounts/core/pull/574 tnx @stubailo). +* [core] added postSignUpHook hook to let people modify newly created user objects (merged https://github.com/meteor-useraccounts/core/pull/586 tnx @shwaydogg) +* added [Meteor Icon](http://www.getmdl.io/) badges to all packages' README file. + +## v1.12.4 + +* fixed input element classes for `useraccounts:materialize` (see https://github.com/meteor-useraccounts/materialize/pull/18) +* fixed query parameters look-up for `useraccounts:iron-routing` +* updated `useraccounts:polymer` to use Polimer 1.0 (see updated [boilerplate](https://github.com/meteor-useraccounts/boilerplates/tree/master/polymer) with some instructions for Meteor 1.2) +* updates and fixes for `useraccounts:flow-rounting` (see https://github.com/meteor-useraccounts/flow-routing/issues/12) +* improoved css for `useraccounts:semantic-ui` +* disallowed use of `signUp` state in case `forbidClientAccountCreation` is set (see #547) +* updated dependency on softwarerero:accounts-t9n to version 1.1.4 +* a bit of linting here and there... +* a few typos correction and improvements to the [Guide](https://github.com/meteor-useraccounts/core/blob/master/Guide.md) + +## v1.12.3 + +* fixed radio buttons for useraccounts:materialize (see https://github.com/meteor-useraccounts/core/issues/421) +* fixed query parameters pick up for useraccounts:iron-routing (see meteor-useraccounts/core#367) +* corrected few typos within the docs and removed unnecessary debug log + +## v1.12.2 + +* various fixes and a bit of clean up for `useraccounts:flow-routing` + + +## v1.12.1 + +* fixed inifinite redirect loop for `ensuredSignedIn` within `useraccounts:flow-routing` (see https://github.com/meteor-useraccounts/flow-routing/issues/2) + + +## v1.12.0 + +* removed routing support from core: refer to [useraccounts:iron-routing](https://github.com/meteor-useraccounts/iron-routing) and [useraccounts:flow-routing](https://github.com/meteor-useraccounts/flow-routing) packages to get some ;-) +* added template level content protection (see new [Content Protection](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#content-protection) section) +* updated `useraccounts:semantic-ui` to SUI v2.0 (thanks @lumatijev) +* `displayName` configuration option for form fields now accepts also functions +* added the `focusFirstInput` configuration option +* fixed many typos and added/removed some sections in the Guide + + +## v1.11.1 + +* fixes for #410, #411, and #413 +* Added a section about available internal states to the Guide (see [Internal States](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#internal-states) + + +## v1.11.0 + +* change `profile.username` to `profile.name` when using `lowercaseUsername` options (WARNING! this is a bit of a breaking change, see #388) +* removed possibly annoying warning (see #398) +* added a `preSignUpHook` to be possibly used to enrich the user profile just before new user registration (see #400) +* route configuration now accepts additional parameters to be passed to IR (see #409) +* some improvements to the docs + +## v1.10.0 + +* more customizable texts (see 7d166b74f111e05b22ef2c7d93908441e242350d) +* added autofocus for the first input field of `atPwdForm`. +* fixed some texts configuration capability (see #380) +* various corrections/improvements to the docs +* allowed for `field.setError` to take in Boolean values (see #361) +* fixed bug with `Must be logged in` error message shown after sign out (see #321) + +## v1.9.1 + +* aligned `useraccounts:unstyled` with the latest PRs + +## v1.9.0 + +* resend verification email (see #349, thanks @dalgard) +* allow for a neutral message text to be displayed (see #314 and #317, thanks @dalgard) +* more configurable error texts (see [Errors Text](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#errors-text), plus #301 #342) +* fixed little redirect bug (see #315) +* added title configuration for `verifyEmail` state plus letting titles to be hidden by + setting the corresponding text to an empy string (see [Form Title](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#form-title)) + +## v1.8.1 + +* made (a fake) `ensureSignedIn` plugin available also on server side code (fixed #291) + +## v1.8.0 + +* added `lowercaseUsername` configuration option (see [Configuration API Options](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#options)) +* added `ensureSignedIn` plugin for Iron Router (see [Content Protection](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#content-protection)) +* fixed `ensureSignedIn` regression (see #286) + +## v1.7.1 + +* fixed routing regression (see #284) +* removed useless logs + +## v1.7.0 + +* `useraccounts:materialize` to the suite! (Many thanks to @Kestanous!!!) +* fixed glitch within `ensureSignedIn` (see #278) +* added experimental support for [reChaptcha](https://www.google.com/recaptcha/intro/index.html) (see #268 and [reCaptcha Setup](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#recaptcha-setup), great work @theplatapi!) +* new `template` option for deeper input fields customization (see #273 and [Form Fields Configuration](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#form-fields-configuration)) +* prevent access to `atChangePwd` for users not being logged in (see #207) +* use `Meteor.userID()` in place of `Meteor.user()` where possible to reduce reactive re-computations +* fixed bug with timed out redirects (see #263) +* fixed reactivity bug within `ensureSignedIn` (see #262) +* removed warning about MAIL_URL not being configured (see #267, #210) +* better `atNavButton` behaviour (see #265 tnx @adrianmc) + +## v1.6.1 + +* updated deps for iron:router and softwarerero:accounts-t9n to latest versions + +## v1.6.0 + +* moved the documentation to a separate file: [Guide](https://github.com/meteor-useraccounts/core/blob/master/Guide.md) +* fixed bug about calling `sibmitHook` (see #249 #252 tnx @dalgard) +* new `options` for field configuration (see #250 and [Extending Templates](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#extending-templates) tnx @dalgard) +* a bit of cleanup for docs (see #251 tnx @dalgard) +* capitalazed default value for display name and placeholder (see #247) +* switch to official `Accounts._hasPassword` (see [this](https://github.com/meteor/meteor/pull/2271) and [this](https://github.com/meteor/meteor/pull/3410), tnx @glasser) +* more sites using useraccounts: congrats to @nate-strauser and @msamoylov on their launches! (see [the list](https://github.com/meteor-useraccounts/core#whos-using-this)) +* new landing page for the whole project and new live examples (still to be further improoved...) :) (see [useraccounts.meteor.com](https://useraccounts.meteor.com)) +* added `transform` among the options for [field configuration](https://github.com/meteor-useraccounts/core/blob/master/Guide.md#form-fields-configuration) +* better behaviour for input value tranform/fix +* terms and agreements now showed also on enrollment form (see #253) +* link to singIn now shown also on forgot password form in case `forbidClientAccountCreation` is set to true (partial solution to #229) +* moved terms and agreements link right after the submit button (see #239) + +## v1.5.0 + +* added `useraccounts:polymer` to the suite! (WIP, Thanks @kevohagan!!!) +* fixed a bug with atVerifyEmail route (see #241 and #173) +* little docs improovements + +## v1.4.1 + +* updated dependency to softwarerero:accounts-t9n@1.0.5 to include Turkish language +* fixed `{{> atForm state='<state>'}}` which was no more working with Meteor@1.0.2 (see #217) +* fixed some text configuration (see #209, thanks @bumbleblym) +* fixed some typos into the docs (see #208, thanks @bumbleblym) + +## v1.4.0 + +* added `useraccounts:ionic` to the suite! (Thanks @nickw!!!) +* updated `useraccounts:semantic-ui` to SemanticUI@1.0.0 (Thanks @lumatijev!!!) +* added `onLogoutHook` to be able to run code (custom redirects?) on `AccountsTemplates.logout` (see #191) +* added `onSubmitHook` among configuration parameters to be able to run code on form submission (might be useful for modals! see #201 and #180) +* submission button get now disabled also during fields (asynchronous) validation +* `enforceEmailVerification` now works also with username login (fixed #196) +* better IE compatibility (see #199) +* better input field validation flows to recover from previous errors (see #177) +* updated dependency to softwarerero:accounts-t9n@1.0.4 +* new [Contributing section](https://github.com/meteor-useraccounts/core#contributing) among docs +* a few improvements and typo fixes for README.md + +## v1.3.2 / 2014/11/25 + +* more robust logout pattern when dealing with routes protected with ensureSigndIn + +## v1.3.1 / 2014/11/25 + +* updated dependency to iron:router@1.0.3 +* fixed bug in linkClick (see #170) +* fixed bug in configureRoute + +## v1.3.0 / 2014/11/23 + +* added support for [Ratchet](http://goratchet.com/): see [useraccounts:ratchet](https://atmospherejs.com/useraccounts/ratchet). Note: form validation is currently not supported by Ratchet! +* fixed bug in custom validation flow +* better default validation for `email` field (see #156) +* few corrections inside docs +* added `ensuredSignedIn` among configurable routes so that different `template` and `layoutTemplate` can be specified (fix for #160 and #98) +* added `socialLoginStyle` among the configuration options to select the login flow (`popup` or `redirect`) for 3rd party login services (see #163) +* fixed bug about fields ordering + +## v1.2.3 / 2014/11/13 + +* put back in a `init` method dispalying a warning to preserve backward compatibility... + +## v1.2.2 / 2014/11/12 + +* fixed bad redirect for cheange password route (see #154) + +## v1.2.1 / 2014/11/12 + +* fixed regression due reactivity problems after fix for #139 + +## v1.2.0 / 2014/11/12 + +* **breaking change:** removed the need to call `Accounts.init()` +* added support for fields' validating state to display a 'loading' icon +* added support for fields' icon configuration +* added support for social buttons' icon configuration (see [this](https://github.com/meteor-useraccounts/core#social-button-icons) new section) +* added support for `meteor-developer` oauth service (see #147) +* fixed (special) fields ordering, see #144 +* fixed ensureSignedIn (see #152) +* removed `new_password` and `new_password_again` special fields, simply use `password` and `password_again` from now on! +* better redirect behaviour when a logged in user lands on a sign-in/sign-up page: usual redirect is now performed. (see #139) +* better field validation patterns... +* updated dependency to irou:router@1.0.1 +* updated dependency to softwarerero:accounts-t9n@1.0.2 +* corrected many errors and typos inside the Documentation + +## v1.1.1 +## v1.1.0 + +* fixed `atNavButton` for useraccounts:unstyled +* fixed variour names and links in README files + +## v1.1.0 + +* new template `atNavButton` +* added methos `AccountsTemplates.logout()` which redirects back to `homeRoutePath` when configured +* support for hidden fields +* url query parameters loaded into input fields -> useful mostly for hidden fields ;-) +* granted full control over field ordering (except for special fields...). see #135 +* fixes for #130, #132 + +## v1.0.1 + +* fixed link to git repositories inside package.js files + +## v1.0.0 + +* new names: no more splendido:accounts-templates:<somethig> but useraccounts:<somethig> ! +* updated iron:router to v1.0.0 + +## v0.11.0 + +* added support for checkbox, select, and radio inputs +* added defaultState as referred in #125 +* fixes for #127 + +## v0.10.0 + +* better texts configuration API (as for #117) +* prevPath fix + + +## v0.9.16 + +* updated iron:router to v0.9.4 + +## v0.9.15 + +* fixed #110 + +## v0.9.14 + +* fixed some redirection problems connected with `ensureSignedIn` + +## v0.9.13 + +* experimental implementation for forbidding access with unverified email (see #108) through configuration flag `enforceEmailVerification` +* added options to hide links: hideSignInLink, hideSignUpLink +* fixed #107 + +## v0.9.12 + +* fixed #109 + +## v0.9.11 + +* better submit button disabling when no negative feedback is used +* fixed #105 + +## v0.9.10 + +* added `defaultLayout` to configuration options +* new callback parameter to `setState` +* better rendering behaviour on `ensureSignedIn` + +## v0.9.9 + +* Fixed links for `reset-password`, `enroll-account`, and `verify-email` + +## v0.9.8 + +* fixed checks for login services (see #93) +* minor updates to docs + +## v0.9.7 + +* fixed #92, to permit the use of, e.g., `{{> atForm state="changePwd"}}` ( see [docs](https://github.com/splendido/accounts-templates-core#templates)) + +## v0.9.6 + +* fixed #91, pwdForm submission on signin page has no effect unless both password and usename/email are not empty + +## v0.9.5 + +* show title on sign in also with other services +* moved sign in link below pwd form +* removed sign in link from forgot-pwd page (sign up link is still there!) +* added class at-btn to submit button +* added class at-signin to sign in link +* added class at-signup to sign up link +* added class at-pwd to forgot password link +* accounts-t9n dependency updated to @1.0.0 + +## v0.9.4 + + +## Older versions (to be written) + +* Fixes for #19, #24, #25, #26 +* layoutTemplate option +* Better signup flow, with proper server side validation! +* Fixes for #15, and #16 +* Do not show validation errors during sign in +* Do not show sign up link when account creation is disabled +* Better use of UnderscoreJS +* Corrected documentation for showAddRemoveServices + +## v0.0.9 + +* added configuration parameter [`showAddRemoveServices`](https://github.com/splendido/accounts-templates-core#appearance) +* Fix ensureSignedIn for drawing correct template + +## v0.0.8 diff --git a/packages/meteor-useraccounts-core/LICENSE.md b/packages/meteor-useraccounts-core/LICENSE.md new file mode 100644 index 00000000..aba77efb --- /dev/null +++ b/packages/meteor-useraccounts-core/LICENSE.md @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 [@splendido](https://github.com/splendido) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/meteor-useraccounts-core/README.md b/packages/meteor-useraccounts-core/README.md new file mode 100644 index 00000000..cc8d0bf8 --- /dev/null +++ b/packages/meteor-useraccounts-core/README.md @@ -0,0 +1,104 @@ +[![Meteor Icon](http://icon.meteor.com/package/useraccounts:core)](https://atmospherejs.com/useraccounts/core) +[![Build Status](https://travis-ci.org/meteor-useraccounts/core.svg?branch=master)](https://travis-ci.org/meteor-useraccounts/core) + +# User Accounts + +User Accounts is a suite of packages for the [Meteor.js](https://www.meteor.com/) platform. It provides highly customizable user accounts UI templates for many different front-end frameworks. At the moment it includes forms for sign in, sign up, forgot password, reset password, change password, enroll account, and link or remove of many 3rd party services. + +## Some Details + +The package `useraccounts:core` contains all the core logic and templates' helpers and events used by dependant packages providing styled versions of the accounts UI. +This means that developing a version of the UI with a different styling is just a matter of writing a few dozen of html lines, nothing more! + +Thanks to [accounts-t9n](https://github.com/softwarerero/meteor-accounts-t9n) you can switch to your preferred language on the fly! Available languages are now: Arabic, Czech, French, German, Italian, Polish, Portuguese, Russian, Slovenian, Spanish, Swedish, Turkish and Vietnamese. + +For basic routing and content protection, `useraccounts:core` integrates with either [flow-router](https://github.com/meteor-useraccounts/flow-routing) or [iron-router](https://atmospherejs.com/package/iron-router). + +Any comments, suggestions, testing efforts, and PRs are very very welcome! Please use the [repository](https://github.com/meteor-useraccounts/ui) issues tracker for reporting bugs, problems, ideas, discussions, etc.. + +## The UserAccounts Guide +Detailed explanations of features and configuration options can be found in the <a href="https://github.com/meteor-useraccounts/core/blob/master/Guide.md" target="_blank">Guide</a>. + +## Who's using this? + +* [Abesea](https://abesea.com/) +* [backspace.academy](http://backspace.academy/) +* [bootstrappers.io](http://www.bootstrappers.io/) +* [crater.io](http://crater.io/) +* [Dechiper Chinese](http://app.decipherchinese.com/) +* [Henfood](http://labs.henesis.eu/henfood) +* [meteorgigs.io](https://www.meteorgigs.io/) +* [Orion](http://orionjs.org/) +* [Telescope](http://www.telesc.pe/) +* [We Work Meteor](http://www.weworkmeteor.com/) + + +Aren't you on the list?! +If you have a production app using accounts templates, let me know! I'd like to add your link to the above ones. + +## Contributing +Contributors are very welcome. There are many things you can help with, +including finding and fixing bugs and creating examples for the brand new [wiki](https://github.com/meteor-useraccounts/wiki). +We're also working on `useraccounts@2.0` (see the [Milestone](https://github.com/meteor-useraccounts/core/milestones)) so you can also help +with an improved design or adding features. + +Some guidelines below: + +* **Questions**: Please create a new issue and label it as a `question`. + +* **New Features**: If you'd like to work on a feature, + start by creating a 'Feature Design: Title' issue. This will let people bat it + around a bit before you send a full blown pull request. Also, you can create + an issue to discuss a design even if you won't be working on it. + +* **Bugs**: If you think you found a bug, please create a "reproduction." This is a small project that demonstrates the problem as concisely as possible. If you think the bug can be reproduced with only a few steps a description by words might be enough though. The project should be cloneable from Github. Any bug reports without a reproduction that don't have an obvious solution will be marked as "awaiting-reproduction" and closed after a bit of time. + +### Working Locally +This is useful if you're contributing code to useraccounts or just trying to modify something to suit your own specific needs. + +##### Scenario A + +1. Set up a local packages folder +2. Add the PACKAGE_DIRS environment variable to your .bashrc file + - Example: `export PACKAGE_DIRS="/full/path/topackages/folder"` + - Screencast: https://www.eventedmind.com/posts/meteor-versioning-and-packages +3. Clone the repository into your local packages directory +4. Add the package just like any other meteor core package like this: `meteor + add useraccounts:unstyled` + +```bash +> cd /full/path/topackages/folder +> git clone https://github.com/meteor-useraccounts/semantic-ui.git +> cd your/project/path +> meteor add useraccounts:semantic-ui +> meteor +``` + +##### Scenario B + +Like Scenario A, but skipping point 2. +Add the official package as usual with `meteor add useraccounts:semantic-ui` but then run your project like this: + +```bash +> PACKAGE_DIRS="/full/path/topackages/folder" meteor +``` + +##### Scenario C + +```bash +> cd your/project/path +> mkdir packages && cd packages +> git clone https://github.com/meteor-useraccounts/semantic-ui.git +> cd .. +> meteor add useraccounts:semantic-ui +> meteor +``` + + +## Thanks + +Anyone is welcome to contribute. Fork, make your changes, and then submit a pull request. + +Thanks to [all those who have contributed code changes](https://github.com/meteor-useraccounts/ui/graphs/contributors) and all who have helped by submitting bug reports and feature ideas. + +[![Support via Gittip](https://rawgithub.com/twolfson/gittip-badge/0.2.0/dist/gittip.png)](https://www.gittip.com/splendido/) diff --git a/packages/meteor-useraccounts-core/lib/client.js b/packages/meteor-useraccounts-core/lib/client.js new file mode 100644 index 00000000..31c9db74 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/client.js @@ -0,0 +1,464 @@ +/* global + AT: false +*/ +"use strict"; + +// Allowed Internal (client-side) States +AT.prototype.STATES = [ + "changePwd", // Change Password + "enrollAccount", // Account Enrollment + "forgotPwd", // Forgot Password + "hide", // Nothing displayed + "resetPwd", // Reset Password + "signIn", // Sign In + "signUp", // Sign Up + "verifyEmail", // Email verification + "resendVerificationEmail", // Resend verification email +]; + +AT.prototype._loginType = ""; + +// Flag telling whether the whole form should appear disabled +AT.prototype._disabled = false; + +// State validation +AT.prototype._isValidState = function(value) { + return _.contains(this.STATES, value); +}; + +// Flags used to avoid clearing errors and redirecting to previous route when +// signing in/up as a results of a call to ensureSignedIn +AT.prototype.avoidRedirect = false; +AT.prototype.avoidClearError = false; + +// Token to be provided for routes like reset-password and enroll-account +AT.prototype.paramToken = null; + +AT.prototype.loginType = function () { + return this._loginType; +}; + +AT.prototype.getparamToken = function() { + return this.paramToken; +}; + +// Getter for current state +AT.prototype.getState = function() { + return this.state.form.get("state"); +}; + +// Getter for disabled state +AT.prototype.disabled = function() { + return this.state.form.equals("disabled", true) ? "disabled" : undefined; +}; + +// Setter for disabled state +AT.prototype.setDisabled = function(value) { + check(value, Boolean); + return this.state.form.set("disabled", value); +}; + +// Setter for current state +AT.prototype.setState = function(state, callback) { + check(state, String); + + if (!this._isValidState(state) || (this.options.forbidClientAccountCreation && state === 'signUp')) { + throw new Meteor.Error(500, "Internal server error", "accounts-templates-core package got an invalid state value!"); + } + + this.state.form.set("state", state); + if (!this.avoidClearError) { + this.clearState(); + } + this.avoidClearError = false; + + if (_.isFunction(callback)) { + callback(); + } +}; + +AT.prototype.clearState = function() { + _.each(this._fields, function(field) { + field.clearStatus(); + }); + + var form = this.state.form; + + form.set("error", null); + form.set("result", null); + form.set("message", null); + + AccountsTemplates.setDisabled(false); +}; + +AT.prototype.clearError = function() { + this.state.form.set("error", null); +}; + +AT.prototype.clearResult = function() { + this.state.form.set("result", null); +}; + +AT.prototype.clearMessage = function() { + this.state.form.set("message", null); +}; + +// Initialization +AT.prototype.init = function() { + console.warn("[AccountsTemplates] There is no more need to call AccountsTemplates.init()! Simply remove the call ;-)"); +}; + +AT.prototype._init = function() { + if (this._initialized) { + return; + } + + var usernamePresent = this.hasField("username"); + var emailPresent = this.hasField("email"); + + if (usernamePresent && emailPresent) { + this._loginType = "username_and_email"; + } else { + this._loginType = usernamePresent ? "username" : "email"; + } + + if (this._loginType === "username_and_email") { + // Possibly adds the field username_and_email in case + // it was not configured + if (!this.hasField("username_and_email")) { + this.addField({ + _id: "username_and_email", + type: "text", + displayName: "usernameOrEmail", + placeholder: "usernameOrEmail", + required: true, + }); + } + } + + // Only in case password confirmation is required + if (this.options.confirmPassword) { + // Possibly adds the field password_again in case + // it was not configured + if (!this.hasField("password_again")) { + var pwdAgain = _.clone(this.getField("password")); + + pwdAgain._id = "password_again"; + pwdAgain.displayName = { + "default": "passwordAgain", + changePwd: "newPasswordAgain", + resetPwd: "newPasswordAgain", + }; + pwdAgain.placeholder = { + "default": "passwordAgain", + changePwd: "newPasswordAgain", + resetPwd: "newPasswordAgain", + }; + this.addField(pwdAgain); + } + } else { + if (this.hasField("password_again")) { + throw new Error("AccountsTemplates: a field password_again was added but confirmPassword is set to false!"); + } + } + + // Possibly adds the field current_password in case + // it was not configured + if (this.options.enablePasswordChange) { + if (!this.hasField("current_password")) { + this.addField({ + _id: "current_password", + type: "password", + displayName: "currentPassword", + placeholder: "currentPassword", + required: true, + }); + } + } + + // Ensuser the right order of special fields + var moveFieldAfter = function(fieldName, referenceFieldName) { + var fieldIds = AccountsTemplates.getFieldIds(); + var refFieldId = _.indexOf(fieldIds, referenceFieldName); + // In case the reference field is not present, just return... + if (refFieldId === -1) { + return; + } + + var fieldId = _.indexOf(fieldIds, fieldName); + // In case the sought field is not present, just return... + if (fieldId === -1) { + return; + } + + if (fieldId !== -1 && fieldId !== (refFieldId + 1)) { + // removes the field + var field = AccountsTemplates._fields.splice(fieldId, 1)[0]; + // push the field right after the reference field position + var newFieldIds = AccountsTemplates.getFieldIds(); + var newReferenceFieldId = _.indexOf(newFieldIds, referenceFieldName); + AccountsTemplates._fields.splice(newReferenceFieldId + 1, 0, field); + } + }; + + // Ensuser the right order of special fields + var moveFieldBefore = function(fieldName, referenceFieldName) { + var fieldIds = AccountsTemplates.getFieldIds(); + var refFieldId = _.indexOf(fieldIds, referenceFieldName); + // In case the reference field is not present, just return... + if (refFieldId === -1) { + return; + } + + var fieldId = _.indexOf(fieldIds, fieldName); + // In case the sought field is not present, just return... + if (fieldId === -1) { + return; + } + + if (fieldId !== -1 && fieldId !== (refFieldId - 1)) { + // removes the field + var field = AccountsTemplates._fields.splice(fieldId, 1)[0]; + // push the field right after the reference field position + var newFieldIds = AccountsTemplates.getFieldIds(); + var newReferenceFieldId = _.indexOf(newFieldIds, referenceFieldName); + AccountsTemplates._fields.splice(newReferenceFieldId, 0, field); + } + }; + + // The final order should be something like: + // - username + // - email + // - username_and_email + // - password + // - password_again + // + // ...so lets do it in reverse order... + moveFieldAfter("username_and_email", "username"); + moveFieldAfter("username_and_email", "email"); + moveFieldBefore("current_password", "password"); + moveFieldAfter("password", "current_password"); + moveFieldAfter("password_again", "password"); + + + // Sets visibility condition and validation flags for each field + var gPositiveValidation = !!AccountsTemplates.options.positiveValidation; + var gNegativeValidation = !!AccountsTemplates.options.negativeValidation; + var gShowValidating = !!AccountsTemplates.options.showValidating; + var gContinuousValidation = !!AccountsTemplates.options.continuousValidation; + var gNegativeFeedback = !!AccountsTemplates.options.negativeFeedback; + var gPositiveFeedback = !!AccountsTemplates.options.positiveFeedback; + + _.each(this._fields, function(field) { + // Visibility + switch(field._id) { + case "current_password": + field.visible = ["changePwd"]; + break; + case "email": + field.visible = ["forgotPwd", "signUp", "resendVerificationEmail"]; + if (AccountsTemplates.loginType() === "email") { + field.visible.push("signIn"); + } + break; + case "password": + field.visible = ["changePwd", "enrollAccount", "resetPwd", "signIn", "signUp"]; + break; + case "password_again": + field.visible = ["changePwd", "enrollAccount", "resetPwd", "signUp"]; + break; + case "username": + field.visible = ["signUp"]; + if (AccountsTemplates.loginType() === "username") { + field.visible.push("signIn"); + } + break; + case "username_and_email": + field.visible = []; + if (AccountsTemplates.loginType() === "username_and_email") { + field.visible.push("signIn"); + } + break; + default: + field.visible = ["signUp"]; + } + + // Validation + var positiveValidation = field.positiveValidation; + if (_.isUndefined(positiveValidation)) { + field.positiveValidation = gPositiveValidation; + } + + var negativeValidation = field.negativeValidation; + if (_.isUndefined(negativeValidation)) { + field.negativeValidation = gNegativeValidation; + } + + field.validation = field.positiveValidation || field.negativeValidation; + if (_.isUndefined(field.continuousValidation)) { + field.continuousValidation = gContinuousValidation; + } + + field.continuousValidation = field.validation && field.continuousValidation; + if (_.isUndefined(field.negativeFeedback)) { + field.negativeFeedback = gNegativeFeedback; + } + + if (_.isUndefined(field.positiveFeedback)) { + field.positiveFeedback = gPositiveFeedback; + } + + field.feedback = field.negativeFeedback || field.positiveFeedback; + // Validating icon + var showValidating = field.showValidating; + if (_.isUndefined(showValidating)) { + field.showValidating = gShowValidating; + } + + // Custom Template + if (field.template) { + if (field.template in Template) { + Template[field.template].helpers(AccountsTemplates.atInputHelpers); + } else { + console.warn( + "[UserAccounts] Warning no template " + field.template + " found!" + ); + } + } + }); + + // Initializes reactive states + var form = new ReactiveDict(); + + form.set("disabled", false); + form.set("state", "signIn"); + form.set("result", null); + form.set("error", null); + form.set("message", null); + this.state = { + form: form, + }; + + // Possibly subscribes to extended user data (to get the list of registered services...) + if (this.options.showAddRemoveServices) { + Meteor.subscribe("userRegisteredServices"); + } + + //Check that reCaptcha site keys are available and no secret keys visible + if (this.options.showReCaptcha) { + var atSiteKey = null; + var atSecretKey = null; + var settingsSiteKey = null; + var settingsSecretKey = null; + + if (AccountsTemplates.options.reCaptcha) { + atSiteKey = AccountsTemplates.options.reCaptcha.siteKey; + atSecretKey = AccountsTemplates.options.reCaptcha.secretKey; + } + + if (Meteor.settings && Meteor.settings.public && Meteor.settings.public.reCaptcha) { + settingsSiteKey = Meteor.settings.public.reCaptcha.siteKey; + settingsSecretKey = Meteor.settings.public.reCaptcha.secretKey; + } + + if (atSecretKey || settingsSecretKey) { + //erase the secret key + if (atSecretKey) { + AccountsTemplates.options.reCaptcha.secretKey = null; + } + + if (settingsSecretKey) { + Meteor.settings.public.reCaptcha.secretKey = null; + } + + var loc = atSecretKey ? "User Accounts configuration!" : "Meteor settings!"; + throw new Meteor.Error(401, "User Accounts: DANGER - reCaptcha private key leaked to client from " + loc + + " Provide the key in server settings ONLY."); + } + + if (!atSiteKey && !settingsSiteKey) { + throw new Meteor.Error(401, "User Accounts: reCaptcha site key not found! Please provide it or set showReCaptcha to false."); + } + } + + // Marks AccountsTemplates as initialized + this._initialized = true; +}; + +AT.prototype.linkClick = function(route) { + if (AccountsTemplates.disabled()) { + return; + } + + AccountsTemplates.setState(route); + + if (AccountsTemplates.options.focusFirstInput) { + var firstVisibleInput = _.find(this.getFields(), function(f) { + return _.contains(f.visible, route); + }); + + if (firstVisibleInput) { + $("input#at-field-" + firstVisibleInput._id).focus(); + } + } +}; + +AT.prototype.logout = function() { + var onLogoutHook = AccountsTemplates.options.onLogoutHook; + + Meteor.logout(function() { + if (onLogoutHook) { + onLogoutHook(); + } + }); +}; + +AT.prototype.submitCallback = function(error, state, onSuccess) { + var onSubmitHook = AccountsTemplates.options.onSubmitHook; + + if (onSubmitHook) { + onSubmitHook(error, state); + } + + if (error) { + if (_.isObject(error.details)) { + // If error.details is an object, we may try to set fields errors from it + _.each(error.details, function(error, fieldId) { + AccountsTemplates.getField(fieldId).setError(error); + }); + } else { + var err = "error.accounts.Unknown error"; + + if (error.reason) { + err = error.reason; + } + + if (err.substring(0, 15) !== "error.accounts.") { + err = "error.accounts." + err; + } + + AccountsTemplates.state.form.set("error", [err]); + } + + AccountsTemplates.setDisabled(false); + // Possibly resets reCaptcha form + if (state === "signUp" && AccountsTemplates.options.showReCaptcha) { + grecaptcha.reset(); + } + } else { + if (onSuccess) { + onSuccess(); + } + + if (state) { + AccountsTemplates.setDisabled(false); + } + } +}; + +AccountsTemplates = new AT(); + +// Initialization +Meteor.startup(function() { + AccountsTemplates._init(); +}); diff --git a/packages/meteor-useraccounts-core/lib/core.js b/packages/meteor-useraccounts-core/lib/core.js new file mode 100644 index 00000000..1c7bc07a --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/core.js @@ -0,0 +1,593 @@ +// --------------------------------------------------------------------------------- +// Patterns for methods" parameters +// --------------------------------------------------------------------------------- + +STATE_PAT = { + changePwd: Match.Optional(String), + enrollAccount: Match.Optional(String), + forgotPwd: Match.Optional(String), + resetPwd: Match.Optional(String), + signIn: Match.Optional(String), + signUp: Match.Optional(String), + verifyEmail: Match.Optional(String), + resendVerificationEmail: Match.Optional(String), +}; + +ERRORS_PAT = { + accountsCreationDisabled: Match.Optional(String), + cannotRemoveService: Match.Optional(String), + captchaVerification: Match.Optional(String), + loginForbidden: Match.Optional(String), + mustBeLoggedIn: Match.Optional(String), + pwdMismatch: Match.Optional(String), + validationErrors: Match.Optional(String), + verifyEmailFirst: Match.Optional(String), +}; + +INFO_PAT = { + emailSent: Match.Optional(String), + emailVerified: Match.Optional(String), + pwdChanged: Match.Optional(String), + pwdReset: Match.Optional(String), + pwdSet: Match.Optional(String), + signUpVerifyEmail: Match.Optional(String), + verificationEmailSent: Match.Optional(String), +}; + +INPUT_ICONS_PAT = { + hasError: Match.Optional(String), + hasSuccess: Match.Optional(String), + isValidating: Match.Optional(String), +}; + +ObjWithStringValues = Match.Where(function (x) { + check(x, Object); + _.each(_.values(x), function(value) { + check(value, String); + }); + return true; +}); + +TEXTS_PAT = { + button: Match.Optional(STATE_PAT), + errors: Match.Optional(ERRORS_PAT), + info: Match.Optional(INFO_PAT), + inputIcons: Match.Optional(INPUT_ICONS_PAT), + maxAllowedLength: Match.Optional(String), + minRequiredLength: Match.Optional(String), + navSignIn: Match.Optional(String), + navSignOut: Match.Optional(String), + optionalField: Match.Optional(String), + pwdLink_link: Match.Optional(String), + pwdLink_pre: Match.Optional(String), + pwdLink_suff: Match.Optional(String), + requiredField: Match.Optional(String), + resendVerificationEmailLink_pre: Match.Optional(String), + resendVerificationEmailLink_link: Match.Optional(String), + resendVerificationEmailLink_suff: Match.Optional(String), + sep: Match.Optional(String), + signInLink_link: Match.Optional(String), + signInLink_pre: Match.Optional(String), + signInLink_suff: Match.Optional(String), + signUpLink_link: Match.Optional(String), + signUpLink_pre: Match.Optional(String), + signUpLink_suff: Match.Optional(String), + socialAdd: Match.Optional(String), + socialConfigure: Match.Optional(String), + socialIcons: Match.Optional(ObjWithStringValues), + socialRemove: Match.Optional(String), + socialSignIn: Match.Optional(String), + socialSignUp: Match.Optional(String), + socialWith: Match.Optional(String), + termsAnd: Match.Optional(String), + termsPreamble: Match.Optional(String), + termsPrivacy: Match.Optional(String), + termsTerms: Match.Optional(String), + title: Match.Optional(STATE_PAT), +}; + +// Configuration pattern to be checked with check +CONFIG_PAT = { + // Behaviour + confirmPassword: Match.Optional(Boolean), + defaultState: Match.Optional(String), + enablePasswordChange: Match.Optional(Boolean), + enforceEmailVerification: Match.Optional(Boolean), + focusFirstInput: Match.Optional(Boolean), + forbidClientAccountCreation: Match.Optional(Boolean), + lowercaseUsername: Match.Optional(Boolean), + overrideLoginErrors: Match.Optional(Boolean), + sendVerificationEmail: Match.Optional(Boolean), + socialLoginStyle: Match.Optional(Match.OneOf("popup", "redirect")), + + // Appearance + defaultLayout: Match.Optional(String), + hideSignInLink: Match.Optional(Boolean), + hideSignUpLink: Match.Optional(Boolean), + showAddRemoveServices: Match.Optional(Boolean), + showForgotPasswordLink: Match.Optional(Boolean), + showResendVerificationEmailLink: Match.Optional(Boolean), + showLabels: Match.Optional(Boolean), + showPlaceholders: Match.Optional(Boolean), + + // Client-side Validation + continuousValidation: Match.Optional(Boolean), + negativeFeedback: Match.Optional(Boolean), + negativeValidation: Match.Optional(Boolean), + positiveFeedback: Match.Optional(Boolean), + positiveValidation: Match.Optional(Boolean), + showValidating: Match.Optional(Boolean), + + // Privacy Policy and Terms of Use + privacyUrl: Match.Optional(String), + termsUrl: Match.Optional(String), + + // Redirects + homeRoutePath: Match.Optional(String), + redirectTimeout: Match.Optional(Number), + + // Hooks + onLogoutHook: Match.Optional(Function), + onSubmitHook: Match.Optional(Function), + preSignUpHook: Match.Optional(Function), + postSignUpHook: Match.Optional(Function), + + texts: Match.Optional(TEXTS_PAT), + + //reCaptcha config + reCaptcha: Match.Optional({ + data_type: Match.Optional(Match.OneOf("audio", "image")), + secretKey: Match.Optional(String), + siteKey: Match.Optional(String), + theme: Match.Optional(Match.OneOf("dark", "light")), + }), + + showReCaptcha: Match.Optional(Boolean), +}; + + +FIELD_SUB_PAT = { + "default": Match.Optional(String), + changePwd: Match.Optional(String), + enrollAccount: Match.Optional(String), + forgotPwd: Match.Optional(String), + resetPwd: Match.Optional(String), + signIn: Match.Optional(String), + signUp: Match.Optional(String), +}; + + +// Field pattern +FIELD_PAT = { + _id: String, + type: String, + required: Match.Optional(Boolean), + displayName: Match.Optional(Match.OneOf(String, Match.Where(_.isFunction), FIELD_SUB_PAT)), + placeholder: Match.Optional(Match.OneOf(String, FIELD_SUB_PAT)), + select: Match.Optional([{text: String, value: Match.Any}]), + minLength: Match.Optional(Match.Integer), + maxLength: Match.Optional(Match.Integer), + re: Match.Optional(RegExp), + func: Match.Optional(Match.Where(_.isFunction)), + errStr: Match.Optional(String), + + // Client-side Validation + continuousValidation: Match.Optional(Boolean), + negativeFeedback: Match.Optional(Boolean), + negativeValidation: Match.Optional(Boolean), + positiveValidation: Match.Optional(Boolean), + positiveFeedback: Match.Optional(Boolean), + + // Transforms + trim: Match.Optional(Boolean), + lowercase: Match.Optional(Boolean), + uppercase: Match.Optional(Boolean), + transform: Match.Optional(Match.Where(_.isFunction)), + + // Custom options + options: Match.Optional(Object), + template: Match.Optional(String), +}; + +// ----------------------------------------------------------------------------- +// AccountsTemplates object +// ----------------------------------------------------------------------------- + +// ------------------- +// Client/Server stuff +// ------------------- + +// Constructor +AT = function() { + +}; + +AT.prototype.CONFIG_PAT = CONFIG_PAT; + +/* + Each field object is represented by the following properties: + _id: String (required) // A unique field"s id / name + type: String (required) // Displayed input type + required: Boolean (optional) // Specifies Whether to fail or not when field is left empty + displayName: String (optional) // The field"s name to be displayed as a label above the input element + placeholder: String (optional) // The placeholder text to be displayed inside the input element + minLength: Integer (optional) // Possibly specifies the minimum allowed length + maxLength: Integer (optional) // Possibly specifies the maximum allowed length + re: RegExp (optional) // Regular expression for validation + func: Function (optional) // Custom function for validation + errStr: String (optional) // Error message to be displayed in case re validation fails +*/ + + +// Allowed input types +AT.prototype.INPUT_TYPES = [ + "checkbox", + "email", + "hidden", + "password", + "radio", + "select", + "tel", + "text", + "url", +]; + +// Current configuration values +AT.prototype.options = { + // Appearance + //defaultLayout: undefined, + showAddRemoveServices: false, + showForgotPasswordLink: false, + showResendVerificationEmailLink: false, + showLabels: true, + showPlaceholders: true, + + // Behaviour + confirmPassword: true, + defaultState: "signIn", + enablePasswordChange: false, + focusFirstInput: !Meteor.isCordova, + forbidClientAccountCreation: false, + lowercaseUsername: false, + overrideLoginErrors: true, + sendVerificationEmail: false, + socialLoginStyle: "popup", + + // Client-side Validation + //continuousValidation: false, + //negativeFeedback: false, + //negativeValidation: false, + //positiveValidation: false, + //positiveFeedback: false, + //showValidating: false, + + // Privacy Policy and Terms of Use + privacyUrl: undefined, + termsUrl: undefined, + + // Hooks + onSubmitHook: undefined, +}; + +AT.prototype.texts = { + button: { + changePwd: "updateYourPassword", + //enrollAccount: "createAccount", + enrollAccount: "signUp", + forgotPwd: "emailResetLink", + resetPwd: "setPassword", + signIn: "signIn", + signUp: "signUp", + resendVerificationEmail: "Send email again", + }, + errors: { + accountsCreationDisabled: "Client side accounts creation is disabled!!!", + cannotRemoveService: "Cannot remove the only active service!", + captchaVerification: "Captcha verification failed!", + loginForbidden: "error.accounts.Login forbidden", + mustBeLoggedIn: "error.accounts.Must be logged in", + pwdMismatch: "error.pwdsDontMatch", + validationErrors: "Validation Errors", + verifyEmailFirst: "Please verify your email first. Check the email and follow the link!", + }, + navSignIn: 'signIn', + navSignOut: 'signOut', + info: { + emailSent: "info.emailSent", + emailVerified: "info.emailVerified", + pwdChanged: "info.passwordChanged", + pwdReset: "info.passwordReset", + pwdSet: "Password Set", + signUpVerifyEmail: "Successful Registration! Please check your email and follow the instructions.", + verificationEmailSent: "A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.", + }, + inputIcons: { + isValidating: "fa fa-spinner fa-spin", + hasSuccess: "fa fa-check", + hasError: "fa fa-times", + }, + maxAllowedLength: "Maximum allowed length", + minRequiredLength: "Minimum required length", + optionalField: "optional", + pwdLink_pre: "", + pwdLink_link: "forgotPassword", + pwdLink_suff: "", + requiredField: "Required Field", + resendVerificationEmailLink_pre: "Verification email lost?", + resendVerificationEmailLink_link: "Send again", + resendVerificationEmailLink_suff: "", + sep: "OR", + signInLink_pre: "ifYouAlreadyHaveAnAccount", + signInLink_link: "signin", + signInLink_suff: "", + signUpLink_pre: "dontHaveAnAccount", + signUpLink_link: "signUp", + signUpLink_suff: "", + socialAdd: "add", + socialConfigure: "configure", + socialIcons: { + "meteor-developer": "fa fa-rocket" + }, + socialRemove: "remove", + socialSignIn: "signIn", + socialSignUp: "signUp", + socialWith: "with", + termsPreamble: "clickAgree", + termsPrivacy: "privacyPolicy", + termsAnd: "and", + termsTerms: "terms", + title: { + changePwd: "changePassword", + enrollAccount: "createAccount", + forgotPwd: "resetYourPassword", + resetPwd: "resetYourPassword", + signIn: "signIn", + signUp: "createAccount", + verifyEmail: "", + resendVerificationEmail: "Send the verification email again", + }, +}; + +AT.prototype.SPECIAL_FIELDS = [ + "password_again", + "username_and_email", +]; + +// SignIn / SignUp fields +AT.prototype._fields = [ + new Field({ + _id: "email", + type: "email", + required: true, + lowercase: true, + trim: true, + func: function(email) { + return !_.contains(email, '@'); + }, + errStr: 'Invalid email', + }), + new Field({ + _id: "password", + type: "password", + required: true, + minLength: 6, + displayName: { + "default": "password", + changePwd: "newPassword", + resetPwd: "newPassword", + }, + placeholder: { + "default": "password", + changePwd: "newPassword", + resetPwd: "newPassword", + }, + }), +]; + + +AT.prototype._initialized = false; + +// Input type validation +AT.prototype._isValidInputType = function(value) { + return _.indexOf(this.INPUT_TYPES, value) !== -1; +}; + +AT.prototype.addField = function(field) { + // Fields can be added only before initialization + if (this._initialized) { + throw new Error("AccountsTemplates.addField should strictly be called before AccountsTemplates.init!"); + } + + field = _.pick(field, _.keys(FIELD_PAT)); + check(field, FIELD_PAT); + // Checks there"s currently no field called field._id + if (_.indexOf(_.pluck(this._fields, "_id"), field._id) !== -1) { + throw new Error("A field called " + field._id + " already exists!"); + } + // Validates field.type + if (!this._isValidInputType(field.type)) { + throw new Error("field.type is not valid!"); + } + // Checks field.minLength is strictly positive + if (typeof field.minLength !== "undefined" && field.minLength <= 0) { + throw new Error("field.minLength should be greater than zero!"); + } + // Checks field.maxLength is strictly positive + if (typeof field.maxLength !== "undefined" && field.maxLength <= 0) { + throw new Error("field.maxLength should be greater than zero!"); + } + // Checks field.maxLength is greater than field.minLength + if (typeof field.minLength !== "undefined" && typeof field.minLength !== "undefined" && field.maxLength < field.minLength) { + throw new Error("field.maxLength should be greater than field.maxLength!"); + } + + if (!(Meteor.isServer && _.contains(this.SPECIAL_FIELDS, field._id))) { + this._fields.push(new Field(field)); + } + + return this._fields; +}; + +AT.prototype.addFields = function(fields) { + var ok; + + try { // don"t bother with `typeof` - just access `length` and `catch` + ok = fields.length > 0 && "0" in Object(fields); + } catch (e) { + throw new Error("field argument should be an array of valid field objects!"); + } + if (ok) { + _.map(fields, function(field) { + this.addField(field); + }, this); + } else { + throw new Error("field argument should be an array of valid field objects!"); + } + + return this._fields; +}; + +AT.prototype.configure = function(config) { + // Configuration options can be set only before initialization + if (this._initialized) { + throw new Error("Configuration options must be set before AccountsTemplates.init!"); + } + + // Updates the current configuration + check(config, CONFIG_PAT); + var options = _.omit(config, "texts", "reCaptcha"); + this.options = _.defaults(options, this.options); + + // Possibly sets up reCaptcha options + var reCaptcha = config.reCaptcha; + if (reCaptcha) { + // Updates the current button object + this.options.reCaptcha = _.defaults(reCaptcha, this.options.reCaptcha || {}); + } + + // Possibly sets up texts... + if (config.texts) { + var texts = config.texts; + var simpleTexts = _.omit(texts, "button", "errors", "info", "inputIcons", "socialIcons", "title"); + + this.texts = _.defaults(simpleTexts, this.texts); + + if (texts.button) { + // Updates the current button object + this.texts.button = _.defaults(texts.button, this.texts.button); + } + + if (texts.errors) { + // Updates the current errors object + this.texts.errors = _.defaults(texts.errors, this.texts.errors); + } + + if (texts.info) { + // Updates the current info object + this.texts.info = _.defaults(texts.info, this.texts.info); + } + + if (texts.inputIcons) { + // Updates the current inputIcons object + this.texts.inputIcons = _.defaults(texts.inputIcons, this.texts.inputIcons); + } + + if (texts.socialIcons) { + // Updates the current socialIcons object + this.texts.socialIcons = _.defaults(texts.socialIcons, this.texts.socialIcons); + } + + if (texts.title) { + // Updates the current title object + this.texts.title = _.defaults(texts.title, this.texts.title); + } + } +}; + + +AT.prototype.configureRoute = function(route, options) { + console.warn('You now need a routing package like useraccounts:iron-routing or useraccounts:flow-routing to be able to configure routes!'); +}; + + +AT.prototype.hasField = function(fieldId) { + return !!this.getField(fieldId); +}; + +AT.prototype.getField = function(fieldId) { + var field = _.filter(this._fields, function(field) { + return field._id === fieldId; + }); + + return (field.length === 1) ? field[0] : undefined; +}; + +AT.prototype.getFields = function() { + return this._fields; +}; + +AT.prototype.getFieldIds = function() { + return _.pluck(this._fields, "_id"); +}; + +AT.prototype.getRoutePath = function(route) { + return "#"; +}; + +AT.prototype.oauthServices = function() { + // Extracts names of available services + var names; + + if (Meteor.isServer) { + names = (Accounts.oauth && Accounts.oauth.serviceNames()) || []; + } else { + names = (Accounts.oauth && Accounts.loginServicesConfigured() && Accounts.oauth.serviceNames()) || []; + } + // Extracts names of configured services + var configuredServices = []; + + if (Accounts.loginServiceConfiguration) { + configuredServices = _.pluck(Accounts.loginServiceConfiguration.find().fetch(), "service"); + } + + // Builds a list of objects containing service name as _id and its configuration status + var services = _.map(names, function(name) { + return { + _id : name, + configured: _.contains(configuredServices, name), + }; + }); + + // Checks whether there is a UI to configure services... + // XXX: this only works with the accounts-ui package + var showUnconfigured = typeof Accounts._loginButtonsSession !== "undefined"; + + // Filters out unconfigured services in case they"re not to be displayed + if (!showUnconfigured) { + services = _.filter(services, function(service) { + return service.configured; + }); + } + + // Sorts services by name + services = _.sortBy(services, function(service) { + return service._id; + }); + + return services; +}; + +AT.prototype.removeField = function(fieldId) { + // Fields can be removed only before initialization + if (this._initialized) { + throw new Error("AccountsTemplates.removeField should strictly be called before AccountsTemplates.init!"); + } + // Tries to look up the field with given _id + var index = _.indexOf(_.pluck(this._fields, "_id"), fieldId); + + if (index !== -1) { + return this._fields.splice(index, 1)[0]; + } else if (!(Meteor.isServer && _.contains(this.SPECIAL_FIELDS, fieldId))) { + throw new Error("A field called " + fieldId + " does not exist!"); + } +}; diff --git a/packages/meteor-useraccounts-core/lib/field.js b/packages/meteor-useraccounts-core/lib/field.js new file mode 100644 index 00000000..c3ecfbb9 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/field.js @@ -0,0 +1,292 @@ +// --------------------------------------------------------------------------------- +// Field object +// --------------------------------------------------------------------------------- + +Field = function(field) { + check(field, FIELD_PAT); + _.defaults(this, field); + + this.validating = new ReactiveVar(false); + this.status = new ReactiveVar(null); +}; + +if (Meteor.isClient) { + Field.prototype.clearStatus = function() { + return this.status.set(null); + }; +} + +if (Meteor.isServer) { + Field.prototype.clearStatus = function() { + // Nothing to do server-side + return; + }; +} + +Field.prototype.fixValue = function(value) { + if (this.type === "checkbox") { + return !!value; + } + + if (this.type === "select") { + // TODO: something working... + return value; + } + + if (this.type === "radio") { + // TODO: something working... + return value; + } + + // Possibly applies required transformations to the input value + if (this.trim) { + value = value.trim(); + } + + if (this.lowercase) { + value = value.toLowerCase(); + } + + if (this.uppercase) { + value = value.toUpperCase(); + } + + if (!!this.transform) { + value = this.transform(value); + } + + return value; +}; + +if (Meteor.isClient) { + Field.prototype.getDisplayName = function(state) { + var displayName = this.displayName; + + if (_.isFunction(displayName)) { + displayName = displayName(); + } else if (_.isObject(displayName)) { + displayName = displayName[state] || displayName["default"]; + } + + if (!displayName) { + displayName = capitalize(this._id); + } + + return displayName; + }; +} + +if (Meteor.isClient) { + Field.prototype.getPlaceholder = function(state) { + var placeholder = this.placeholder; + + if (_.isObject(placeholder)) { + placeholder = placeholder[state] || placeholder["default"]; + } + + if (!placeholder) { + placeholder = capitalize(this._id); + } + + return placeholder; + }; +} + +Field.prototype.getStatus = function() { + return this.status.get(); +}; + +if (Meteor.isClient) { + Field.prototype.getValue = function(templateInstance) { + if (this.type === "checkbox") { + return !!(templateInstance.$("#at-field-" + this._id + ":checked").val()); + } + + if (this.type === "radio") { + return templateInstance.$("[name=at-field-"+ this._id + "]:checked").val(); + } + + return templateInstance.$("#at-field-" + this._id).val(); + }; +} + +if (Meteor.isClient) { + Field.prototype.hasError = function() { + return this.negativeValidation && this.status.get(); + }; +} + +if (Meteor.isClient) { + Field.prototype.hasIcon = function() { + if (this.showValidating && this.isValidating()) { + return true; + } + + if (this.negativeFeedback && this.hasError()) { + return true; + } + + if (this.positiveFeedback && this.hasSuccess()) { + return true; + } + }; +} + +if (Meteor.isClient) { + Field.prototype.hasSuccess = function() { + return this.positiveValidation && this.status.get() === false; + }; +} + +if (Meteor.isClient) + Field.prototype.iconClass = function() { + if (this.isValidating()) { + return AccountsTemplates.texts.inputIcons["isValidating"]; + } + + if (this.hasError()) { + return AccountsTemplates.texts.inputIcons["hasError"]; + } + + if (this.hasSuccess()) { + return AccountsTemplates.texts.inputIcons["hasSuccess"]; + } + }; + +if (Meteor.isClient) { + Field.prototype.isValidating = function() { + return this.validating.get(); + }; +} + +if (Meteor.isClient) { + Field.prototype.setError = function(err) { + check(err, Match.OneOf(String, undefined, Boolean)); + + if (err === false) { + return this.status.set(false); + } + + return this.status.set(err || true); + }; +} + +if (Meteor.isServer) { + Field.prototype.setError = function(err) { + // Nothing to do server-side + return; + }; +} + +if (Meteor.isClient) { + Field.prototype.setSuccess = function() { + return this.status.set(false); + }; +} + +if (Meteor.isServer) { + Field.prototype.setSuccess = function() { + // Nothing to do server-side + return; + }; +} + +if (Meteor.isClient) { + Field.prototype.setValidating = function(state) { + check(state, Boolean); + return this.validating.set(state); + }; +} + +if (Meteor.isServer) { + Field.prototype.setValidating = function(state) { + // Nothing to do server-side + return; + }; +} + +if (Meteor.isClient) { + Field.prototype.setValue = function(templateInstance, value) { + if (this.type === "checkbox") { + templateInstance.$("#at-field-" + this._id).prop('checked', true); + return; + } + + if (this.type === "radio") { + templateInstance.$("[name=at-field-"+ this._id + "]").prop('checked', true); + return; + } + + templateInstance.$("#at-field-" + this._id).val(value); + }; +} + +Field.prototype.validate = function(value, strict) { + check(value, Match.OneOf(undefined, String, Boolean)); + this.setValidating(true); + this.clearStatus(); + + if (_.isUndefined(value) || value === '') { + if (!!strict) { + if (this.required) { + this.setError(AccountsTemplates.texts.requiredField); + this.setValidating(false); + + return AccountsTemplates.texts.requiredField; + } else { + this.setSuccess(); + this.setValidating(false); + + return false; + } + } else { + this.clearStatus(); + this.setValidating(false); + + return null; + } + } + + var valueLength = value.length; + var minLength = this.minLength; + if (minLength && valueLength < minLength) { + this.setError(AccountsTemplates.texts.minRequiredLength + ": " + minLength); + this.setValidating(false); + + return AccountsTemplates.texts.minRequiredLength + ": " + minLength; + } + + var maxLength = this.maxLength; + if (maxLength && valueLength > maxLength) { + this.setError(AccountsTemplates.texts.maxAllowedLength + ": " + maxLength); + this.setValidating(false); + + return AccountsTemplates.texts.maxAllowedLength + ": " + maxLength; + } + + if (this.re && valueLength && !value.match(this.re)) { + this.setError(this.errStr); + this.setValidating(false); + + return this.errStr; + } + + if (this.func) { + var result = this.func(value); + var err = result === true ? this.errStr || true : result; + + if (_.isUndefined(result)) { + return err; + } + + this.status.set(err); + this.setValidating(false); + + return err; + } + + this.setSuccess(); + this.setValidating(false); + + return false; +}; diff --git a/packages/meteor-useraccounts-core/lib/methods.js b/packages/meteor-useraccounts-core/lib/methods.js new file mode 100644 index 00000000..0d3a070d --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/methods.js @@ -0,0 +1,25 @@ +/* global + AccountsTemplates: false +*/ +"use strict"; + +Meteor.methods({ + ATRemoveService: function(serviceName) { + check(serviceName, String); + + var userId = this.userId; + + if (userId) { + var user = Meteor.users.findOne(userId); + var numServices = _.keys(user.services).length; // including "resume" + var unset = {}; + + if (numServices === 2) { + throw new Meteor.Error(403, AccountsTemplates.texts.errors.cannotRemoveService, {}); + } + + unset["services." + serviceName] = ""; + Meteor.users.update(userId, {$unset: unset}); + } + }, +}); diff --git a/packages/meteor-useraccounts-core/lib/server.js b/packages/meteor-useraccounts-core/lib/server.js new file mode 100644 index 00000000..2a925dc7 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/server.js @@ -0,0 +1,184 @@ +/* global + AT: false, + AccountsTemplates: false +*/ +"use strict"; + +// Initialization +AT.prototype.init = function() { + console.warn("[AccountsTemplates] There is no more need to call AccountsTemplates.init()! Simply remove the call ;-)"); +}; + +AT.prototype._init = function() { + if (this._initialized) { + return; + } + + // Checks there is at least one account service installed + if (!Package["accounts-password"] && (!Accounts.oauth || Accounts.oauth.serviceNames().length === 0)) { + throw Error("AccountsTemplates: You must add at least one account service!"); + } + + // A password field is strictly required + var password = this.getField("password"); + if (!password) { + throw Error("A password field is strictly required!"); + } + + if (password.type !== "password") { + throw Error("The type of password field should be password!"); + } + + // Then we can have "username" or "email" or even both of them + // but at least one of the two is strictly required + var username = this.getField("username"); + var email = this.getField("email"); + + if (!username && !email) { + throw Error("At least one field out of username and email is strictly required!"); + } + + if (username && !username.required) { + throw Error("The username field should be required!"); + } + + if (email) { + if (email.type !== "email") { + throw Error("The type of email field should be email!"); + } + + if (username) { + // username and email + if (username.type !== "text") { + throw Error("The type of username field should be text when email field is present!"); + } + } else { + // email only + if (!email.required) { + throw Error("The email field should be required when username is not present!"); + } + } + } else { + // username only + if (username.type !== "text" && username.type !== "tel") { + throw Error("The type of username field should be text or tel!"); + } + } + + // Possibly publish more user data in order to be able to show add/remove + // buttons for 3rd-party services + if (this.options.showAddRemoveServices) { + // Publish additional current user info to get the list of registered services + // XXX TODO: use + // Accounts.addAutopublishFields({ + // forLoggedInUser: ['services.facebook'], + // forOtherUsers: [], + // }) + // ...adds only user.services.*.id + Meteor.publish("userRegisteredServices", function() { + var userId = this.userId; + return Meteor.users.find(userId, {fields: {services: 1}}); + /* + if (userId) { + var user = Meteor.users.findOne(userId); + var services_id = _.chain(user.services) + .keys() + .reject(function(service) {return service === "resume";}) + .map(function(service) {return "services." + service + ".id";}) + .value(); + var projection = {}; + _.each(services_id, function(key) {projection[key] = 1;}); + return Meteor.users.find(userId, {fields: projection}); + } + */ + }); + } + + // Security stuff + if (this.options.overrideLoginErrors) { + Accounts.validateLoginAttempt(function(attempt) { + if (attempt.error) { + var reason = attempt.error.reason; + if (reason === "User not found" || reason === "Incorrect password") { + throw new Meteor.Error(403, AccountsTemplates.texts.errors.loginForbidden); + } + } + return attempt.allowed; + }); + } + + if (this.options.sendVerificationEmail && this.options.enforceEmailVerification) { + Accounts.validateLoginAttempt(function(attempt) { + if (!attempt.allowed) { + return false; + } + + if (attempt.type !== "password" || attempt.methodName !== "login") { + return attempt.allowed; + } + + var user = attempt.user; + if (!user) { + return attempt.allowed; + } + + var ok = true; + var loginEmail = attempt.methodArguments[0].user.email.toLowerCase(); + if (loginEmail) { + var email = _.filter(user.emails, function(obj) { + return obj.address.toLowerCase() === loginEmail; + }); + if (!email.length || !email[0].verified) { + ok = false; + } + } else { + // we got the username, lets check there's at lease one verified email + var emailVerified = _.chain(user.emails) + .pluck('verified') + .any() + .value(); + + if (!emailVerified) { + ok = false; + } + } + if (!ok) { + throw new Meteor.Error(401, AccountsTemplates.texts.errors.verifyEmailFirst); + } + + return attempt.allowed; + }); + } + + //Check that reCaptcha secret keys are available + if (this.options.showReCaptcha) { + var atSecretKey = AccountsTemplates.options.reCaptcha && AccountsTemplates.options.reCaptcha.secretKey; + var settingsSecretKey = Meteor.settings.reCaptcha && Meteor.settings.reCaptcha.secretKey; + + if (!atSecretKey && !settingsSecretKey) { + throw new Meteor.Error(401, "User Accounts: reCaptcha secret key not found! Please provide it or set showReCaptcha to false." ); + } + } + + // Marks AccountsTemplates as initialized + this._initialized = true; +}; + +AccountsTemplates = new AT(); + +// Client side account creation is disabled by default: +// the methos ATCreateUserServer is used instead! +// to actually disable client side account creation use: +// +// AccountsTemplates.config({ +// forbidClientAccountCreation: true +// }); + +Accounts.config({ + forbidClientAccountCreation: true +}); + +// Initialization +Meteor.startup(function() { + AccountsTemplates._init(); +}); diff --git a/packages/meteor-useraccounts-core/lib/server_methods.js b/packages/meteor-useraccounts-core/lib/server_methods.js new file mode 100644 index 00000000..500440d7 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/server_methods.js @@ -0,0 +1,142 @@ +/* global + AccountsTemplates +*/ +"use strict"; + +Meteor.methods({ + ATCreateUserServer: function(options) { + if (AccountsTemplates.options.forbidClientAccountCreation) { + throw new Meteor.Error(403, AccountsTemplates.texts.errors.accountsCreationDisabled); + } + + // createUser() does more checking. + check(options, Object); + var allFieldIds = AccountsTemplates.getFieldIds(); + + // Picks-up whitelisted fields for profile + var profile = options.profile; + profile = _.pick(profile, allFieldIds); + profile = _.omit(profile, "username", "email", "password"); + + // Validates fields" value + var signupInfo = _.clone(profile); + if (options.username) { + signupInfo.username = options.username; + + if (AccountsTemplates.options.lowercaseUsername) { + signupInfo.username = signupInfo.username.trim().replace(/\s+/gm, ' '); + options.profile.name = signupInfo.username; + signupInfo.username = signupInfo.username.toLowerCase().replace(/\s+/gm, ''); + options.username = signupInfo.username; + } + } + + if (options.email) { + signupInfo.email = options.email; + + if (AccountsTemplates.options.lowercaseUsername) { + signupInfo.email = signupInfo.email.toLowerCase().replace(/\s+/gm, ''); + options.email = signupInfo.email; + } + } + + if (options.password) { + signupInfo.password = options.password; + } + + var validationErrors = {}; + var someError = false; + + // Validates fields values + _.each(AccountsTemplates.getFields(), function(field) { + var fieldId = field._id; + var value = signupInfo[fieldId]; + + if (fieldId === "password") { + // Can"t Pick-up password here + // NOTE: at this stage the password is already encripted, + // so there is no way to validate it!!! + check(value, Object); + return; + } + + var validationErr = field.validate(value, "strict"); + if (validationErr) { + validationErrors[fieldId] = validationErr; + someError = true; + } + }); + + if (AccountsTemplates.options.showReCaptcha) { + var secretKey = null; + + if (AccountsTemplates.options.reCaptcha && AccountsTemplates.options.reCaptcha.secretKey) { + secretKey = AccountsTemplates.options.reCaptcha.secretKey; + } else { + secretKey = Meteor.settings.reCaptcha.secretKey; + } + + var apiResponse = HTTP.post("https://www.google.com/recaptcha/api/siteverify", { + params: { + secret: secretKey, + response: options.profile.reCaptchaResponse, + remoteip: this.connection.clientAddress, + } + }).data; + + if (!apiResponse.success) { + throw new Meteor.Error(403, AccountsTemplates.texts.errors.captchaVerification, + apiResponse['error-codes'] ? apiResponse['error-codes'].join(", ") : "Unknown Error."); + } + } + + if (someError) { + throw new Meteor.Error(403, AccountsTemplates.texts.errors.validationErrors, validationErrors); + } + + // Possibly removes the profile field + if (_.isEmpty(options.profile)) { + delete options.profile; + } + + // Create user. result contains id and token. + var userId = Accounts.createUser(options); + // safety belt. createUser is supposed to throw on error. send 500 error + // instead of sending a verification email with empty userid. + if (! userId) { + throw new Error("createUser failed to insert new user"); + } + + // Call postSignUpHook, if any... + var postSignUpHook = AccountsTemplates.options.postSignUpHook; + if (postSignUpHook) { + postSignUpHook(userId, options); + } + + // Send a email address verification email in case the context permits it + // and the specific configuration flag was set to true + if (options.email && AccountsTemplates.options.sendVerificationEmail) { + Accounts.sendVerificationEmail(userId, options.email); + } + }, + + // Resend a user's verification e-mail + ATResendVerificationEmail: function (email) { + check(email, String); + + var user = Meteor.users.findOne({ "emails.address": email }); + + // Send the standard error back to the client if no user exist with this e-mail + if (!user) { + throw new Meteor.Error(403, "User not found"); + } + + try { + Accounts.sendVerificationEmail(user._id); + } catch (error) { + // Handle error when email already verified + // https://github.com/dwinston/send-verification-email-bug + throw new Meteor.Error(403, "Already verified"); + } + }, +}); diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_error.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_error.js new file mode 100644 index 00000000..5673dfe7 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_error.js @@ -0,0 +1,26 @@ +AT.prototype.atErrorHelpers = { + singleError: function() { + var errors = AccountsTemplates.state.form.get("error"); + return errors && errors.length === 1; + }, + error: function() { + return AccountsTemplates.state.form.get("error"); + }, + errorText: function(){ + var field, err; + if (this.field){ + field = T9n.get(this.field, markIfMissing=false); + err = T9n.get(this.err, markIfMissing=false); + } + else + err = T9n.get(this.valueOf(), markIfMissing=false); + + // Possibly removes initial prefix in case the key in not found inside t9n + if (err.substring(0, 15) === "error.accounts.") + err = err.substring(15); + + if (field) + return field + ": " + err; + return err; + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_form.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_form.js new file mode 100644 index 00000000..95a34c0c --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_form.js @@ -0,0 +1,83 @@ +AT.prototype.atFormHelpers = { + hide: function(){ + var state = this.state || AccountsTemplates.getState(); + return state === "hide"; + }, + showTitle: function(next_state){ + var state = next_state || this.state || AccountsTemplates.getState(); + if (Meteor.userId() && state === "signIn") + return false; + return !!AccountsTemplates.texts.title[state]; + }, + showOauthServices: function(next_state){ + var state = next_state || this.state || AccountsTemplates.getState(); + if (!(state === "signIn" || state === "signUp")) + return false; + var services = AccountsTemplates.oauthServices(); + if (!services.length) + return false; + if (Meteor.userId()) + return AccountsTemplates.options.showAddRemoveServices; + return true; + }, + showServicesSeparator: function(next_state){ + var pwdService = Package["accounts-password"] !== undefined; + var state = next_state || this.state || AccountsTemplates.getState(); + var rightState = (state === "signIn" || state === "signUp"); + return rightState && !Meteor.userId() && pwdService && AccountsTemplates.oauthServices().length; + }, + showError: function(next_state) { + return !!AccountsTemplates.state.form.get("error"); + }, + showResult: function(next_state) { + return !!AccountsTemplates.state.form.get("result"); + }, + showMessage: function(next_state) { + return !!AccountsTemplates.state.form.get("message"); + }, + showPwdForm: function(next_state) { + if (Package["accounts-password"] === undefined) + return false; + var state = next_state || this.state || AccountsTemplates.getState(); + if ((state === "verifyEmail") || (state === "signIn" && Meteor.userId())) + return false; + return true; + }, + showSignInLink: function(next_state){ + if (AccountsTemplates.options.hideSignInLink) + return false; + var state = next_state || this.state || AccountsTemplates.getState(); + if (AccountsTemplates.options.forbidClientAccountCreation && state === "forgotPwd") + return true; + return state === "signUp"; + }, + showSignUpLink: function(next_state){ + if (AccountsTemplates.options.hideSignUpLink) + return false; + var state = next_state || this.state || AccountsTemplates.getState(); + return ((state === "signIn" && !Meteor.userId()) || state === "forgotPwd") && !AccountsTemplates.options.forbidClientAccountCreation; + }, + showTermsLink: function(next_state){ + //TODO: Add privacyRoute and termsRoute as alternatives (the point of named routes is + // being able to change the url in one place only) + if (!!AccountsTemplates.options.privacyUrl || !!AccountsTemplates.options.termsUrl) { + var state = next_state || this.state || AccountsTemplates.getState(); + if (state === "signUp" || state === "enrollAccount" ) { + return true; + } + } + /* + if (state === "signIn"){ + var pwdService = Package["accounts-password"] !== undefined; + if (!pwdService) + return true; + } + */ + return false; + }, + showResendVerificationEmailLink: function(){ + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + return (state === "signIn" || state === "forgotPwd") && AccountsTemplates.options.showResendVerificationEmailLink; + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_input.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_input.js new file mode 100644 index 00000000..fe74eeb1 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_input.js @@ -0,0 +1,124 @@ +AT.prototype.atInputRendered = [function(){ + var fieldId = this.data._id; + + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + + if (AccountsTemplates.options.focusFirstInput) { + var firstVisibleInput = _.find(AccountsTemplates.getFields(), function(f){ + return _.contains(f.visible, state); + }); + + if (firstVisibleInput && firstVisibleInput._id === fieldId) { + this.$("input#at-field-" + fieldId).focus(); + } + } +}]; + +AT.prototype.atInputHelpers = { + disabled: function() { + return AccountsTemplates.disabled(); + }, + showLabels: function() { + return AccountsTemplates.options.showLabels; + }, + displayName: function() { + var parentData = Template.parentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + var displayName = this.getDisplayName(state); + return T9n.get(displayName, markIfMissing=false); + }, + optionalText: function(){ + return "(" + T9n.get(AccountsTemplates.texts.optionalField, markIfMissing=false) + ")"; + }, + templateName: function() { + if (this.template) + return this.template; + if (this.type === "checkbox") + return "atCheckboxInput"; + if (this.type === "select") + return "atSelectInput"; + if (this.type === "radio") + return "atRadioInput"; + if (this.type === "hidden") + return "atHiddenInput"; + return "atTextInput"; + }, + values: function(){ + var id = this._id; + return _.map(this.select, function(select){ + var s = _.clone(select); + s._id = id + "-" + select.value; + s.id = id; + return s; + }); + }, + errorText: function() { + var err = this.getStatus(); + return T9n.get(err, markIfMissing=false); + }, + placeholder: function() { + if (AccountsTemplates.options.showPlaceholders) { + var parentData = Template.parentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + var placeholder = this.getPlaceholder(state); + return T9n.get(placeholder, markIfMissing=false); + } + }, +}; + +AT.prototype.atInputEvents = { + "focusin input": function(event, t){ + var field = Template.currentData(); + field.clearStatus(); + }, + "focusout input, change select": function(event, t){ + var field = Template.currentData(); + var fieldId = field._id; + var rawValue = field.getValue(t); + var value = field.fixValue(rawValue); + // Possibly updates the input value + if (value !== rawValue) { + field.setValue(t, value); + } + + // Client-side only validation + if (!field.validation) + return; + var parentData = Template.parentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + // No validation during signIn + if (state === "signIn") + return; + // Special case for password confirmation + if (value && fieldId === "password_again"){ + if (value !== $("#at-field-password").val()) + return field.setError(AccountsTemplates.texts.errors.pwdMismatch); + } + field.validate(value); + }, + "keyup input": function(event, t){ + var field = Template.currentData(); + // Client-side only continuous validation + if (!field.continuousValidation) + return; + var parentData = Template.parentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + // No validation during signIn + if (state === "signIn") + return; + var fieldId = field._id; + var rawValue = field.getValue(t); + var value = field.fixValue(rawValue); + // Possibly updates the input value + if (value !== rawValue) { + field.setValue(t, value); + } + // Special case for password confirmation + if (value && fieldId === "password_again"){ + if (value !== $("#at-field-password").val()) + return field.setError(AccountsTemplates.texts.errors.pwdMismatch); + } + field.validate(value); + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_message.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_message.js new file mode 100644 index 00000000..baa9ca04 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_message.js @@ -0,0 +1,7 @@ +AT.prototype.atMessageHelpers = { + message: function() { + var messageText = AccountsTemplates.state.form.get("message"); + if (messageText) + return T9n.get(messageText, markIfMissing=false); + }, +}; \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_nav_button.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_nav_button.js new file mode 100644 index 00000000..c434060d --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_nav_button.js @@ -0,0 +1,16 @@ +AT.prototype.atNavButtonHelpers = { + text: function(){ + var key = Meteor.userId() ? AccountsTemplates.texts.navSignOut : AccountsTemplates.texts.navSignIn; + return T9n.get(key, markIfMissing=false); + } +}; + +AT.prototype.atNavButtonEvents = { + 'click #at-nav-button': function(event){ + event.preventDefault(); + if (Meteor.userId()) + AccountsTemplates.logout(); + else + AccountsTemplates.linkClick("signIn"); + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_oauth.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_oauth.js new file mode 100644 index 00000000..1b1d13c1 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_oauth.js @@ -0,0 +1,5 @@ +AT.prototype.atOauthHelpers = { + oauthService: function() { + return AccountsTemplates.oauthServices(); + }, +}; \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form.js new file mode 100644 index 00000000..2f8d53c4 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form.js @@ -0,0 +1,331 @@ +AT.prototype.atPwdFormHelpers = { + disabled: function() { + return AccountsTemplates.disabled(); + }, + fields: function() { + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + return _.filter(AccountsTemplates.getFields(), function(s) { + return _.contains(s.visible, state); + }); + }, + showForgotPasswordLink: function() { + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + return state === "signIn" && AccountsTemplates.options.showForgotPasswordLink; + }, + showReCaptcha: function() { + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + return state === "signUp" && AccountsTemplates.options.showReCaptcha; + }, +}; + + +var toLowercaseUsername = function(value){ + return value.toLowerCase().replace(/\s+/gm, ''); +}; + +AT.prototype.atPwdFormEvents = { + // Form submit + "submit #at-pwd-form": function(event, t) { + event.preventDefault(); + t.$("#at-btn").blur(); + + AccountsTemplates.setDisabled(true); + + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + var preValidation = (state !== "signIn"); + + // Client-side pre-validation + // Validates fields values + // NOTE: This is the only place where password validation can be enforced! + var formData = {}; + var someError = false; + var errList = []; + _.each(AccountsTemplates.getFields(), function(field){ + // Considers only visible fields... + if (!_.contains(field.visible, state)) + return; + + var fieldId = field._id; + + var rawValue = field.getValue(t); + var value = field.fixValue(rawValue); + // Possibly updates the input value + if (value !== rawValue) { + field.setValue(t, value); + } + if (value !== undefined && value !== "") { + formData[fieldId] = value; + } + + // Validates the field value only if current state is not "signIn" + if (preValidation && field.getStatus() !== false){ + var validationErr = field.validate(value, "strict"); + if (validationErr) { + if (field.negativeValidation) + field.setError(validationErr); + else{ + var fId = T9n.get(field.getDisplayName(), markIfMissing=false); + //errList.push(fId + ": " + err); + errList.push({ + field: field.getDisplayName(), + err: validationErr + }); + } + someError = true; + } + else + field.setSuccess(); + } + }); + + // Clears error and result + AccountsTemplates.clearError(); + AccountsTemplates.clearResult(); + AccountsTemplates.clearMessage(); + // Possibly sets errors + if (someError){ + if (errList.length) + AccountsTemplates.state.form.set("error", errList); + AccountsTemplates.setDisabled(false); + //reset reCaptcha form + if (state === "signUp" && AccountsTemplates.options.showReCaptcha) { + grecaptcha.reset(); + } + return; + } + + // Extracts username, email, and pwds + var current_password = formData.current_password; + var email = formData.email; + var password = formData.password; + var password_again = formData.password_again; + var username = formData.username; + var username_and_email = formData.username_and_email; + // Clears profile data removing username, email, and pwd + delete formData.current_password; + delete formData.email; + delete formData.password; + delete formData.password_again; + delete formData.username; + delete formData.username_and_email; + + if (AccountsTemplates.options.confirmPassword){ + // Checks passwords for correct match + if (password_again && password !== password_again){ + var pwd_again = AccountsTemplates.getField("password_again"); + if (pwd_again.negativeValidation) + pwd_again.setError(AccountsTemplates.texts.errors.pwdMismatch); + else + AccountsTemplates.state.form.set("error", [{ + field: pwd_again.getDisplayName(), + err: AccountsTemplates.texts.errors.pwdMismatch + }]); + AccountsTemplates.setDisabled(false); + //reset reCaptcha form + if (state === "signUp" && AccountsTemplates.options.showReCaptcha) { + grecaptcha.reset(); + } + return; + } + } + + // ------- + // Sign In + // ------- + if (state === "signIn") { + var pwdOk = !!password; + var userOk = true; + var loginSelector; + if (email) { + if (AccountsTemplates.options.lowercaseUsername) { + email = toLowercaseUsername(email); + } + + loginSelector = {email: email}; + } + else if (username) { + if (AccountsTemplates.options.lowercaseUsername) { + username = toLowercaseUsername(username); + } + loginSelector = {username: username}; + } + else if (username_and_email) { + if (AccountsTemplates.options.lowercaseUsername) { + username_and_email = toLowercaseUsername(username_and_email); + } + loginSelector = username_and_email; + } + else + userOk = false; + + // Possibly exits if not both 'password' and 'username' are non-empty... + if (!pwdOk || !userOk){ + AccountsTemplates.state.form.set("error", [AccountsTemplates.texts.errors.loginForbidden]); + AccountsTemplates.setDisabled(false); + return; + } + + + return Meteor.loginWithPassword(loginSelector, password, function(error) { + AccountsTemplates.submitCallback(error, state); + }); + } + + // ------- + // Sign Up + // ------- + if (state === "signUp") { + // Possibly gets reCaptcha response + if (AccountsTemplates.options.showReCaptcha) { + var response = grecaptcha.getResponse(); + if (response === "") { + // recaptcha verification has not completed yet (or has expired)... + // ...simply ignore submit event! + AccountsTemplates.setDisabled(false); + return; + } else { + formData.reCaptchaResponse = response; + } + } + + var hash = Accounts._hashPassword(password); + var options = { + username: username, + email: email, + password: hash, + profile: formData, + }; + + // Call preSignUpHook, if any... + var preSignUpHook = AccountsTemplates.options.preSignUpHook; + if (preSignUpHook) { + preSignUpHook(password, options); + } + + return Meteor.call("ATCreateUserServer", options, function(error){ + if (error && error.reason === 'Email already exists.') { + if (AccountsTemplates.options.showReCaptcha) { + grecaptcha.reset(); + } + } + AccountsTemplates.submitCallback(error, undefined, function(){ + if (AccountsTemplates.options.sendVerificationEmail && AccountsTemplates.options.enforceEmailVerification){ + AccountsTemplates.submitCallback(error, state, function () { + AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.signUpVerifyEmail); + // Cleans up input fields' content + _.each(AccountsTemplates.getFields(), function(field){ + // Considers only visible fields... + if (!_.contains(field.visible, state)) + return; + + var elem = t.$("#at-field-" + field._id); + + // Naïve reset + if (field.type === "checkbox") elem.prop('checked', false); + else elem.val(""); + + }); + AccountsTemplates.setDisabled(false); + AccountsTemplates.avoidRedirect = true; + }); + } + else { + var loginSelector; + + if (email) { + if (AccountsTemplates.options.lowercaseUsername) { + email = toLowercaseUsername(email); + } + + loginSelector = {email: email}; + } + else if (username) { + if (AccountsTemplates.options.lowercaseUsername) { + username = toLowercaseUsername(username); + } + loginSelector = {username: username}; + } + else { + if (AccountsTemplates.options.lowercaseUsername) { + username_and_email = toLowercaseUsername(username_and_email); + } + loginSelector = username_and_email; + } + + Meteor.loginWithPassword(loginSelector, password, function(error) { + AccountsTemplates.submitCallback(error, state, function(){ + AccountsTemplates.setState("signIn"); + }); + }); + } + }); + }); + } + + //---------------- + // Forgot Password + //---------------- + if (state === "forgotPwd"){ + return Accounts.forgotPassword({ + email: email + }, function(error) { + AccountsTemplates.submitCallback(error, state, function(){ + AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.emailSent); + t.$("#at-field-email").val(""); + }); + }); + } + + //-------------------------------- + // Reset Password / Enroll Account + //-------------------------------- + if (state === "resetPwd" || state === "enrollAccount") { + var paramToken = AccountsTemplates.getparamToken(); + return Accounts.resetPassword(paramToken, password, function(error) { + AccountsTemplates.submitCallback(error, state, function(){ + var pwd_field_id; + if (state === "resetPwd") + AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.pwdReset); + else // Enroll Account + AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.pwdSet); + t.$("#at-field-password").val(""); + if (AccountsTemplates.options.confirmPassword) + t.$("#at-field-password_again").val(""); + }); + }); + } + + //---------------- + // Change Password + //---------------- + if (state === "changePwd"){ + return Accounts.changePassword(current_password, password, function(error) { + AccountsTemplates.submitCallback(error, state, function(){ + AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.pwdChanged); + t.$("#at-field-current_password").val(""); + t.$("#at-field-password").val(""); + if (AccountsTemplates.options.confirmPassword) + t.$("#at-field-password_again").val(""); + }); + }); + } + + //---------------- + // Resend Verification E-mail + //---------------- + if (state === "resendVerificationEmail"){ + return Meteor.call("ATResendVerificationEmail", email, function (error) { + AccountsTemplates.submitCallback(error, state, function(){ + AccountsTemplates.state.form.set("result", AccountsTemplates.texts.info.verificationEmailSent); + t.$("#at-field-email").val(""); + + AccountsTemplates.avoidRedirect = true; + }); + }); + } + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form_btn.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form_btn.js new file mode 100644 index 00000000..fc263623 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_form_btn.js @@ -0,0 +1,18 @@ +AT.prototype.atPwdFormBtnHelpers = { + submitDisabled: function(){ + var disable = _.chain(AccountsTemplates.getFields()) + .map(function(field){ + return field.hasError() || field.isValidating(); + }) + .some() + .value() + ; + if (disable) + return "disabled"; + }, + buttonText: function() { + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + return T9n.get(AccountsTemplates.texts.button[state], markIfMissing=false); + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_link.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_link.js new file mode 100644 index 00000000..dd93a398 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_pwd_link.js @@ -0,0 +1,24 @@ +AT.prototype.atPwdLinkHelpers = { + disabled: function() { + return AccountsTemplates.disabled(); + }, + forgotPwdLink: function(){ + return AccountsTemplates.getRoutePath("forgotPwd"); + }, + preText: function(){ + return T9n.get(AccountsTemplates.texts.pwdLink_pre, markIfMissing=false); + }, + linkText: function(){ + return T9n.get(AccountsTemplates.texts.pwdLink_link, markIfMissing=false); + }, + suffText: function(){ + return T9n.get(AccountsTemplates.texts.pwdLink_suff, markIfMissing=false); + }, +}; + +AT.prototype.atPwdLinkEvents = { + "click #at-forgotPwd": function(event, t) { + event.preventDefault(); + AccountsTemplates.linkClick("forgotPwd"); + }, +}; \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_reCaptcha.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_reCaptcha.js new file mode 100644 index 00000000..ea0c0c69 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_reCaptcha.js @@ -0,0 +1,19 @@ +AT.prototype.atReCaptchaRendered = function() { + $.getScript('//www.google.com/recaptcha/api.js?hl=' + T9n.getLanguage()); +}; + +AT.prototype.atReCaptchaHelpers = { + key: function() { + if (AccountsTemplates.options.reCaptcha && AccountsTemplates.options.reCaptcha.siteKey) + return AccountsTemplates.options.reCaptcha.siteKey; + return Meteor.settings.public.reCaptcha.siteKey; + }, + + theme: function() { + return AccountsTemplates.options.reCaptcha && AccountsTemplates.options.reCaptcha.theme; + }, + + data_type: function() { + return AccountsTemplates.options.reCaptcha && AccountsTemplates.options.reCaptcha.data_type; + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_resend_verification_email_link.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_resend_verification_email_link.js new file mode 100644 index 00000000..5587900c --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_resend_verification_email_link.js @@ -0,0 +1,24 @@ +AT.prototype.atResendVerificationEmailLinkHelpers = { + disabled: function () { + return AccountsTemplates.disabled(); + }, + resendVerificationEmailLink: function () { + return AccountsTemplates.getRoutePath("resendVerificationEmail"); + }, + preText: function(){ + return T9n.get(AccountsTemplates.texts.resendVerificationEmailLink_pre, markIfMissing=false); + }, + linkText: function(){ + return T9n.get(AccountsTemplates.texts.resendVerificationEmailLink_link, markIfMissing=false); + }, + suffText: function(){ + return T9n.get(AccountsTemplates.texts.resendVerificationEmailLink_suff, markIfMissing=false); + }, +}; + +AT.prototype.atResendVerificationEmailLinkEvents = { + "click #at-resend-verification-email": function(event, t) { + event.preventDefault(); + AccountsTemplates.linkClick('resendVerificationEmail'); + }, +}; \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_result.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_result.js new file mode 100644 index 00000000..d4b287dd --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_result.js @@ -0,0 +1,7 @@ +AT.prototype.atResultHelpers = { + result: function() { + var resultText = AccountsTemplates.state.form.get("result"); + if (resultText) + return T9n.get(resultText, markIfMissing=false); + }, +}; \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_sep.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_sep.js new file mode 100644 index 00000000..7c27557d --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_sep.js @@ -0,0 +1,5 @@ +AT.prototype.atSepHelpers = { + sepText: function(){ + return T9n.get(AccountsTemplates.texts.sep, markIfMissing=false); + }, +}; \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_signin_link.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_signin_link.js new file mode 100644 index 00000000..14f6e88c --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_signin_link.js @@ -0,0 +1,24 @@ +AT.prototype.atSigninLinkHelpers = { + disabled: function() { + return AccountsTemplates.disabled(); + }, + signInLink: function(){ + return AccountsTemplates.getRoutePath("signIn"); + }, + preText: function(){ + return T9n.get(AccountsTemplates.texts.signInLink_pre, markIfMissing=false); + }, + linkText: function(){ + return T9n.get(AccountsTemplates.texts.signInLink_link, markIfMissing=false); + }, + suffText: function(){ + return T9n.get(AccountsTemplates.texts.signInLink_suff, markIfMissing=false); + }, +}; + +AT.prototype.atSigninLinkEvents = { + "click #at-signIn": function(event, t) { + event.preventDefault(); + AccountsTemplates.linkClick("signIn"); + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_signup_link.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_signup_link.js new file mode 100644 index 00000000..29c809a4 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_signup_link.js @@ -0,0 +1,24 @@ +AT.prototype.atSignupLinkHelpers = { + disabled: function() { + return AccountsTemplates.disabled(); + }, + signUpLink: function(){ + return AccountsTemplates.getRoutePath("signUp"); + }, + preText: function(){ + return T9n.get(AccountsTemplates.texts.signUpLink_pre, markIfMissing=false); + }, + linkText: function(){ + return T9n.get(AccountsTemplates.texts.signUpLink_link, markIfMissing=false); + }, + suffText: function(){ + return T9n.get(AccountsTemplates.texts.signUpLink_suff, markIfMissing=false); + }, +}; + +AT.prototype.atSignupLinkEvents = { + "click #at-signUp": function(event, t) { + event.preventDefault(); + AccountsTemplates.linkClick('signUp'); + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_social.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_social.js new file mode 100644 index 00000000..912fd6e9 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_social.js @@ -0,0 +1,105 @@ +AT.prototype.atSocialHelpers = { + disabled: function() { + if (AccountsTemplates.disabled()) + return "disabled"; + var user = Meteor.user(); + if (user){ + var numServices = 0; + if (user.services) + numServices = _.keys(user.services).length; // including "resume" + if (numServices === 2 && user.services[this._id]) + return "disabled"; + } + }, + name: function(){ + return this._id; + }, + iconClass: function() { + var ic = AccountsTemplates.texts.socialIcons[this._id]; + if (!ic) + ic = "fa fa-" + this._id; + return ic; + }, + buttonText: function() { + var service = this; + var serviceName = this._id; + if (serviceName === "meteor-developer") + serviceName = "meteor"; + serviceName = capitalize(serviceName); + if (!service.configured) + return T9n.get(AccountsTemplates.texts.socialConfigure, markIfMissing=false) + " " + serviceName; + var showAddRemove = AccountsTemplates.options.showAddRemoveServices; + var user = Meteor.user(); + if (user && showAddRemove){ + if (user.services && user.services[this._id]){ + var numServices = _.keys(user.services).length; // including "resume" + if (numServices === 2) + return serviceName; + else + return T9n.get(AccountsTemplates.texts.socialRemove, markIfMissing=false) + " " + serviceName; + } else + return T9n.get(AccountsTemplates.texts.socialAdd, markIfMissing=false) + " " + serviceName; + } + var parentData = Template.parentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + var prefix = state === "signIn" ? + T9n.get(AccountsTemplates.texts.socialSignIn, markIfMissing=false) : + T9n.get(AccountsTemplates.texts.socialSignUp, markIfMissing=false); + return prefix + " " + T9n.get(AccountsTemplates.texts.socialWith, markIfMissing=false) + " " + serviceName; + }, +}; + +AT.prototype.atSocialEvents = { + "click button": function(event, t) { + event.preventDefault(); + event.currentTarget.blur(); + if (AccountsTemplates.disabled()) + return; + var user = Meteor.user(); + if (user && user.services && user.services[this._id]){ + var numServices = _.keys(user.services).length; // including "resume" + if (numServices === 2) + return; + else{ + AccountsTemplates.setDisabled(true); + Meteor.call("ATRemoveService", this._id, function(error){ + AccountsTemplates.setDisabled(false); + }); + } + } else { + AccountsTemplates.setDisabled(true); + var parentData = Template.parentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + var serviceName = this._id; + var methodName; + if (serviceName === 'meteor-developer') + methodName = "loginWithMeteorDeveloperAccount"; + else + methodName = "loginWith" + capitalize(serviceName); + var loginWithService = Meteor[methodName]; + options = { + loginStyle: AccountsTemplates.options.socialLoginStyle, + }; + if (Accounts.ui) { + if (Accounts.ui._options.requestPermissions[serviceName]) { + options.requestPermissions = Accounts.ui._options.requestPermissions[serviceName]; + } + if (Accounts.ui._options.requestOfflineToken[serviceName]) { + options.requestOfflineToken = Accounts.ui._options.requestOfflineToken[serviceName]; + } + } + loginWithService(options, function(err) { + AccountsTemplates.setDisabled(false); + if (err && err instanceof Accounts.LoginCancelledError) { + // do nothing + } + else if (err && err instanceof ServiceConfiguration.ConfigError) { + if (Accounts._loginButtonsSession) + return Accounts._loginButtonsSession.configureService(serviceName); + } + else + AccountsTemplates.submitCallback(err, state); + }); + } + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_terms_link.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_terms_link.js new file mode 100644 index 00000000..0ada35cb --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_terms_link.js @@ -0,0 +1,33 @@ +AT.prototype.atTermsLinkHelpers = { + disabled: function() { + return AccountsTemplates.disabled(); + }, + text: function(){ + return T9n.get(AccountsTemplates.texts.termsPreamble, markIfMissing=false); + }, + privacyUrl: function(){ + return AccountsTemplates.options.privacyUrl; + }, + privacyLinkText: function(){ + return T9n.get(AccountsTemplates.texts.termsPrivacy, markIfMissing=false); + }, + showTermsAnd: function(){ + return !!AccountsTemplates.options.privacyUrl && !!AccountsTemplates.options.termsUrl; + }, + and: function(){ + return T9n.get(AccountsTemplates.texts.termsAnd, markIfMissing=false); + }, + termsUrl: function(){ + return AccountsTemplates.options.termsUrl; + }, + termsLinkText: function(){ + return T9n.get(AccountsTemplates.texts.termsTerms, markIfMissing=false); + }, +}; + +AT.prototype.atTermsLinkEvents = { + "click a": function(event) { + if (AccountsTemplates.disabled()) + event.preventDefault(); + }, +}; \ No newline at end of file diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/at_title.js b/packages/meteor-useraccounts-core/lib/templates_helpers/at_title.js new file mode 100644 index 00000000..74f711b9 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/at_title.js @@ -0,0 +1,7 @@ +AT.prototype.atTitleHelpers = { + title: function() { + var parentData = Template.currentData(); + var state = (parentData && parentData.state) || AccountsTemplates.getState(); + return T9n.get(AccountsTemplates.texts.title[state], markIfMissing = false); + }, +}; diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.html b/packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.html new file mode 100644 index 00000000..08c0d7e3 --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.html @@ -0,0 +1,12 @@ +<!-- Template level auth --> +<template name="ensureSignedIn"> + {{#if signedIn}} + {{> Template.dynamic template=template}} + {{else}} + {{#if auth}} + {{> Template.dynamic template=auth}} + {{else}} + {{> fullPageAtForm}} + {{/if}} + {{/if}} +</template> diff --git a/packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.js b/packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.js new file mode 100644 index 00000000..3d947aae --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/templates_helpers/ensure_signed_in.js @@ -0,0 +1,15 @@ + +Template.ensureSignedIn.helpers({ + signedIn: function () { + if (!Meteor.user()) { + AccountsTemplates.setState(AccountsTemplates.options.defaultState, function(){ + var err = AccountsTemplates.texts.errors.mustBeLoggedIn; + AccountsTemplates.state.form.set('error', [err]); + }); + return false; + } else { + AccountsTemplates.clearError(); + return true; + } + } +}); diff --git a/packages/meteor-useraccounts-core/lib/utils.js b/packages/meteor-useraccounts-core/lib/utils.js new file mode 100644 index 00000000..30b108ca --- /dev/null +++ b/packages/meteor-useraccounts-core/lib/utils.js @@ -0,0 +1,19 @@ +capitalize = function(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +}; + +signedInAs = function() { + var user = Meteor.user(); + + if (user) { + if (user.username) { + return user.username; + } else if (user.profile && user.profile.name) { + return user.profile.name; + } else if (user.emails && user.emails[0]) { + return user.emails[0].address; + } else { + return "Signed In"; + } + } +}; diff --git a/packages/meteor-useraccounts-core/package.js b/packages/meteor-useraccounts-core/package.js new file mode 100644 index 00000000..f6e0ca32 --- /dev/null +++ b/packages/meteor-useraccounts-core/package.js @@ -0,0 +1,94 @@ +'use strict'; + +Package.describe({ + summary: 'Meteor sign up and sign in templates core package.', + version: '1.14.2', + name: 'useraccounts:core', + git: 'https://github.com/meteor-useraccounts/core.git', +}); + +Package.onUse(function(api) { + //api.versionsFrom('METEOR@1.0.3'); + + api.use([ + 'accounts-base', + 'check', + 'underscore', + 'reactive-var', + ], ['client', 'server']); + + api.use([ + 'blaze', + 'reactive-dict', + 'templating', + 'jquery' + ], 'client'); + + api.use([ + 'http' + ], 'server'); + + api.imply([ + 'accounts-base', + 'softwarerero:accounts-t9n@1.3.3', + ], ['client', 'server']); + + api.imply([ + 'templating', + ], ['client']); + + api.addFiles([ + 'lib/field.js', + 'lib/core.js', + 'lib/server.js', + 'lib/methods.js', + 'lib/server_methods.js', + ], ['server']); + + api.addFiles([ + 'lib/utils.js', + 'lib/field.js', + 'lib/core.js', + 'lib/client.js', + 'lib/templates_helpers/at_error.js', + 'lib/templates_helpers/at_form.js', + 'lib/templates_helpers/at_input.js', + 'lib/templates_helpers/at_nav_button.js', + 'lib/templates_helpers/at_oauth.js', + 'lib/templates_helpers/at_pwd_form.js', + 'lib/templates_helpers/at_pwd_form_btn.js', + 'lib/templates_helpers/at_pwd_link.js', + 'lib/templates_helpers/at_reCaptcha.js', + 'lib/templates_helpers/at_resend_verification_email_link.js', + 'lib/templates_helpers/at_result.js', + 'lib/templates_helpers/at_sep.js', + 'lib/templates_helpers/at_signin_link.js', + 'lib/templates_helpers/at_signup_link.js', + 'lib/templates_helpers/at_social.js', + 'lib/templates_helpers/at_terms_link.js', + 'lib/templates_helpers/at_title.js', + 'lib/templates_helpers/at_message.js', + 'lib/templates_helpers/ensure_signed_in.html', + 'lib/templates_helpers/ensure_signed_in.js', + 'lib/methods.js', + ], ['client']); + + api.export([ + 'AccountsTemplates', + ], ['client', 'server']); +}); + +Package.onTest(function(api) { + api.use('useraccounts:core@1.14.2'); + + api.use([ + 'accounts-password', + 'tinytest', + 'test-helpers', + 'underscore', + ], ['client', 'server']); + + api.addFiles([ + 'tests/tests.js', + ], ['client', 'server']); +}); diff --git a/packages/meteor-useraccounts-core/tests/tests.js b/packages/meteor-useraccounts-core/tests/tests.js new file mode 100644 index 00000000..985200a3 --- /dev/null +++ b/packages/meteor-useraccounts-core/tests/tests.js @@ -0,0 +1,215 @@ +Tinytest.add("AccountsTemplates - addField/removeField", function(test) { + // Calls after AccountsTemplates.init() + AccountsTemplates._initialized = true; + test.throws(function() { + AccountsTemplates.addField(""); + }, function(err) { + if (err instanceof Error && err.message === "AccountsTemplates.addField should strictly be called before AccountsTemplates.init!") + return true; + }); + test.throws(function() { + AccountsTemplates.removeField(""); + }, function(err) { + if (err instanceof Error && err.message === "AccountsTemplates.removeField should strictly be called before AccountsTemplates.init!") + return true; + }); + AccountsTemplates._initialized = false; + + // Trying to remove a non-existing field + test.throws(function() { + AccountsTemplates.removeField("foo"); + }, function(err) { + if (err instanceof Error && err.message == "A field called foo does not exist!") + return true; + }); + + // Trying to remove an existing field + var email = AccountsTemplates.removeField("email"); + test.isUndefined(AccountsTemplates.getField("email")); + // ...and puts it back in for tests re-run + AccountsTemplates.addField(email); + + // Trying to add an already existing field + test.throws(function() { + var pwd = AccountsTemplates.getField("password"); + AccountsTemplates.addField(pwd); + }, function(err) { + if (err instanceof Error && err.message == "A field called password already exists!") + return true; + }); + + var login = { + _id: "login", + displayName: "Email", + type: "email" + }; + + // Successful add + AccountsTemplates.addField(login); + // ...and removes it for tests re-run + AccountsTemplates.removeField("login"); + + // Invalid field.type + test.throws(function() { + AccountsTemplates.addField({ + _id: "foo", + displayName: "Foo", + type: "bar" + }); + }, function(err) { + if (err instanceof Error && err.message == "field.type is not valid!") + return true; + }); + + // Invalid minLength + test.throws(function() { + AccountsTemplates.addField({ + _id: "first-name", + displayName: "First Name", + type: "text", + minLength: 0 + }); + }, function(err) { + if (err instanceof Error && err.message == "field.minLength should be greater than zero!") + return true; + }); + // Invalid maxLength + test.throws(function() { + AccountsTemplates.addField({ + _id: "first-name", + displayName: "First Name", + type: "text", + maxLength: 0 + }); + }, function(err) { + if (err instanceof Error && err.message == "field.maxLength should be greater than zero!") + return true; + }); + // maxLength < minLength + test.throws(function() { + AccountsTemplates.addField({ + _id: "first-name", + displayName: "First Name", + type: "text", + minLength: 2, + maxLength: 1 + }); + }, function(err) { + if (err instanceof Error && err.message == "field.maxLength should be greater than field.maxLength!") + return true; + }); + + // Successful add + var first_name = { + _id: "first_name", + displayName: "First Name", + type: "text", + minLength: 2, + maxLength: 50, + required: true + }; + AccountsTemplates.addField(first_name); + // Now removes it to be consistent with tests re-run + AccountsTemplates.removeField("first_name"); +}); + + +Tinytest.add("AccountsTemplates - addFields", function(test) { + // Fake uninitialized state... + AccountsTemplates._initialized = false; + + if (Meteor.isClient) { + // addFields does not exist client-side + test.throws(function() { + AccountsTemplates.addFields(); + }); + } else { + // Not an array of objects + test.throws(function() { + AccountsTemplates.addFields(""); + }, function(err) { + if (err instanceof Error && err.message === "field argument should be an array of valid field objects!") + return true; + }); + test.throws(function() { + AccountsTemplates.addFields(100); + }, function(err) { + if (err instanceof Error && err.message === "field argument should be an array of valid field objects!") + return true; + }); + // Empty array + test.throws(function() { + AccountsTemplates.addFields([]); + }, function(err) { + if (err instanceof Error && err.message === "field argument should be an array of valid field objects!") + return true; + }); + + // Successful add + var first_name = { + _id: "first_name", + displayName: "First Name", + type: "text", + minLength: 2, + maxLength: 50, + required: true + }; + var last_name = { + _id: "last_name", + displayName: "Last Name", + type: "text", + minLength: 2, + maxLength: 100, + required: false + }; + AccountsTemplates.addFields([first_name, last_name]); + // Now removes ot to be consistend with tests re-run + AccountsTemplates.removeField("first_name"); + AccountsTemplates.removeField("last_name"); + } + // Restores initialized state... + AccountsTemplates._initialized = true; +}); + + +Tinytest.add("AccountsTemplates - setState/getState", function(test) { + if (Meteor.isServer) { + // getState does not exist server-side + test.throws(function() { + AccountsTemplates.getState(); + }); + // setState does not exist server-side + test.throws(function() { + AccountsTemplates.setState(); + }); + } else { + _.each(AccountsTemplates.STATES, function(state){ + AccountsTemplates.setState(state); + test.equal(AccountsTemplates.getState(), state); + }); + // Setting an invalid state should throw a Meteor.Error + test.throws(function() { + AccountsTemplates.setState("foo"); + }, function(err) { + if (err instanceof Meteor.Error && err.details == "accounts-templates-core package got an invalid state value!") + return true; + }); + } +}); + + +// ------------------------------------- +// TODO: complite the following tests... +// ------------------------------------- + + +Tinytest.add("AccountsTemplates - configure", function(test) { + if (Meteor.isClient) { + // configure does not exist client-side + test.throws(function() { + AccountsTemplates.configure({}); + }); + } else { + // TODO: write actual tests... + } +}); \ No newline at end of file diff --git a/packages/wekan-accounts-cas/LICENSE b/packages/wekan-accounts-cas/LICENSE new file mode 100644 index 00000000..c2d69158 --- /dev/null +++ b/packages/wekan-accounts-cas/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2019 The Wekan Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/wekan-accounts-cas/README.md b/packages/wekan-accounts-cas/README.md new file mode 100644 index 00000000..3e246c4f --- /dev/null +++ b/packages/wekan-accounts-cas/README.md @@ -0,0 +1,88 @@ +This is a merged repository of useful forks of: atoy40:accounts-cas +=================== +([(https://atmospherejs.com/atoy40/accounts-cas](https://atmospherejs.com/atoy40/accounts-cas)) + +## Essential improvements by ppoulard to atoy40 and xaionaro versions + +* Added support of CAS attributes + +With this plugin, you can pick CAS attributes : https://github.com/joshchan/node-cas/wiki/CAS-Attributes + +Moved to Wekan GitHub org from from https://github.com/ppoulard/meteor-accounts-cas + +## Install + +``` +cd ~site +mkdir packages +cd packages +git clone https://github.com/wekan/meteor-accounts-cas +cd ~site +meteor add wekan:accounts-cas +``` + +## Usage + +Put CAS settings in Meteor.settings (for example using METEOR_SETTINGS env or --settings) like so: + +If casVersion is not defined, it will assume you use CAS 1.0. (note by xaionaro: option `casVersion` seems to be just ignored in the code, ATM). + +Server side settings: + +``` +Meteor.settings = { + "cas": { + "baseUrl": "https://cas.example.com/cas", + "autoClose": true, + "validateUrl":"https://cas.example.com/cas/p3/serviceValidate", + "casVersion": 3.0, + "attributes": { + "debug" : true + } + }, +} +``` + +CAS `attributes` settings : + +* `attributes`: by default `{}` : all default values below will apply +* * `debug` : by default `false` ; `true` will print to the server console the CAS attribute names to map, the CAS attributes values retrieved, if necessary the new user account created, and finally the user to use +* * `id` : by default, the CAS user is used for the user account, but you can specified another CAS attribute +* * `firstname` : by default `cas:givenName` ; but you can use your own CAS attribute +* * `lastname` : by default `cas:sn` (respectively) ; but you can use your own CAS attribute +* * `fullname` : by default unused, but if you specify your own CAS attribute, it will be used instead of the `firstname` + `lastname` +* * `mail` : by default `cas:mail` + +Client side settings: + +``` +Meteor.settings = { + "public": { + "cas": { + "loginUrl": "https://cas.example.com/login", + "serviceParam": "service", + "popupWidth": 810, + "popupHeight": 610, + "popup": true, + } + } +} +``` + +`proxyUrl` is not required. Setup [ROOT_URL](http://docs.meteor.com/api/core.html#Meteor-absoluteUrl) environment variable instead. + +Then, to start authentication, you have to call the following method from the client (for example in a click handler) : + +``` +Meteor.loginWithCas([callback]); +``` + +It must open a popup containing you CAS login form or redirect to the CAS login form (depending on "popup" setting). + +If popup is disabled (== false), then it's required to execute `Meteor.initCas([callback])` in `Meteor.startup` of the client side. ATM, `Meteor.initCas()` completes authentication. + +## Examples + +* [https://devel.mephi.ru/dyokunev/start-mephi-ru](https://devel.mephi.ru/dyokunev/start-mephi-ru) + + diff --git a/packages/wekan-accounts-cas/cas_client.js b/packages/wekan-accounts-cas/cas_client.js new file mode 100644 index 00000000..bd94be6b --- /dev/null +++ b/packages/wekan-accounts-cas/cas_client.js @@ -0,0 +1,112 @@ + +function addParameterToURL(url, param){ + var urlSplit = url.split('?'); + return url+(urlSplit.length>0 ? '?':'&') + param; +} + +Meteor.initCas = function(callback) { + const casTokenMatch = window.location.href.match(/[?&]casToken=([^&]+)/); + if (casTokenMatch == null) { + return; + } + + window.history.pushState('', document.title, window.location.href.replace(/([&?])casToken=[^&]+[&]?/, '$1').replace(/[?&]+$/g, '')); + + Accounts.callLoginMethod({ + methodArguments: [{ cas: { credentialToken: casTokenMatch[1] } }], + userCallback: function(err){ + if (err == null) { + // should we do anything on success? + } + if (callback != null) { + callback(err); + } + } + }); +} + +Meteor.loginWithCas = function(options, callback) { + + var credentialToken = Random.id(); + + if (!Meteor.settings.public && + !Meteor.settings.public.cas && + !Meteor.settings.public.cas.loginUrl) { + return; + } + + var settings = Meteor.settings.public.cas; + + var backURL = window.location.href.replace('#', ''); + if (options != null && options.redirectUrl != null) + backURL = options.redirectUrl; + + var serviceURL = addParameterToURL(backURL, 'casToken='+credentialToken); + + var loginUrl = settings.loginUrl + + "?" + (settings.serviceParam || "service") + "=" + + encodeURIComponent(serviceURL) + + if (settings.popup == false) { + window.location = loginUrl; + return; + } + + var popup = openCenteredPopup( + loginUrl, + settings.width || 800, + settings.height || 600 + ); + + var checkPopupOpen = setInterval(function() { + try { + if(popup && popup.document && popup.document.getElementById('popupCanBeClosed')) { + popup.close(); + } + // Fix for #328 - added a second test criteria (popup.closed === undefined) + // to humour this Android quirk: + // http://code.google.com/p/android/issues/detail?id=21061 + var popupClosed = popup.closed || popup.closed === undefined; + } catch (e) { + // For some unknown reason, IE9 (and others?) sometimes (when + // the popup closes too quickly?) throws "SCRIPT16386: No such + // interface supported" when trying to read 'popup.closed'. Try + // again in 100ms. + return; + } + + if (popupClosed) { + clearInterval(checkPopupOpen); + + // check auth on server. + Accounts.callLoginMethod({ + methodArguments: [{ cas: { credentialToken: credentialToken } }], + userCallback: callback + }); + } + }, 100); +}; + +var openCenteredPopup = function(url, width, height) { + var screenX = typeof window.screenX !== 'undefined' + ? window.screenX : window.screenLeft; + var screenY = typeof window.screenY !== 'undefined' + ? window.screenY : window.screenTop; + var outerWidth = typeof window.outerWidth !== 'undefined' + ? window.outerWidth : document.body.clientWidth; + var outerHeight = typeof window.outerHeight !== 'undefined' + ? window.outerHeight : (document.body.clientHeight - 22); + // XXX what is the 22? + + // Use `outerWidth - width` and `outerHeight - height` for help in + // positioning the popup centered relative to the current window + var left = screenX + (outerWidth - width) / 2; + var top = screenY + (outerHeight - height) / 2; + var features = ('width=' + width + ',height=' + height + + ',left=' + left + ',top=' + top + ',scrollbars=yes'); + + var newwindow = window.open(url, '_blank', features); + if (newwindow.focus) + newwindow.focus(); + return newwindow; +}; diff --git a/packages/wekan-accounts-cas/cas_client_cordova.js b/packages/wekan-accounts-cas/cas_client_cordova.js new file mode 100644 index 00000000..c7f95b50 --- /dev/null +++ b/packages/wekan-accounts-cas/cas_client_cordova.js @@ -0,0 +1,71 @@ + +Meteor.loginWithCas = function(callback) { + + var credentialToken = Random.id(); + + if (!Meteor.settings.public && + !Meteor.settings.public.cas && + !Meteor.settings.public.cas.loginUrl) { + return; + } + + var settings = Meteor.settings.public.cas; + + var loginUrl = settings.loginUrl + + "?" + (settings.service || "service") + "=" + + Meteor.absoluteUrl('_cas/') + + credentialToken; + + + var fail = function (err) { + Meteor._debug("Error from OAuth popup: " + JSON.stringify(err)); + }; + + // When running on an android device, we sometimes see the + // `pageLoaded` callback fire twice for the final page in the OAuth + // popup, even though the page only loads once. This is maybe an + // Android bug or maybe something intentional about how onPageFinished + // works that we don't understand and isn't well-documented. + var oauthFinished = false; + + var pageLoaded = function (event) { + if (oauthFinished) { + return; + } + + if (event.url.indexOf(Meteor.absoluteUrl('_cas')) === 0) { + + oauthFinished = true; + + // On iOS, this seems to prevent "Warning: Attempt to dismiss from + // view controller <MainViewController: ...> while a presentation + // or dismiss is in progress". My guess is that the last + // navigation of the OAuth popup is still in progress while we try + // to close the popup. See + // https://issues.apache.org/jira/browse/CB-2285. + // + // XXX Can we make this timeout smaller? + setTimeout(function () { + popup.close(); + // check auth on server. + Accounts.callLoginMethod({ + methodArguments: [{ cas: { credentialToken: credentialToken } }], + userCallback: callback + }); + }, 100); + } + }; + + var onExit = function () { + popup.removeEventListener('loadstop', pageLoaded); + popup.removeEventListener('loaderror', fail); + popup.removeEventListener('exit', onExit); + }; + + var popup = window.open(loginUrl, '_blank', 'location=no,hidden=no'); + popup.addEventListener('loadstop', pageLoaded); + popup.addEventListener('loaderror', fail); + popup.addEventListener('exit', onExit); + popup.show(); + +}; \ No newline at end of file diff --git a/packages/wekan-accounts-cas/cas_server.js b/packages/wekan-accounts-cas/cas_server.js new file mode 100644 index 00000000..15c1b174 --- /dev/null +++ b/packages/wekan-accounts-cas/cas_server.js @@ -0,0 +1,281 @@ +"use strict"; + +const Fiber = Npm.require('fibers'); +const https = Npm.require('https'); +const url = Npm.require('url'); +const xmlParser = Npm.require('xml2js'); + +// Library +class CAS { + constructor(options) { + options = options || {}; + + if (!options.validate_url) { + throw new Error('Required CAS option `validateUrl` missing.'); + } + + if (!options.service) { + throw new Error('Required CAS option `service` missing.'); + } + + const cas_url = url.parse(options.validate_url); + if (cas_url.protocol != 'https:' ) { + throw new Error('Only https CAS servers are supported.'); + } else if (!cas_url.hostname) { + throw new Error('Option `validateUrl` must be a valid url like: https://example.com/cas/serviceValidate'); + } else { + this.hostname = cas_url.host; + this.port = 443;// Should be 443 for https + this.validate_path = cas_url.pathname; + } + + this.service = options.service; + } + + validate(ticket, callback) { + const httparams = { + host: this.hostname, + port: this.port, + path: url.format({ + pathname: this.validate_path, + query: {ticket: ticket, service: this.service}, + }), + }; + + https.get(httparams, (res) => { + res.on('error', (e) => { + console.log('error' + e); + callback(e); + }); + + // Read result + res.setEncoding('utf8'); + let response = ''; + res.on('data', (chunk) => { + response += chunk; + }); + + res.on('end', (error) => { + if (error) { + console.log('error callback'); + console.log(error); + callback(undefined, false); + } else { + xmlParser.parseString(response, (err, result) => { + if (err) { + console.log('Bad response format.'); + callback({message: 'Bad response format. XML could not parse it'}); + } else { + if (result['cas:serviceResponse'] == null) { + console.log('Empty response.'); + callback({message: 'Empty response.'}); + } + if (result['cas:serviceResponse']['cas:authenticationSuccess']) { + var userData = { + id: result['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:user'][0].toLowerCase(), + } + const attributes = result['cas:serviceResponse']['cas:authenticationSuccess'][0]['cas:attributes'][0]; + for (var fieldName in attributes) { + userData[fieldName] = attributes[fieldName][0]; + }; + callback(undefined, true, userData); + } else { + callback(undefined, false); + } + } + }); + } + }); + }); + } +} +////// END OF CAS MODULE + +let _casCredentialTokens = {}; +let _userData = {}; + +//RoutePolicy.declare('/_cas/', 'network'); + +// Listen to incoming OAuth http requests +WebApp.connectHandlers.use((req, res, next) => { + // Need to create a Fiber since we're using synchronous http calls and nothing + // else is wrapping this in a fiber automatically + + Fiber(() => { + middleware(req, res, next); + }).run(); +}); + +const middleware = (req, res, next) => { + // Make sure to catch any exceptions because otherwise we'd crash + // the runner + try { + urlParsed = url.parse(req.url, true); + + // Getting the ticket (if it's defined in GET-params) + // If no ticket, then request will continue down the default + // middlewares. + const query = urlParsed.query; + if (query == null) { + next(); + return; + } + const ticket = query.ticket; + if (ticket == null) { + next(); + return; + } + + const serviceUrl = Meteor.absoluteUrl(urlParsed.href.replace(/^\//g, '')).replace(/([&?])ticket=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, ''); + const redirectUrl = serviceUrl;//.replace(/([&?])casToken=[^&]+[&]?/g, '$1').replace(/[?&]+$/g, ''); + + // get auth token + const credentialToken = query.casToken; + if (!credentialToken) { + end(res, redirectUrl); + return; + } + + // validate ticket + casValidate(req, ticket, credentialToken, serviceUrl, () => { + end(res, redirectUrl); + }); + + } catch (err) { + console.log("account-cas: unexpected error : " + err.message); + end(res, redirectUrl); + } +}; + +const casValidate = (req, ticket, token, service, callback) => { + // get configuration + if (!Meteor.settings.cas/* || !Meteor.settings.cas.validate*/) { + throw new Error('accounts-cas: unable to get configuration.'); + } + + const cas = new CAS({ + validate_url: Meteor.settings.cas.validateUrl, + service: service, + version: Meteor.settings.cas.casVersion + }); + + cas.validate(ticket, (err, status, userData) => { + if (err) { + console.log("accounts-cas: error when trying to validate " + err); + console.log(err); + } else { + if (status) { + console.log(`accounts-cas: user validated ${userData.id} + (${JSON.stringify(userData)})`); + _casCredentialTokens[token] = { id: userData.id }; + _userData = userData; + } else { + console.log("accounts-cas: unable to validate " + ticket); + } + } + callback(); + }); + + return; +}; + +/* + * Register a server-side login handle. + * It is call after Accounts.callLoginMethod() is call from client. + */ + Accounts.registerLoginHandler((options) => { + if (!options.cas) + return undefined; + + if (!_hasCredential(options.cas.credentialToken)) { + throw new Meteor.Error(Accounts.LoginCancelledError.numericError, + 'no matching login attempt found'); + } + + const result = _retrieveCredential(options.cas.credentialToken); + + const attrs = Meteor.settings.cas.attributes || {}; + // CAS keys + const fn = attrs.firstname || 'cas:givenName'; + const ln = attrs.lastname || 'cas:sn'; + const full = attrs.fullname; + const mail = attrs.mail || 'cas:mail'; // or 'email' + const uid = attrs.id || 'id'; + if (attrs.debug) { + if (full) { + console.log(`CAS fields : id:"${uid}", fullname:"${full}", mail:"${mail}"`); + } else { + console.log(`CAS fields : id:"${uid}", firstname:"${fn}", lastname:"${ln}", mail:"${mail}"`); + } + } + const name = full ? _userData[full] : _userData[fn] + ' ' + _userData[ln]; + // https://docs.meteor.com/api/accounts.html#Meteor-users + options = { + // _id: Meteor.userId() + username: _userData[uid], // Unique name + emails: [ + { address: _userData[mail], verified: true } + ], + createdAt: new Date(), + profile: { + // The profile is writable by the user by default. + name: name, + fullname : name, + email : _userData[mail] + }, + active: true, + globalRoles: ['user'] + }; + if (attrs.debug) { + console.log(`CAS response : ${JSON.stringify(result)}`); + } + let user = Meteor.users.findOne({ 'username': options.username }); + if (! user) { + if (attrs.debug) { + console.log(`Creating user account ${JSON.stringify(options)}`); + } + const userId = Accounts.insertUserDoc({}, options); + user = Meteor.users.findOne(userId); + } + if (attrs.debug) { + console.log(`Using user account ${JSON.stringify(user)}`); + } + return { userId: user._id }; +}); + +const _hasCredential = (credentialToken) => { + return _.has(_casCredentialTokens, credentialToken); +} + +/* + * Retrieve token and delete it to avoid replaying it. + */ +const _retrieveCredential = (credentialToken) => { + const result = _casCredentialTokens[credentialToken]; + delete _casCredentialTokens[credentialToken]; + return result; +} + +const closePopup = (res) => { + if (Meteor.settings.cas && Meteor.settings.cas.popup == false) { + return; + } + res.writeHead(200, {'Content-Type': 'text/html'}); + const content = '<html><body><div id="popupCanBeClosed"></div></body></html>'; + res.end(content, 'utf-8'); +} + +const redirect = (res, whereTo) => { + res.writeHead(302, {'Location': whereTo}); + const content = '<html><head><meta http-equiv="refresh" content="0; url='+whereTo+'" /></head><body>Redirection to <a href='+whereTo+'>'+whereTo+'</a></body></html>'; + res.end(content, 'utf-8'); + return +} + +const end = (res, whereTo) => { + if (Meteor.settings.cas && Meteor.settings.cas.popup == false) { + redirect(res, whereTo); + } else { + closePopup(res); + } +} diff --git a/packages/wekan-accounts-cas/package.js b/packages/wekan-accounts-cas/package.js new file mode 100644 index 00000000..d4b46c54 --- /dev/null +++ b/packages/wekan-accounts-cas/package.js @@ -0,0 +1,29 @@ +Package.describe({ + summary: "CAS support for accounts", + version: "0.1.0", + name: "wekan-accounts-cas", + git: "https://github.com/wekan/wekan-accounts-cas" +}); + +Package.onUse(function(api) { + api.versionsFrom('METEOR@1.3.5.1'); + api.use('routepolicy', 'server'); + api.use('webapp', 'server'); + api.use('accounts-base', ['client', 'server']); + // Export Accounts (etc) to packages using this one. + api.imply('accounts-base', ['client', 'server']); + api.use('underscore'); + api.add_files('cas_client.js', 'web.browser'); + api.add_files('cas_client_cordova.js', 'web.cordova'); + api.add_files('cas_server.js', 'server'); + +}); + +Npm.depends({ + xml2js: "0.4.17", + cas: "https://github.com/anrizal/node-cas/tarball/2baed530842e7a437f8f71b9346bcac8e84773cc" +}); + +Cordova.depends({ + 'cordova-plugin-inappbrowser': '1.2.0' +}); diff --git a/packages/wekan-accounts-oidc/.gitignore b/packages/wekan-accounts-oidc/.gitignore new file mode 100644 index 00000000..5379d4c3 --- /dev/null +++ b/packages/wekan-accounts-oidc/.gitignore @@ -0,0 +1 @@ +.versions diff --git a/packages/wekan-accounts-oidc/LICENSE.txt b/packages/wekan-accounts-oidc/LICENSE.txt new file mode 100644 index 00000000..c7be3264 --- /dev/null +++ b/packages/wekan-accounts-oidc/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (C) 2016 SWITCH + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/packages/wekan-accounts-oidc/README.md b/packages/wekan-accounts-oidc/README.md new file mode 100644 index 00000000..ce0b5738 --- /dev/null +++ b/packages/wekan-accounts-oidc/README.md @@ -0,0 +1,75 @@ +# salleman:accounts-oidc package + +A Meteor login service for OpenID Connect (OIDC). + +## Installation + + meteor add salleman:accounts-oidc + +## Usage + +`Meteor.loginWithOidc(options, callback)` +* `options` - object containing options, see below (optional) +* `callback` - callback function (optional) + +#### Example + +```js +Template.myTemplateName.events({ + 'click #login-button': function() { + Meteor.loginWithOidc(); + } +); +``` + + +## Options + +These options override service configuration stored in the database. + +* `loginStyle`: `redirect` or `popup` +* `redirectUrl`: Where to redirect after successful login. Only used if `loginStyle` is set to `redirect` + +## Manual Configuration Setup + +You can manually configure this package by upserting the service configuration on startup. First, add the `service-configuration` package: + + meteor add service-configuration + +### Service Configuration + +The following service configuration are available: + +* `clientId`: OIDC client identifier +* `secret`: OIDC client shared secret +* `serverUrl`: URL of the OIDC server. e.g. `https://openid.example.org:8443` +* `authorizationEndpoint`: Endpoint of the OIDC authorization service, e.g. `/oidc/authorize` +* `tokenEndpoint`: Endpoint of the OIDC token service, e.g. `/oidc/token` +* `userinfoEndpoint`: Endpoint of the OIDC userinfo service, e.g. `/oidc/userinfo` +* `idTokenWhitelistFields`: A list of fields from IDToken to be added to Meteor.user().services.oidc object + +### Project Configuration + +Then in your project: + +```js +if (Meteor.isServer) { + Meteor.startup(function () { + ServiceConfiguration.configurations.upsert( + { service: 'oidc' }, + { + $set: { + loginStyle: 'redirect', + clientId: 'my-client-id-registered-with-the-oidc-server', + secret: 'my-client-shared-secret', + serverUrl: 'https://openid.example.org', + authorizationEndpoint: '/oidc/authorize', + tokenEndpoint: '/oidc/token', + userinfoEndpoint: '/oidc/userinfo', + idTokenWhitelistFields: [] + } + } + ); + }); +} +``` diff --git a/packages/wekan-accounts-oidc/oidc.js b/packages/wekan-accounts-oidc/oidc.js new file mode 100644 index 00000000..75cd89ae --- /dev/null +++ b/packages/wekan-accounts-oidc/oidc.js @@ -0,0 +1,22 @@ +Accounts.oauth.registerService('oidc'); + +if (Meteor.isClient) { + Meteor.loginWithOidc = function(options, callback) { + // support a callback without options + if (! callback && typeof options === "function") { + callback = options; + options = null; + } + + var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback); + Oidc.requestCredential(options, credentialRequestCompleteCallback); + }; +} else { + Accounts.addAutopublishFields({ + // not sure whether the OIDC api can be used from the browser, + // thus not sure if we should be sending access tokens; but we do it + // for all other oauth2 providers, and it may come in handy. + forLoggedInUser: ['services.oidc'], + forOtherUsers: ['services.oidc.id'] + }); +} diff --git a/packages/wekan-accounts-oidc/oidc_login_button.css b/packages/wekan-accounts-oidc/oidc_login_button.css new file mode 100644 index 00000000..da42120b --- /dev/null +++ b/packages/wekan-accounts-oidc/oidc_login_button.css @@ -0,0 +1,3 @@ +#login-buttons-image-oidc { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACQUlEQVQ4T5WTy2taQRTGv4kSXw0IoYIihCjFmhhfhUqW9a+o0I2LInTRRbtw05V2I9KQuuimi24KXQqChIhQQcQgGGNz0YpvMCG1yL1tGqvBZsKMIIXcjQcOcznnfL+ZOecOEUVx4/Ly8mQ6neqxhKlUKmltbc1Nut2uqJ/bEnJAkiTmEhEEgVqtViiVyjuAP70j/Pj6Htbglzu52WyGdrsNUq1Wqc1mk939+9sHPP7wTVM232g0QMrlMrXb7bIFndgcbAk3ZPP1eh2kVCrRra2tRcFoNEK1WoXf78fg3Rxsfl3H3t4e3G43dnd3wWrMZjNqtRpIsVhcAFKpFPL5PBfF43H8TDj49/2XAvb393F2dgaNRgNKKaLR6ByQz+epw+HAwcEBisUijEYjgsEg1Go1pA9ODtC/+MZFDCKKIo9FIhEIggCSy+Xozs4OYrEY2ChDoRAIIVww/ujhxdrnFTSbTX6Cfr+Pi4sLhMNhnJ6egmSzWepyuZBIJGAwGBAIBLiY2ezTI74qg2UoFIqFr6ys4OrqiveKHB4eckAmk8FgMMD29jZ8Ph8XKj4/5uu/ZyXZKXBAOp2mHo+H/0isD6zDOp0Om5ubsAuvcA+/8ffpkSygUqmApFIp6vV6+b2ZsNfrodVqYTgcwqXtwul04pfhiSzg+PgYJJlMUovFwhvIbHV1lTs70c3NDSaTCa6vr+8A2FvodDr8CmwuepPJtIDIbvdfkInPz89ZRCKFQmFjNBqdjMfjpZ6jVquV1tfX3bcYegI7CyIWlgAAAABJRU5ErkJggg=='); +} diff --git a/packages/wekan-accounts-oidc/package.js b/packages/wekan-accounts-oidc/package.js new file mode 100644 index 00000000..251fb265 --- /dev/null +++ b/packages/wekan-accounts-oidc/package.js @@ -0,0 +1,19 @@ +Package.describe({ + summary: "OpenID Connect (OIDC) for Meteor accounts", + version: "1.0.10", + name: "wekan-accounts-oidc", + git: "https://github.com/wekan/meteor-accounts-oidc.git", + +}); + +Package.onUse(function(api) { + api.use('accounts-base@1.2.0', ['client', 'server']); + // Export Accounts (etc) to packages using this one. + api.imply('accounts-base', ['client', 'server']); + api.use('accounts-oauth@1.1.0', ['client', 'server']); + api.use('wekan-oidc@1.0.10', ['client', 'server']); + + api.addFiles('oidc_login_button.css', 'client'); + + api.addFiles('oidc.js'); +}); diff --git a/packages/wekan-ldap/LICENSE b/packages/wekan-ldap/LICENSE new file mode 100644 index 00000000..c2d69158 --- /dev/null +++ b/packages/wekan-ldap/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2019 The Wekan Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/wekan-ldap/README.md b/packages/wekan-ldap/README.md new file mode 100644 index 00000000..4f41d023 --- /dev/null +++ b/packages/wekan-ldap/README.md @@ -0,0 +1,130 @@ +# meteor-ldap + +This packages is based on the RocketChat ldap login package + +# settings definition + +LDAP_Enable: Self explanatory + +LDAP_Port: The port of the LDAP server + +LDAP_Host: The host server for the LDAP server + +LDAP_BaseDN: The base DN for the LDAP Tree + +LDAP_Login_Fallback: Fallback on the default authentication method + +LDAP_Reconnect: Reconnect to the server if the connection is lost + +LDAP_Timeout: self explanatory + +LDAP_Idle_Timeout: self explanatory + +LDAP_Connect_Timeout: self explanatory + +LDAP_Authentication: If the LDAP needs a user account to search + +LDAP_Authentication_UserDN: The search user DN + +LDAP_Authentication_Password: The password for the search user + +LDAP_Internal_Log_Level: The logging level for the module + +LDAP_Background_Sync: If the sync of the users should be done in the +background + +LDAP_Background_Sync_Interval: At which interval does the background task sync + +LDAP_Encryption: If using LDAPS, set it to 'ssl', else it will use 'ldap://' + +LDAP_CA_Cert: The certification for the LDAPS server + +LDAP_Reject_Unauthorized: Reject Unauthorized Certificate + +LDAP_User_Search_Filter: + +LDAP_User_Search_Scope: + +LDAP_User_Search_Field: Which field is used to find the user + +LDAP_Search_Page_Size: + +LDAP_Search_Size_Limit: + +LDAP_Group_Filter_Enable: enable group filtering + +LDAP_Group_Filter_ObjectClass: The object class for filtering + +LDAP_Group_Filter_Group_Id_Attribute: + +LDAP_Group_Filter_Group_Member_Attribute: + +LDAP_Group_Filter_Group_Member_Format: + +LDAP_Group_Filter_Group_Name: + +LDAP_Unique_Identifier_Field: This field is sometimes class GUID ( Globally Unique Identifier) + +UTF8_Names_Slugify: Convert the username to utf8 + +LDAP_Username_Field: Which field contains the ldap username + +LDAP_Fullname_Field: Which field contains the ldap full name + +LDAP_Email_Match_Enable: Allow existing account matching by e-mail address when username does not match + +LDAP_Email_Match_Require: Require existing account matching by e-mail address when username does match + +LDAP_Email_Match_Verified: Require existing account email address to be verified for matching + +LDAP_Email_Field: Which field contains the LDAP e-mail address + +LDAP_Sync_User_Data: + +LDAP_Sync_User_Data_FieldMap: + +Accounts_CustomFields: + +LDAP_Default_Domain: The default domain of the ldap it is used to create email if the field is not map correctly with the LDAP_Sync_User_Data_FieldMap + + + + +# example settings.json +``` +{ + "LDAP_Port": 389, + "LDAP_Host": "localhost", + "LDAP_BaseDN": "ou=user,dc=example,dc=org", + "LDAP_Login_Fallback": false, + "LDAP_Reconnect": true, + "LDAP_Timeout": 10000, + "LDAP_Idle_Timeout": 10000, + "LDAP_Connect_Timeout": 10000, + "LDAP_Authentication": true, + "LDAP_Authentication_UserDN": "cn=admin,dc=example,dc=org", + "LDAP_Authentication_Password": "admin", + "LDAP_Internal_Log_Level": "debug", + "LDAP_Background_Sync": false, + "LDAP_Background_Sync_Interval": "100", + "LDAP_Encryption": false, + "LDAP_Reject_Unauthorized": false, + "LDAP_Group_Filter_Enable": false, + "LDAP_Search_Page_Size": 0, + "LDAP_Search_Size_Limit": 0, + "LDAP_User_Search_Filter": "", + "LDAP_User_Search_Field": "uid", + "LDAP_User_Search_Scope": "", + "LDAP_Unique_Identifier_Field": "guid", + "LDAP_Username_Field": "uid", + "LDAP_Fullname_Field": "cn", + "LDAP_Email_Match_Enable": true, + "LDAP_Email_Match_Require": false, + "LDAP_Email_Match_Verified": false, + "LDAP_Email_Field": "mail", + "LDAP_Sync_User_Data": false, + "LDAP_Sync_User_Data_FieldMap": "{\"cn\":\"name\", \"mail\":\"email\"}", + "LDAP_Merge_Existing_Users": true, + "UTF8_Names_Slugify": true +} +``` diff --git a/packages/wekan-ldap/client/loginHelper.js b/packages/wekan-ldap/client/loginHelper.js new file mode 100644 index 00000000..48a290c1 --- /dev/null +++ b/packages/wekan-ldap/client/loginHelper.js @@ -0,0 +1,52 @@ +// Pass in username, password as normal +// customLdapOptions should be passed in if you want to override LDAP_DEFAULTS +// on any particular call (if you have multiple ldap servers you'd like to connect to) +// You'll likely want to set the dn value here {dn: "..."} +Meteor.loginWithLDAP = function(username, password, customLdapOptions, callback) { + // Retrieve arguments as array + const args = []; + for (let i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + // Pull username and password + username = args.shift(); + password = args.shift(); + + // Check if last argument is a function + // if it is, pop it off and set callback to it + if (typeof args[args.length-1] === 'function') { + callback = args.pop(); + } else { + callback = null; + } + + // if args still holds options item, grab it + if (args.length > 0) { + customLdapOptions = args.shift(); + } else { + customLdapOptions = {}; + } + + // Set up loginRequest object + const loginRequest = { + ldap: true, + username, + ldapPass: password, + ldapOptions: customLdapOptions, + }; + + Accounts.callLoginMethod({ + // Call login method with ldap = true + // This will hook into our login handler for ldap + methodArguments: [loginRequest], + userCallback(error/*, result*/) { + if (error) { + if (callback) { + callback(error); + } + } else if (callback) { + callback(); + } + }, + }); +}; diff --git a/packages/wekan-ldap/package.js b/packages/wekan-ldap/package.js new file mode 100644 index 00000000..f6fbb458 --- /dev/null +++ b/packages/wekan-ldap/package.js @@ -0,0 +1,32 @@ +Package.describe({ + name: 'wekan:wekan-ldap', + version: '0.0.2', + // Brief, one-line summary of the package. + summary: 'Basic meteor login with ldap', + // URL to the Git repository containing the source code for this package. + git: 'https://github.com/wekan/wekan-ldap', + // By default, Meteor will default to using README.md for documentation. + // To avoid submitting documentation, set this field to null. + documentation: 'README.md' +}); + + +Package.onUse(function(api) { + api.versionsFrom('1.0.3.1'); + api.use('yasaricli:slugify@0.0.5'); + api.use('ecmascript@0.9.0'); + api.use('underscore'); + api.use('sha'); + api.use('templating', 'client'); + + api.use('accounts-base', 'server'); + api.use('accounts-password', 'server'); + + api.addFiles('client/loginHelper.js', 'client'); + + api.mainModule('server/index.js', 'server'); +}); + +Npm.depends({ + ldapjs: '1.0.2', +}); \ No newline at end of file diff --git a/packages/wekan-ldap/server/index.js b/packages/wekan-ldap/server/index.js new file mode 100644 index 00000000..e3ff85a1 --- /dev/null +++ b/packages/wekan-ldap/server/index.js @@ -0,0 +1 @@ +import './loginHandler'; diff --git a/packages/wekan-ldap/server/ldap.js b/packages/wekan-ldap/server/ldap.js new file mode 100644 index 00000000..555a30aa --- /dev/null +++ b/packages/wekan-ldap/server/ldap.js @@ -0,0 +1,555 @@ +import ldapjs from 'ldapjs'; +import util from 'util'; +import Bunyan from 'bunyan'; +import { log_debug, log_info, log_warn, log_error } from './logger'; + +export default class LDAP { + constructor(){ + this.ldapjs = ldapjs; + + this.connected = false; + + this.options = { + host: this.constructor.settings_get('LDAP_HOST'), + port: this.constructor.settings_get('LDAP_PORT'), + Reconnect: this.constructor.settings_get('LDAP_RECONNECT'), + timeout: this.constructor.settings_get('LDAP_TIMEOUT'), + connect_timeout: this.constructor.settings_get('LDAP_CONNECT_TIMEOUT'), + idle_timeout: this.constructor.settings_get('LDAP_IDLE_TIMEOUT'), + encryption: this.constructor.settings_get('LDAP_ENCRYPTION'), + ca_cert: this.constructor.settings_get('LDAP_CA_CERT'), + reject_unauthorized: this.constructor.settings_get('LDAP_REJECT_UNAUTHORIZED') || false, + Authentication: this.constructor.settings_get('LDAP_AUTHENTIFICATION'), + Authentication_UserDN: this.constructor.settings_get('LDAP_AUTHENTIFICATION_USERDN'), + Authentication_Password: this.constructor.settings_get('LDAP_AUTHENTIFICATION_PASSWORD'), + Authentication_Fallback: this.constructor.settings_get('LDAP_LOGIN_FALLBACK'), + BaseDN: this.constructor.settings_get('LDAP_BASEDN'), + Internal_Log_Level: this.constructor.settings_get('INTERNAL_LOG_LEVEL'), + User_Search_Filter: this.constructor.settings_get('LDAP_USER_SEARCH_FILTER'), + User_Search_Scope: this.constructor.settings_get('LDAP_USER_SEARCH_SCOPE'), + User_Search_Field: this.constructor.settings_get('LDAP_USER_SEARCH_FIELD'), + Search_Page_Size: this.constructor.settings_get('LDAP_SEARCH_PAGE_SIZE'), + Search_Size_Limit: this.constructor.settings_get('LDAP_SEARCH_SIZE_LIMIT'), + group_filter_enabled: this.constructor.settings_get('LDAP_GROUP_FILTER_ENABLE'), + group_filter_object_class: this.constructor.settings_get('LDAP_GROUP_FILTER_OBJECTCLASS'), + group_filter_group_id_attribute: this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_ID_ATTRIBUTE'), + group_filter_group_member_attribute: this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_MEMBER_ATTRIBUTE'), + group_filter_group_member_format: this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_MEMBER_FORMAT'), + group_filter_group_name: this.constructor.settings_get('LDAP_GROUP_FILTER_GROUP_NAME'), + }; + } + + static settings_get(name, ...args) { + let value = process.env[name]; + if (value !== undefined) { + if (value === 'true' || value === 'false') { + value = JSON.parse(value); + } else if (value !== '' && !isNaN(value)) { + value = Number(value); + } + return value; + } else { + log_warn(`Lookup for unset variable: ${name}`); + } + } + connectSync(...args) { + if (!this._connectSync) { + this._connectSync = Meteor.wrapAsync(this.connectAsync, this); + } + return this._connectSync(...args); + } + + searchAllSync(...args) { + if (!this._searchAllSync) { + this._searchAllSync = Meteor.wrapAsync(this.searchAllAsync, this); + } + return this._searchAllSync(...args); + } + + connectAsync(callback) { + log_info('Init setup'); + + let replied = false; + + const connectionOptions = { + url: `${ this.options.host }:${ this.options.port }`, + timeout: this.options.timeout, + connectTimeout: this.options.connect_timeout, + idleTimeout: this.options.idle_timeout, + reconnect: this.options.Reconnect, + }; + + if (this.options.Internal_Log_Level !== 'disabled') { + connectionOptions.log = new Bunyan({ + name: 'ldapjs', + component: 'client', + stream: process.stderr, + level: this.options.Internal_Log_Level, + }); + } + + const tlsOptions = { + rejectUnauthorized: this.options.reject_unauthorized, + }; + + if (this.options.ca_cert && this.options.ca_cert !== '') { + // Split CA cert into array of strings + const chainLines = this.constructor.settings_get('LDAP_CA_CERT').split('\n'); + let cert = []; + const ca = []; + chainLines.forEach((line) => { + cert.push(line); + if (line.match(/-END CERTIFICATE-/)) { + ca.push(cert.join('\n')); + cert = []; + } + }); + tlsOptions.ca = ca; + } + + if (this.options.encryption === 'ssl') { + connectionOptions.url = `ldaps://${ connectionOptions.url }`; + connectionOptions.tlsOptions = tlsOptions; + } else { + connectionOptions.url = `ldap://${ connectionOptions.url }`; + } + + log_info('Connecting', connectionOptions.url); + log_debug(`connectionOptions${ util.inspect(connectionOptions)}`); + + this.client = ldapjs.createClient(connectionOptions); + + this.bindSync = Meteor.wrapAsync(this.client.bind, this.client); + + this.client.on('error', (error) => { + log_error('connection', error); + if (replied === false) { + replied = true; + callback(error, null); + } + }); + + this.client.on('idle', () => { + log_info('Idle'); + this.disconnect(); + }); + + this.client.on('close', () => { + log_info('Closed'); + }); + + if (this.options.encryption === 'tls') { + // Set host parameter for tls.connect which is used by ldapjs starttls. This shouldn't be needed in newer nodejs versions (e.g v5.6.0). + // https://github.com/RocketChat/Rocket.Chat/issues/2035 + // https://github.com/mcavage/node-ldapjs/issues/349 + tlsOptions.host = this.options.host; + + log_info('Starting TLS'); + log_debug('tlsOptions', tlsOptions); + + this.client.starttls(tlsOptions, null, (error, response) => { + if (error) { + log_error('TLS connection', error); + if (replied === false) { + replied = true; + callback(error, null); + } + return; + } + + log_info('TLS connected'); + this.connected = true; + if (replied === false) { + replied = true; + callback(null, response); + } + }); + } else { + this.client.on('connect', (response) => { + log_info('LDAP connected'); + this.connected = true; + if (replied === false) { + replied = true; + callback(null, response); + } + }); + } + + setTimeout(() => { + if (replied === false) { + log_error('connection time out', connectionOptions.connectTimeout); + replied = true; + callback(new Error('Timeout')); + } + }, connectionOptions.connectTimeout); + } + + getUserFilter(username) { + const filter = []; + + if (this.options.User_Search_Filter !== '') { + if (this.options.User_Search_Filter[0] === '(') { + filter.push(`${ this.options.User_Search_Filter }`); + } else { + filter.push(`(${ this.options.User_Search_Filter })`); + } + } + + const usernameFilter = this.options.User_Search_Field.split(',').map((item) => `(${ item }=${ username })`); + + if (usernameFilter.length === 0) { + log_error('LDAP_LDAP_User_Search_Field not defined'); + } else if (usernameFilter.length === 1) { + filter.push(`${ usernameFilter[0] }`); + } else { + filter.push(`(|${ usernameFilter.join('') })`); + } + + return `(&${ filter.join('') })`; + } + + bindIfNecessary() { + if (this.domainBinded === true) { + return; + } + + if (this.options.Authentication !== true) { + return; + } + + log_info('Binding UserDN', this.options.Authentication_UserDN); + this.bindSync(this.options.Authentication_UserDN, this.options.Authentication_Password); + this.domainBinded = true; + } + + searchUsersSync(username, page) { + this.bindIfNecessary(); + + const searchOptions = { + filter: this.getUserFilter(username), + scope: this.options.User_Search_Scope || 'sub', + sizeLimit: this.options.Search_Size_Limit, + }; + + if (this.options.Search_Page_Size > 0) { + searchOptions.paged = { + pageSize: this.options.Search_Page_Size, + pagePause: !!page, + }; + } + + log_info('Searching user', username); + log_debug('searchOptions', searchOptions); + log_debug('BaseDN', this.options.BaseDN); + + if (page) { + return this.searchAllPaged(this.options.BaseDN, searchOptions, page); + } + + return this.searchAllSync(this.options.BaseDN, searchOptions); + } + + getUserByIdSync(id, attribute) { + this.bindIfNecessary(); + + const Unique_Identifier_Field = this.constructor.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD').split(','); + + let filter; + + if (attribute) { + filter = new this.ldapjs.filters.EqualityFilter({ + attribute, + value: new Buffer(id, 'hex'), + }); + } else { + const filters = []; + Unique_Identifier_Field.forEach((item) => { + filters.push(new this.ldapjs.filters.EqualityFilter({ + attribute: item, + value: new Buffer(id, 'hex'), + })); + }); + + filter = new this.ldapjs.filters.OrFilter({filters}); + } + + const searchOptions = { + filter, + scope: 'sub', + }; + + log_info('Searching by id', id); + log_debug('search filter', searchOptions.filter.toString()); + log_debug('BaseDN', this.options.BaseDN); + + const result = this.searchAllSync(this.options.BaseDN, searchOptions); + + if (!Array.isArray(result) || result.length === 0) { + return; + } + + if (result.length > 1) { + log_error('Search by id', id, 'returned', result.length, 'records'); + } + + return result[0]; + } + + getUserByUsernameSync(username) { + this.bindIfNecessary(); + + const searchOptions = { + filter: this.getUserFilter(username), + scope: this.options.User_Search_Scope || 'sub', + }; + + log_info('Searching user', username); + log_debug('searchOptions', searchOptions); + log_debug('BaseDN', this.options.BaseDN); + + const result = this.searchAllSync(this.options.BaseDN, searchOptions); + + if (!Array.isArray(result) || result.length === 0) { + return; + } + + if (result.length > 1) { + log_error('Search by username', username, 'returned', result.length, 'records'); + } + + return result[0]; + } + + getUserGroups(username, ldapUser){ + if (!this.options.group_filter_enabled) { + return true; + } + + const filter = ['(&']; + + if (this.options.group_filter_object_class !== '') { + filter.push(`(objectclass=${ this.options.group_filter_object_class })`); + } + + if (this.options.group_filter_group_member_attribute !== '') { + const format_value = ldapUser[this.options.group_filter_group_member_format]; + if( format_value ) { + filter.push(`(${ this.options.group_filter_group_member_attribute }=${ format_value })`); + } + } + + filter.push(')'); + + const searchOptions = { + filter: filter.join('').replace(/#{username}/g, username), + scope: 'sub', + }; + + log_debug('Group list filter LDAP:', searchOptions.filter); + + const result = this.searchAllSync(this.options.BaseDN, searchOptions); + + if (!Array.isArray(result) || result.length === 0) { + return []; + } + + const grp_identifier = this.options.group_filter_group_id_attribute || 'cn'; + const groups = []; + result.map((item) => { + groups.push( item[ grp_identifier ] ); + }); + log_debug(`Groups: ${ groups.join(', ')}`); + return groups; + + } + + isUserInGroup(username, ldapUser) { + if (!this.options.group_filter_enabled) { + return true; + } + + const grps = this.getUserGroups(username, ldapUser); + + const filter = ['(&']; + + if (this.options.group_filter_object_class !== '') { + filter.push(`(objectclass=${ this.options.group_filter_object_class })`); + } + + if (this.options.group_filter_group_member_attribute !== '') { + const format_value = ldapUser[this.options.group_filter_group_member_format]; + if( format_value ) { + filter.push(`(${ this.options.group_filter_group_member_attribute }=${ format_value })`); + } + } + + if (this.options.group_filter_group_id_attribute !== '') { + filter.push(`(${ this.options.group_filter_group_id_attribute }=${ this.options.group_filter_group_name })`); + } + filter.push(')'); + + const searchOptions = { + filter: filter.join('').replace(/#{username}/g, username), + scope: 'sub', + }; + + log_debug('Group filter LDAP:', searchOptions.filter); + + const result = this.searchAllSync(this.options.BaseDN, searchOptions); + + if (!Array.isArray(result) || result.length === 0) { + return false; + } + return true; + } + + extractLdapEntryData(entry) { + const values = { + _raw: entry.raw, + }; + + Object.keys(values._raw).forEach((key) => { + const value = values._raw[key]; + + if (!['thumbnailPhoto', 'jpegPhoto'].includes(key)) { + if (value instanceof Buffer) { + values[key] = value.toString(); + } else { + values[key] = value; + } + } + }); + + return values; + } + + searchAllPaged(BaseDN, options, page) { + this.bindIfNecessary(); + + const processPage = ({entries, title, end, next}) => { + log_info(title); + // Force LDAP idle to wait the record processing + this.client._updateIdle(true); + page(null, entries, {end, next: () => { + // Reset idle timer + this.client._updateIdle(); + next && next(); + }}); + }; + + this.client.search(BaseDN, options, (error, res) => { + if (error) { + log_error(error); + page(error); + return; + } + + res.on('error', (error) => { + log_error(error); + page(error); + return; + }); + + let entries = []; + + const internalPageSize = options.paged && options.paged.pageSize > 0 ? options.paged.pageSize * 2 : 500; + + res.on('searchEntry', (entry) => { + entries.push(this.extractLdapEntryData(entry)); + + if (entries.length >= internalPageSize) { + processPage({ + entries, + title: 'Internal Page', + end: false, + }); + entries = []; + } + }); + + res.on('page', (result, next) => { + if (!next) { + this.client._updateIdle(true); + processPage({ + entries, + title: 'Final Page', + end: true, + }); + } else if (entries.length) { + log_info('Page'); + processPage({ + entries, + title: 'Page', + end: false, + next, + }); + entries = []; + } + }); + + res.on('end', () => { + if (entries.length) { + processPage({ + entries, + title: 'Final Page', + end: true, + }); + entries = []; + } + }); + }); + } + + searchAllAsync(BaseDN, options, callback) { + this.bindIfNecessary(); + + this.client.search(BaseDN, options, (error, res) => { + if (error) { + log_error(error); + callback(error); + return; + } + + res.on('error', (error) => { + log_error(error); + callback(error); + return; + }); + + const entries = []; + + res.on('searchEntry', (entry) => { + entries.push(this.extractLdapEntryData(entry)); + }); + + res.on('end', () => { + log_info('Search result count', entries.length); + callback(null, entries); + }); + }); + } + + authSync(dn, password) { + log_info('Authenticating', dn); + + try { + if (password === '') { + throw new Error('Password is not provided'); + } + this.bindSync(dn, password); + log_info('Authenticated', dn); + return true; + } catch (error) { + log_info('Not authenticated', dn); + log_debug('error', error); + return false; + } + } + + disconnect() { + this.connected = false; + this.domainBinded = false; + log_info('Disconecting'); + this.client.unbind(); + } +} diff --git a/packages/wekan-ldap/server/logger.js b/packages/wekan-ldap/server/logger.js new file mode 100644 index 00000000..afd77112 --- /dev/null +++ b/packages/wekan-ldap/server/logger.js @@ -0,0 +1,15 @@ +const isLogEnabled = (process.env.LDAP_LOG_ENABLED === 'true'); + + +function log (level, message, data) { + if (isLogEnabled) { + console.log(`[${level}] ${message} ${ data ? JSON.stringify(data, null, 2) : '' }`); + } +} + +function log_debug (...args) { log('DEBUG', ...args); } +function log_info (...args) { log('INFO', ...args); } +function log_warn (...args) { log('WARN', ...args); } +function log_error (...args) { log('ERROR', ...args); } + +export { log, log_debug, log_info, log_warn, log_error }; diff --git a/packages/wekan-ldap/server/loginHandler.js b/packages/wekan-ldap/server/loginHandler.js new file mode 100644 index 00000000..a8f013d7 --- /dev/null +++ b/packages/wekan-ldap/server/loginHandler.js @@ -0,0 +1,224 @@ +import {slug, getLdapUsername, getLdapEmail, getLdapUserUniqueID, syncUserData, addLdapUser} from './sync'; +import LDAP from './ldap'; +import { log_debug, log_info, log_warn, log_error } from './logger'; + +function fallbackDefaultAccountSystem(bind, username, password) { + if (typeof username === 'string') { + if (username.indexOf('@') === -1) { + username = {username}; + } else { + username = {email: username}; + } + } + + log_info('Fallback to default account system: ', username ); + + const loginRequest = { + user: username, + password: { + digest: SHA256(password), + algorithm: 'sha-256', + }, + }; + log_debug('Fallback options: ', loginRequest); + + return Accounts._runLoginHandlers(bind, loginRequest); +} + +Accounts.registerLoginHandler('ldap', function(loginRequest) { + if (!loginRequest.ldap || !loginRequest.ldapOptions) { + return undefined; + } + + log_info('Init LDAP login', loginRequest.username); + + if (LDAP.settings_get('LDAP_ENABLE') !== true) { + return fallbackDefaultAccountSystem(this, loginRequest.username, loginRequest.ldapPass); + } + + const self = this; + const ldap = new LDAP(); + let ldapUser; + + try { + ldap.connectSync(); + const users = ldap.searchUsersSync(loginRequest.username); + + if (users.length !== 1) { + log_info('Search returned', users.length, 'record(s) for', loginRequest.username); + throw new Error('User not Found'); + } + + if (ldap.authSync(users[0].dn, loginRequest.ldapPass) === true) { + if (ldap.isUserInGroup(loginRequest.username, users[0])) { + ldapUser = users[0]; + } else { + throw new Error('User not in a valid group'); + } + } else { + log_info('Wrong password for', loginRequest.username); + } + } catch (error) { + log_error(error); + } + + if (ldapUser === undefined) { + if (LDAP.settings_get('LDAP_LOGIN_FALLBACK') === true) { + return fallbackDefaultAccountSystem(self, loginRequest.username, loginRequest.ldapPass); + } + + throw new Meteor.Error('LDAP-login-error', `LDAP Authentication failed with provided username [${ loginRequest.username }]`); + } + + // Look to see if user already exists + + let userQuery; + + const Unique_Identifier_Field = getLdapUserUniqueID(ldapUser); + let user; + + // Attempt to find user by unique identifier + + if (Unique_Identifier_Field) { + userQuery = { + 'services.ldap.id': Unique_Identifier_Field.value, + }; + + log_info('Querying user'); + log_debug('userQuery', userQuery); + + user = Meteor.users.findOne(userQuery); + } + + // Attempt to find user by username + + let username; + let email; + + if (LDAP.settings_get('LDAP_USERNAME_FIELD') !== '') { + username = slug(getLdapUsername(ldapUser)); + } else { + username = slug(loginRequest.username); + } + + if(LDAP.settings_get('LDAP_EMAIL_FIELD') !== '') { + email = getLdapEmail(ldapUser); + } + + if (!user) { + if(email && LDAP.settings_get('LDAP_EMAIL_MATCH_REQUIRE') === true) { + if(LDAP.settings_get('LDAP_EMAIL_MATCH_VERIFIED') === true) { + userQuery = { + '_id' : username, + 'emails.0.address' : email, + 'emails.0.verified' : true + }; + } else { + userQuery = { + '_id' : username, + 'emails.0.address' : email + }; + } + } else { + userQuery = { + username + }; + } + + log_debug('userQuery', userQuery); + + user = Meteor.users.findOne(userQuery); + } + + // Attempt to find user by e-mail address only + + if (!user && email && LDAP.settings_get('LDAP_EMAIL_MATCH_ENABLE') === true) { + + log_info('No user exists with username', username, '- attempting to find by e-mail address instead'); + + if(LDAP.settings_get('LDAP_EMAIL_MATCH_VERIFIED') === true) { + userQuery = { + 'emails.0.address': email, + 'emails.0.verified' : true + }; + } else { + userQuery = { + 'emails.0.address' : email + }; + } + + log_debug('userQuery', userQuery); + + user = Meteor.users.findOne(userQuery); + + } + + // Login user if they exist + if (user) { + if (user.authenticationMethod !== 'ldap' && LDAP.settings_get('LDAP_MERGE_EXISTING_USERS') !== true) { + log_info('User exists without "authenticationMethod : ldap"'); + throw new Meteor.Error('LDAP-login-error', `LDAP Authentication succeded, but there's already a matching Wekan account in MongoDB`); + } + + log_info('Logging user'); + + const stampedToken = Accounts._generateStampedLoginToken(); + const update_data = { + $push: { + 'services.resume.loginTokens': Accounts._hashStampedToken(stampedToken), + }, + }; + + if( LDAP.settings_get('LDAP_SYNC_GROUP_ROLES') === true ) { + log_debug('Updating Groups/Roles'); + const groups = ldap.getUserGroups(username, ldapUser); + + if( groups.length > 0 ) { + Roles.setUserRoles(user._id, groups ); + log_info(`Updated roles to:${ groups.join(',')}`); + } + } + + Meteor.users.update(user._id, update_data ); + + syncUserData(user, ldapUser); + + if (LDAP.settings_get('LDAP_LOGIN_FALLBACK') === true) { + Accounts.setPassword(user._id, loginRequest.ldapPass, {logout: false}); + } + + return { + userId: user._id, + token: stampedToken.token, + }; + } + + // Create new user + + log_info('User does not exist, creating', username); + + if (LDAP.settings_get('LDAP_USERNAME_FIELD') === '') { + username = undefined; + } + + if (LDAP.settings_get('LDAP_LOGIN_FALLBACK') !== true) { + loginRequest.ldapPass = undefined; + } + + const result = addLdapUser(ldapUser, username, loginRequest.ldapPass); + + if( LDAP.settings_get('LDAP_SYNC_GROUP_ROLES') === true ) { + const groups = ldap.getUserGroups(username, ldapUser); + if( groups.length > 0 ) { + Roles.setUserRoles(result.userId, groups ); + log_info(`Set roles to:${ groups.join(',')}`); + } + } + + + if (result instanceof Error) { + throw result; + } + + return result; +}); diff --git a/packages/wekan-ldap/server/sync.js b/packages/wekan-ldap/server/sync.js new file mode 100644 index 00000000..141ef349 --- /dev/null +++ b/packages/wekan-ldap/server/sync.js @@ -0,0 +1,447 @@ +import _ from 'underscore'; +import LDAP from './ldap'; +import { log_debug, log_info, log_warn, log_error } from './logger'; + +Object.defineProperty(Object.prototype, "getLDAPValue", { + value: function (prop) { + const self = this; + for (let key in self) { + if (key.toLowerCase() == prop.toLowerCase()) { + return self[key]; + } + } + }, + + enumerable: false +}); + +export function slug(text) { + if (LDAP.settings_get('LDAP_UTF8_NAMES_SLUGIFY') !== true) { + return text; + } + text = slugify(text, '.'); + return text.replace(/[^0-9a-z-_.]/g, ''); +} + +function templateVarHandler (variable, object) { + + const templateRegex = /#{([\w\-]+)}/gi; + let match = templateRegex.exec(variable); + let tmpVariable = variable; + + if (match == null) { + if (!object.hasOwnProperty(variable)) { + return; + } + return object[variable]; + } else { + while (match != null) { + const tmplVar = match[0]; + const tmplAttrName = match[1]; + + if (!object.hasOwnProperty(tmplAttrName)) { + return; + } + + const attrVal = object[tmplAttrName]; + tmpVariable = tmpVariable.replace(tmplVar, attrVal); + match = templateRegex.exec(variable); + } + return tmpVariable; + } +} + +export function getPropertyValue(obj, key) { + try { + return _.reduce(key.split('.'), (acc, el) => acc[el], obj); + } catch (err) { + return undefined; + } +} + +export function getLdapUsername(ldapUser) { + const usernameField = LDAP.settings_get('LDAP_USERNAME_FIELD'); + + if (usernameField.indexOf('#{') > -1) { + return usernameField.replace(/#{(.+?)}/g, function(match, field) { + return ldapUser.getLDAPValue(field); + }); + } + + return ldapUser.getLDAPValue(usernameField); +} + +export function getLdapEmail(ldapUser) { + const emailField = LDAP.settings_get('LDAP_EMAIL_FIELD'); + + if (emailField.indexOf('#{') > -1) { + return emailField.replace(/#{(.+?)}/g, function(match, field) { + return ldapUser.getLDAPValue(field); + }); + } + + return ldapUser.getLDAPValue(emailField); +} + +export function getLdapFullname(ldapUser) { + const fullnameField = LDAP.settings_get('LDAP_FULLNAME_FIELD'); + if (fullnameField.indexOf('#{') > -1) { + return fullnameField.replace(/#{(.+?)}/g, function(match, field) { + return ldapUser.getLDAPValue(field); + }); + } + return ldapUser.getLDAPValue(fullnameField); +} + +export function getLdapUserUniqueID(ldapUser) { + let Unique_Identifier_Field = LDAP.settings_get('LDAP_UNIQUE_IDENTIFIER_FIELD'); + + if (Unique_Identifier_Field !== '') { + Unique_Identifier_Field = Unique_Identifier_Field.replace(/\s/g, '').split(','); + } else { + Unique_Identifier_Field = []; + } + + let User_Search_Field = LDAP.settings_get('LDAP_USER_SEARCH_FIELD'); + + if (User_Search_Field !== '') { + User_Search_Field = User_Search_Field.replace(/\s/g, '').split(','); + } else { + User_Search_Field = []; + } + + Unique_Identifier_Field = Unique_Identifier_Field.concat(User_Search_Field); + + if (Unique_Identifier_Field.length > 0) { + Unique_Identifier_Field = Unique_Identifier_Field.find((field) => { + return !_.isEmpty(ldapUser._raw.getLDAPValue(field)); + }); + if (Unique_Identifier_Field) { + log_debug(`Identifying user with: ${ Unique_Identifier_Field}`); + Unique_Identifier_Field = { + attribute: Unique_Identifier_Field, + value: ldapUser._raw.getLDAPValue(Unique_Identifier_Field).toString('hex'), + }; + } + return Unique_Identifier_Field; + } +} + +export function getDataToSyncUserData(ldapUser, user) { + const syncUserData = LDAP.settings_get('LDAP_SYNC_USER_DATA'); + const syncUserDataFieldMap = LDAP.settings_get('LDAP_SYNC_USER_DATA_FIELDMAP').trim(); + + const userData = {}; + + if (syncUserData && syncUserDataFieldMap) { + const whitelistedUserFields = ['email', 'name', 'customFields']; + const fieldMap = JSON.parse(syncUserDataFieldMap); + const emailList = []; + _.map(fieldMap, function(userField, ldapField) { + log_debug(`Mapping field ${ldapField} -> ${userField}`); + switch (userField) { + case 'email': + if (!ldapUser.hasOwnProperty(ldapField)) { + log_debug(`user does not have attribute: ${ ldapField }`); + return; + } + + if (_.isObject(ldapUser[ldapField])) { + _.map(ldapUser[ldapField], function(item) { + emailList.push({ address: item, verified: true }); + }); + } else { + emailList.push({ address: ldapUser[ldapField], verified: true }); + } + break; + + default: + const [outerKey, innerKeys] = userField.split(/\.(.+)/); + + if (!_.find(whitelistedUserFields, (el) => el === outerKey)) { + log_debug(`user attribute not whitelisted: ${ userField }`); + return; + } + + if (outerKey === 'customFields') { + let customFieldsMeta; + + try { + customFieldsMeta = JSON.parse(LDAP.settings_get('Accounts_CustomFields')); + } catch (e) { + log_debug('Invalid JSON for Custom Fields'); + return; + } + + if (!getPropertyValue(customFieldsMeta, innerKeys)) { + log_debug(`user attribute does not exist: ${ userField }`); + return; + } + } + + const tmpUserField = getPropertyValue(user, userField); + const tmpLdapField = templateVarHandler(ldapField, ldapUser); + + if (tmpLdapField && tmpUserField !== tmpLdapField) { + // creates the object structure instead of just assigning 'tmpLdapField' to + // 'userData[userField]' in order to avoid the "cannot use the part (...) + // to traverse the element" (MongoDB) error that can happen. Do not handle + // arrays. + // TODO: Find a better solution. + const dKeys = userField.split('.'); + const lastKey = _.last(dKeys); + _.reduce(dKeys, (obj, currKey) => + (currKey === lastKey) + ? obj[currKey] = tmpLdapField + : obj[currKey] = obj[currKey] || {} + , userData); + log_debug(`user.${ userField } changed to: ${ tmpLdapField }`); + } + } + }); + + if (emailList.length > 0) { + if (JSON.stringify(user.emails) !== JSON.stringify(emailList)) { + userData.emails = emailList; + } + } + } + + const uniqueId = getLdapUserUniqueID(ldapUser); + + if (uniqueId && (!user.services || !user.services.ldap || user.services.ldap.id !== uniqueId.value || user.services.ldap.idAttribute !== uniqueId.attribute)) { + userData['services.ldap.id'] = uniqueId.value; + userData['services.ldap.idAttribute'] = uniqueId.attribute; + } + + if (user.authenticationMethod !== 'ldap') { + userData.ldap = true; + } + + if (_.size(userData)) { + return userData; + } +} + + +export function syncUserData(user, ldapUser) { + log_info('Syncing user data'); + log_debug('user', {'email': user.email, '_id': user._id}); + // log_debug('ldapUser', ldapUser.object); + + if (LDAP.settings_get('LDAP_USERNAME_FIELD') !== '') { + const username = slug(getLdapUsername(ldapUser)); + if (user && user._id && username !== user.username) { + log_info('Syncing user username', user.username, '->', username); + Meteor.users.findOne({ _id: user._id }, { $set: { username }}); + } + } + + if (LDAP.settings_get('LDAP_FULLNAME_FIELD') !== '') { + const fullname= getLdapFullname(ldapUser); + log_debug('fullname=',fullname); + if (user && user._id && fullname !== '') { + log_info('Syncing user fullname:', fullname); + Meteor.users.update({ _id: user._id }, { $set: { 'profile.fullname' : fullname, }}); + } + } + +} + +export function addLdapUser(ldapUser, username, password) { + const uniqueId = getLdapUserUniqueID(ldapUser); + + const userObject = { + }; + + if (username) { + userObject.username = username; + } + + const userData = getDataToSyncUserData(ldapUser, {}); + + if (userData && userData.emails && userData.emails[0] && userData.emails[0].address) { + if (Array.isArray(userData.emails[0].address)) { + userObject.email = userData.emails[0].address[0]; + } else { + userObject.email = userData.emails[0].address; + } + } else if (ldapUser.mail && ldapUser.mail.indexOf('@') > -1) { + userObject.email = ldapUser.mail; + } else if (LDAP.settings_get('LDAP_DEFAULT_DOMAIN') !== '') { + userObject.email = `${ username || uniqueId.value }@${ LDAP.settings_get('LDAP_DEFAULT_DOMAIN') }`; + } else { + const error = new Meteor.Error('LDAP-login-error', 'LDAP Authentication succeded, there is no email to create an account. Have you tried setting your Default Domain in LDAP Settings?'); + log_error(error); + throw error; + } + + log_debug('New user data', userObject); + + if (password) { + userObject.password = password; + } + + try { + // This creates the account with password service + userObject.ldap = true; + userObject._id = Accounts.createUser(userObject); + + // Add the services.ldap identifiers + Meteor.users.update({ _id: userObject._id }, { + $set: { + 'services.ldap': { id: uniqueId.value }, + 'emails.0.verified': true, + 'authenticationMethod': 'ldap', + }}); + } catch (error) { + log_error('Error creating user', error); + return error; + } + + syncUserData(userObject, ldapUser); + + return { + userId: userObject._id, + }; +} + +export function importNewUsers(ldap) { + if (LDAP.settings_get('LDAP_ENABLE') !== true) { + log_error('Can\'t run LDAP Import, LDAP is disabled'); + return; + } + + if (!ldap) { + ldap = new LDAP(); + ldap.connectSync(); + } + + let count = 0; + ldap.searchUsersSync('*', Meteor.bindEnvironment((error, ldapUsers, {next, end} = {}) => { + if (error) { + throw error; + } + + ldapUsers.forEach((ldapUser) => { + count++; + + const uniqueId = getLdapUserUniqueID(ldapUser); + // Look to see if user already exists + const userQuery = { + 'services.ldap.id': uniqueId.value, + }; + + log_debug('userQuery', userQuery); + + let username; + if (LDAP.settings_get('LDAP_USERNAME_FIELD') !== '') { + username = slug(getLdapUsername(ldapUser)); + } + + // Add user if it was not added before + let user = Meteor.users.findOne(userQuery); + + if (!user && username && LDAP.settings_get('LDAP_MERGE_EXISTING_USERS') === true) { + const userQuery = { + username, + }; + + log_debug('userQuery merge', userQuery); + + user = Meteor.users.findOne(userQuery); + if (user) { + syncUserData(user, ldapUser); + } + } + + if (!user) { + addLdapUser(ldapUser, username); + } + + if (count % 100 === 0) { + log_info('Import running. Users imported until now:', count); + } + }); + + if (end) { + log_info('Import finished. Users imported:', count); + } + + next(count); + })); +} + +function sync() { + if (LDAP.settings_get('LDAP_ENABLE') !== true) { + return; + } + + const ldap = new LDAP(); + + try { + ldap.connectSync(); + + let users; + if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED') === true) { + users = Meteor.users.find({ 'services.ldap': { $exists: true }}); + } + + if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_IMPORT_NEW_USERS') === true) { + importNewUsers(ldap); + } + + if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_KEEP_EXISTANT_USERS_UPDATED') === true) { + users.forEach(function(user) { + let ldapUser; + + if (user.services && user.services.ldap && user.services.ldap.id) { + ldapUser = ldap.getUserByIdSync(user.services.ldap.id, user.services.ldap.idAttribute); + } else { + ldapUser = ldap.getUserByUsernameSync(user.username); + } + + if (ldapUser) { + syncUserData(user, ldapUser); + } else { + log_info('Can\'t sync user', user.username); + } + }); + } + } catch (error) { + log_error(error); + return error; + } + return true; +} + +const jobName = 'LDAP_Sync'; + +const addCronJob = _.debounce(Meteor.bindEnvironment(function addCronJobDebounced() { + if (LDAP.settings_get('LDAP_BACKGROUND_SYNC') !== true) { + log_info('Disabling LDAP Background Sync'); + if (SyncedCron.nextScheduledAtDate(jobName)) { + SyncedCron.remove(jobName); + } + return; + } + + if (LDAP.settings_get('LDAP_BACKGROUND_SYNC_INTERVAL')) { + log_info('Enabling LDAP Background Sync'); + SyncedCron.add({ + name: jobName, + schedule: (parser) => parser.text(LDAP.settings_get('LDAP_BACKGROUND_SYNC_INTERVAL')), + job() { + sync(); + }, + }); + SyncedCron.start(); + } +}), 500); + +Meteor.startup(() => { + Meteor.defer(() => { + LDAP.settings_get('LDAP_BACKGROUND_SYNC', addCronJob); + LDAP.settings_get('LDAP_BACKGROUND_SYNC_INTERVAL', addCronJob); + }); +}); diff --git a/packages/wekan-ldap/server/syncUser.js b/packages/wekan-ldap/server/syncUser.js new file mode 100644 index 00000000..763ea836 --- /dev/null +++ b/packages/wekan-ldap/server/syncUser.js @@ -0,0 +1,29 @@ +import {importNewUsers} from './sync'; +import LDAP from './ldap'; + +Meteor.methods({ + ldap_sync_now() { + const user = Meteor.user(); + if (!user) { + throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'ldap_sync_users' }); + } + + //TODO: This needs to be fixed - security issue -> alanning:meteor-roles + //if (!RocketChat.authz.hasRole(user._id, 'admin')) { + // throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'ldap_sync_users' }); + //} + + if (LDAP.settings_get('LDAP_ENABLE') !== true) { + throw new Meteor.Error('LDAP_disabled'); + } + + this.unblock(); + + importNewUsers(); + + return { + message: 'Sync_in_progress', + params: [], + }; + }, +}); diff --git a/packages/wekan-ldap/server/testConnection.js b/packages/wekan-ldap/server/testConnection.js new file mode 100644 index 00000000..02866ce5 --- /dev/null +++ b/packages/wekan-ldap/server/testConnection.js @@ -0,0 +1,39 @@ +import LDAP from './ldap'; + +Meteor.methods({ + ldap_test_connection() { + const user = Meteor.user(); + if (!user) { + throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'ldap_test_connection' }); + } + + //TODO: This needs to be fixed - security issue -> alanning:meteor-roles + //if (!RocketChat.authz.hasRole(user._id, 'admin')) { + // throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'ldap_test_connection' }); + //} + + if (LDAP.settings_get(LDAP_ENABLE) !== true) { + throw new Meteor.Error('LDAP_disabled'); + } + + let ldap; + try { + ldap = new LDAP(); + ldap.connectSync(); + } catch (error) { + console.log(error); + throw new Meteor.Error(error.message); + } + + try { + ldap.bindIfNecessary(); + } catch (error) { + throw new Meteor.Error(error.name || error.message); + } + + return { + message: 'Connection_success', + params: [], + }; + }, +}); diff --git a/packages/wekan-oidc/.gitignore b/packages/wekan-oidc/.gitignore new file mode 100644 index 00000000..5379d4c3 --- /dev/null +++ b/packages/wekan-oidc/.gitignore @@ -0,0 +1 @@ +.versions diff --git a/packages/wekan-oidc/LICENSE.txt b/packages/wekan-oidc/LICENSE.txt new file mode 100644 index 00000000..c7be3264 --- /dev/null +++ b/packages/wekan-oidc/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (C) 2016 SWITCH + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + diff --git a/packages/wekan-oidc/README.md b/packages/wekan-oidc/README.md new file mode 100644 index 00000000..8948971c --- /dev/null +++ b/packages/wekan-oidc/README.md @@ -0,0 +1,7 @@ +# salleman:oidc package + +A Meteor implementation of OpenID Connect Login flow + +## Usage and Documentation + +Look at the `salleman:accounts-oidc` package for the documentation about using OpenID Connect with Meteor. diff --git a/packages/wekan-oidc/oidc_client.js b/packages/wekan-oidc/oidc_client.js new file mode 100644 index 00000000..744bd841 --- /dev/null +++ b/packages/wekan-oidc/oidc_client.js @@ -0,0 +1,68 @@ +Oidc = {}; + +// Request OpenID Connect credentials for the user +// @param options {optional} +// @param credentialRequestCompleteCallback {Function} Callback function to call on +// completion. Takes one argument, credentialToken on success, or Error on +// error. +Oidc.requestCredential = function (options, credentialRequestCompleteCallback) { + // support both (options, callback) and (callback). + if (!credentialRequestCompleteCallback && typeof options === 'function') { + credentialRequestCompleteCallback = options; + options = {}; + } + + var config = ServiceConfiguration.configurations.findOne({service: 'oidc'}); + if (!config) { + credentialRequestCompleteCallback && credentialRequestCompleteCallback( + new ServiceConfiguration.ConfigError('Service oidc not configured.')); + return; + } + + var credentialToken = Random.secret(); + var loginStyle = OAuth._loginStyle('oidc', config, options); + var scope = config.requestPermissions || ['openid', 'profile', 'email']; + + // options + options = options || {}; + options.client_id = config.clientId; + options.response_type = options.response_type || 'code'; + options.redirect_uri = OAuth._redirectUri('oidc', config); + options.state = OAuth._stateParam(loginStyle, credentialToken, options.redirectUrl); + options.scope = scope.join(' '); + + if (config.loginStyle && config.loginStyle == 'popup') { + options.display = 'popup'; + } + + var loginUrl = config.serverUrl + config.authorizationEndpoint; + // check if the loginUrl already contains a "?" + var first = loginUrl.indexOf('?') === -1; + for (var k in options) { + if (first) { + loginUrl += '?'; + first = false; + } + else { + loginUrl += '&' + } + loginUrl += encodeURIComponent(k) + '=' + encodeURIComponent(options[k]); + } + + //console.log('XXX: loginURL: ' + loginUrl) + + options.popupOptions = options.popupOptions || {}; + var popupOptions = { + width: options.popupOptions.width || 320, + height: options.popupOptions.height || 450 + }; + + OAuth.launchLogin({ + loginService: 'oidc', + loginStyle: loginStyle, + loginUrl: loginUrl, + credentialRequestCompleteCallback: credentialRequestCompleteCallback, + credentialToken: credentialToken, + popupOptions: popupOptions, + }); +}; diff --git a/packages/wekan-oidc/oidc_configure.html b/packages/wekan-oidc/oidc_configure.html new file mode 100644 index 00000000..49282fc1 --- /dev/null +++ b/packages/wekan-oidc/oidc_configure.html @@ -0,0 +1,6 @@ +<template name="configureLoginServiceDialogForOidc"> + <p> + You'll need to create an OpenID Connect client configuration with your provider. + Set App Callbacks URLs to: <span class="url">{{siteUrl}}_oauth/oidc</span> + </p> +</template> diff --git a/packages/wekan-oidc/oidc_configure.js b/packages/wekan-oidc/oidc_configure.js new file mode 100644 index 00000000..5eedaa04 --- /dev/null +++ b/packages/wekan-oidc/oidc_configure.js @@ -0,0 +1,17 @@ +Template.configureLoginServiceDialogForOidc.helpers({ + siteUrl: function () { + return Meteor.absoluteUrl(); + } +}); + +Template.configureLoginServiceDialogForOidc.fields = function () { + return [ + { property: 'clientId', label: 'Client ID'}, + { property: 'secret', label: 'Client Secret'}, + { property: 'serverUrl', label: 'OIDC Server URL'}, + { property: 'authorizationEndpoint', label: 'Authorization Endpoint'}, + { property: 'tokenEndpoint', label: 'Token Endpoint'}, + { property: 'userinfoEndpoint', label: 'Userinfo Endpoint'}, + { property: 'idTokenWhitelistFields', label: 'Id Token Fields'} + ]; +}; diff --git a/packages/wekan-oidc/oidc_server.js b/packages/wekan-oidc/oidc_server.js new file mode 100644 index 00000000..fb948c52 --- /dev/null +++ b/packages/wekan-oidc/oidc_server.js @@ -0,0 +1,143 @@ +Oidc = {}; + +OAuth.registerService('oidc', 2, null, function (query) { + + var debug = process.env.DEBUG || false; + var token = getToken(query); + if (debug) console.log('XXX: register token:', token); + + var accessToken = token.access_token || token.id_token; + var expiresAt = (+new Date) + (1000 * parseInt(token.expires_in, 10)); + + var userinfo = getUserInfo(accessToken); + if (debug) console.log('XXX: userinfo:', userinfo); + + var serviceData = {}; + serviceData.id = userinfo[process.env.OAUTH2_ID_MAP] || userinfo[id]; + serviceData.username = userinfo[process.env.OAUTH2_USERNAME_MAP] || userinfo[uid]; + serviceData.fullname = userinfo[process.env.OAUTH2_FULLNAME_MAP] || userinfo[displayName]; + serviceData.accessToken = accessToken; + serviceData.expiresAt = expiresAt; + serviceData.email = userinfo[process.env.OAUTH2_EMAIL_MAP] || userinfo[email]; + + if (accessToken) { + var tokenContent = getTokenContent(accessToken); + var fields = _.pick(tokenContent, getConfiguration().idTokenWhitelistFields); + _.extend(serviceData, fields); + } + + if (token.refresh_token) + serviceData.refreshToken = token.refresh_token; + if (debug) console.log('XXX: serviceData:', serviceData); + + var profile = {}; + profile.name = userinfo[process.env.OAUTH2_FULLNAME_MAP] || userinfo[displayName]; + profile.email = userinfo[process.env.OAUTH2_EMAIL_MAP] || userinfo[email]; + if (debug) console.log('XXX: profile:', profile); + + return { + serviceData: serviceData, + options: { profile: profile } + }; +}); + +var userAgent = "Meteor"; +if (Meteor.release) { + userAgent += "/" + Meteor.release; +} + +var getToken = function (query) { + var debug = process.env.DEBUG || false; + var config = getConfiguration(); + var serverTokenEndpoint = config.serverUrl + config.tokenEndpoint; + var response; + + try { + response = HTTP.post( + serverTokenEndpoint, + { + headers: { + Accept: 'application/json', + "User-Agent": userAgent + }, + params: { + code: query.code, + client_id: config.clientId, + client_secret: OAuth.openSecret(config.secret), + redirect_uri: OAuth._redirectUri('oidc', config), + grant_type: 'authorization_code', + state: query.state + } + } + ); + } catch (err) { + throw _.extend(new Error("Failed to get token from OIDC " + serverTokenEndpoint + ": " + err.message), + { response: err.response }); + } + if (response.data.error) { + // if the http response was a json object with an error attribute + throw new Error("Failed to complete handshake with OIDC " + serverTokenEndpoint + ": " + response.data.error); + } else { + if (debug) console.log('XXX: getToken response: ', response.data); + return response.data; + } +}; + +var getUserInfo = function (accessToken) { + var debug = process.env.DEBUG || false; + var config = getConfiguration(); + // Some userinfo endpoints use a different base URL than the authorization or token endpoints. + // This logic allows the end user to override the setting by providing the full URL to userinfo in their config. + if (config.userinfoEndpoint.includes("https://")) { + var serverUserinfoEndpoint = config.userinfoEndpoint; + } else { + var serverUserinfoEndpoint = config.serverUrl + config.userinfoEndpoint; + } + var response; + try { + response = HTTP.get( + serverUserinfoEndpoint, + { + headers: { + "User-Agent": userAgent, + "Authorization": "Bearer " + accessToken + } + } + ); + } catch (err) { + throw _.extend(new Error("Failed to fetch userinfo from OIDC " + serverUserinfoEndpoint + ": " + err.message), + {response: err.response}); + } + if (debug) console.log('XXX: getUserInfo response: ', response.data); + return response.data; +}; + +var getConfiguration = function () { + var config = ServiceConfiguration.configurations.findOne({ service: 'oidc' }); + if (!config) { + throw new ServiceConfiguration.ConfigError('Service oidc not configured.'); + } + return config; +}; + +var getTokenContent = function (token) { + var content = null; + if (token) { + try { + var parts = token.split('.'); + var header = JSON.parse(new Buffer(parts[0], 'base64').toString()); + content = JSON.parse(new Buffer(parts[1], 'base64').toString()); + var signature = new Buffer(parts[2], 'base64'); + var signed = parts[0] + '.' + parts[1]; + } catch (err) { + this.content = { + exp: 0 + }; + } + } + return content; +} + +Oidc.retrieveCredential = function (credentialToken, credentialSecret) { + return OAuth.retrieveCredential(credentialToken, credentialSecret); +}; diff --git a/packages/wekan-oidc/package.js b/packages/wekan-oidc/package.js new file mode 100644 index 00000000..273ef612 --- /dev/null +++ b/packages/wekan-oidc/package.js @@ -0,0 +1,23 @@ +Package.describe({ + summary: "OpenID Connect (OIDC) flow for Meteor", + version: "1.0.12", + name: "wekan-oidc", + git: "https://github.com/wekan/wekan-oidc.git", +}); + +Package.onUse(function(api) { + api.use('oauth2@1.1.0', ['client', 'server']); + api.use('oauth@1.1.0', ['client', 'server']); + api.use('http@1.1.0', ['server']); + api.use('underscore@1.0.0', 'client'); + api.use('templating@1.1.0', 'client'); + api.use('random@1.0.0', 'client'); + api.use('service-configuration@1.0.0', ['client', 'server']); + + api.export('Oidc'); + + api.addFiles(['oidc_configure.html', 'oidc_configure.js'], 'client'); + + api.addFiles('oidc_server.js', 'server'); + api.addFiles('oidc_client.js', 'client'); +}); diff --git a/packages/wekan-scrollbar/.gitignore b/packages/wekan-scrollbar/.gitignore new file mode 100644 index 00000000..8d195847 --- /dev/null +++ b/packages/wekan-scrollbar/.gitignore @@ -0,0 +1,14 @@ +.build* + +# Ignore OS generated files +.DS_Store +.DS_Store? +._* +.Trashes +Thumbs.db +ehthumbs.db + +#Ignore temp files +*~ + +.idea \ No newline at end of file diff --git a/packages/wekan-scrollbar/LICENSE b/packages/wekan-scrollbar/LICENSE new file mode 100644 index 00000000..c2d69158 --- /dev/null +++ b/packages/wekan-scrollbar/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2019 The Wekan Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/wekan-scrollbar/jquery.mCustomScrollbar.css b/packages/wekan-scrollbar/jquery.mCustomScrollbar.css new file mode 100644 index 00000000..45152c1b --- /dev/null +++ b/packages/wekan-scrollbar/jquery.mCustomScrollbar.css @@ -0,0 +1,1267 @@ +/* +== malihu jquery custom scrollbar plugin == +Plugin URI: http://manos.malihu.gr/jquery-custom-content-scroller +*/ + + + +/* +CONTENTS: + 1. BASIC STYLE - Plugin's basic/essential CSS properties (normally, should not be edited). + 2. VERTICAL SCROLLBAR - Positioning and dimensions of vertical scrollbar. + 3. HORIZONTAL SCROLLBAR - Positioning and dimensions of horizontal scrollbar. + 4. VERTICAL AND HORIZONTAL SCROLLBARS - Positioning and dimensions of 2-axis scrollbars. + 5. TRANSITIONS - CSS3 transitions for hover events, auto-expanded and auto-hidden scrollbars. + 6. SCROLLBAR COLORS, OPACITY AND BACKGROUNDS + 6.1 THEMES - Scrollbar colors, opacity, dimensions, backgrounds etc. via ready-to-use themes. +*/ + + + +/* +------------------------------------------------------------------------------------------------------------------------ +1. BASIC STYLE +------------------------------------------------------------------------------------------------------------------------ +*/ + + .mCustomScrollbar{ -ms-touch-action: pinch-zoom; touch-action: pinch-zoom; /* direct pointer events to js */ } + .mCustomScrollbar.mCS_no_scrollbar, .mCustomScrollbar.mCS_touch_action{ -ms-touch-action: auto; touch-action: auto; } + + .mCustomScrollBox{ /* contains plugin's markup */ + position: relative; + overflow: hidden; + height: 100%; + max-width: 100%; + outline: none; + direction: ltr; + } + + .mCSB_container{ /* contains the original content */ + overflow: hidden; + width: auto; + height: auto; + } + + + +/* +------------------------------------------------------------------------------------------------------------------------ +2. VERTICAL SCROLLBAR +y-axis +------------------------------------------------------------------------------------------------------------------------ +*/ + + .mCSB_inside > .mCSB_container{ margin-right: 30px; } + + .mCSB_container.mCS_no_scrollbar_y.mCS_y_hidden{ margin-right: 0; } /* non-visible scrollbar */ + + .mCS-dir-rtl > .mCSB_inside > .mCSB_container{ /* RTL direction/left-side scrollbar */ + margin-right: 0; + margin-left: 30px; + } + + .mCS-dir-rtl > .mCSB_inside > .mCSB_container.mCS_no_scrollbar_y.mCS_y_hidden{ margin-left: 0; } /* RTL direction/left-side scrollbar */ + + .mCSB_scrollTools{ /* contains scrollbar markup (draggable element, dragger rail, buttons etc.) */ + position: absolute; + width: 16px; + height: auto; + left: auto; + top: 0; + right: 0; + bottom: 0; + } + + .mCSB_outside + .mCSB_scrollTools{ right: -26px; } /* scrollbar position: outside */ + + .mCS-dir-rtl > .mCSB_inside > .mCSB_scrollTools, + .mCS-dir-rtl > .mCSB_outside + .mCSB_scrollTools{ /* RTL direction/left-side scrollbar */ + right: auto; + left: 0; + } + + .mCS-dir-rtl > .mCSB_outside + .mCSB_scrollTools{ left: -26px; } /* RTL direction/left-side scrollbar (scrollbar position: outside) */ + + .mCSB_scrollTools .mCSB_draggerContainer{ /* contains the draggable element and dragger rail markup */ + position: absolute; + top: 0; + left: 0; + bottom: 0; + right: 0; + height: auto; + } + + .mCSB_scrollTools a + .mCSB_draggerContainer{ margin: 20px 0; } + + .mCSB_scrollTools .mCSB_draggerRail{ + width: 2px; + height: 100%; + margin: 0 auto; + -webkit-border-radius: 16px; -moz-border-radius: 16px; border-radius: 16px; + } + + .mCSB_scrollTools .mCSB_dragger{ /* the draggable element */ + cursor: pointer; + width: 100%; + height: 30px; /* minimum dragger height */ + z-index: 1; + } + + .mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ /* the dragger element */ + position: relative; + width: 4px; + height: 100%; + margin: 0 auto; + -webkit-border-radius: 16px; -moz-border-radius: 16px; border-radius: 16px; + text-align: center; + } + + .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, + .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar{ width: 12px; /* auto-expanded scrollbar */ } + + .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail{ width: 8px; /* auto-expanded scrollbar */ } + + .mCSB_scrollTools .mCSB_buttonUp, + .mCSB_scrollTools .mCSB_buttonDown{ + display: block; + position: absolute; + height: 20px; + width: 100%; + overflow: hidden; + margin: 0 auto; + cursor: pointer; + } + + .mCSB_scrollTools .mCSB_buttonDown{ bottom: 0; } + + + +/* +------------------------------------------------------------------------------------------------------------------------ +3. HORIZONTAL SCROLLBAR +x-axis +------------------------------------------------------------------------------------------------------------------------ +*/ + + .mCSB_horizontal.mCSB_inside > .mCSB_container{ + margin-right: 0; + margin-bottom: 30px; + } + + .mCSB_horizontal.mCSB_outside > .mCSB_container{ min-height: 100%; } + + .mCSB_horizontal > .mCSB_container.mCS_no_scrollbar_x.mCS_x_hidden{ margin-bottom: 0; } /* non-visible scrollbar */ + + .mCSB_scrollTools.mCSB_scrollTools_horizontal{ + width: auto; + height: 16px; + top: auto; + right: 0; + bottom: 0; + left: 0; + } + + .mCustomScrollBox + .mCSB_scrollTools.mCSB_scrollTools_horizontal, + .mCustomScrollBox + .mCSB_scrollTools + .mCSB_scrollTools.mCSB_scrollTools_horizontal{ bottom: -26px; } /* scrollbar position: outside */ + + .mCSB_scrollTools.mCSB_scrollTools_horizontal a + .mCSB_draggerContainer{ margin: 0 20px; } + + .mCSB_scrollTools.mCSB_scrollTools_horizontal .mCSB_draggerRail{ + width: 100%; + height: 2px; + margin: 7px 0; + } + + .mCSB_scrollTools.mCSB_scrollTools_horizontal .mCSB_dragger{ + width: 30px; /* minimum dragger width */ + height: 100%; + left: 0; + } + + .mCSB_scrollTools.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + width: 100%; + height: 4px; + margin: 6px auto; + } + + .mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, + .mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar{ + height: 12px; /* auto-expanded scrollbar */ + margin: 2px auto; + } + + .mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail{ + height: 8px; /* auto-expanded scrollbar */ + margin: 4px 0; + } + + .mCSB_scrollTools.mCSB_scrollTools_horizontal .mCSB_buttonLeft, + .mCSB_scrollTools.mCSB_scrollTools_horizontal .mCSB_buttonRight{ + display: block; + position: absolute; + width: 20px; + height: 100%; + overflow: hidden; + margin: 0 auto; + cursor: pointer; + } + + .mCSB_scrollTools.mCSB_scrollTools_horizontal .mCSB_buttonLeft{ left: 0; } + + .mCSB_scrollTools.mCSB_scrollTools_horizontal .mCSB_buttonRight{ right: 0; } + + + +/* +------------------------------------------------------------------------------------------------------------------------ +4. VERTICAL AND HORIZONTAL SCROLLBARS +yx-axis +------------------------------------------------------------------------------------------------------------------------ +*/ + + .mCSB_container_wrapper{ + position: absolute; + height: auto; + width: auto; + overflow: hidden; + top: 0; + left: 0; + right: 0; + bottom: 0; + margin-right: 30px; + margin-bottom: 30px; + } + + .mCSB_container_wrapper > .mCSB_container{ + padding-right: 30px; + padding-bottom: 30px; + -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; + } + + .mCSB_vertical_horizontal > .mCSB_scrollTools.mCSB_scrollTools_vertical{ bottom: 20px; } + + .mCSB_vertical_horizontal > .mCSB_scrollTools.mCSB_scrollTools_horizontal{ right: 20px; } + + /* non-visible horizontal scrollbar */ + .mCSB_container_wrapper.mCS_no_scrollbar_x.mCS_x_hidden + .mCSB_scrollTools.mCSB_scrollTools_vertical{ bottom: 0; } + + /* non-visible vertical scrollbar/RTL direction/left-side scrollbar */ + .mCSB_container_wrapper.mCS_no_scrollbar_y.mCS_y_hidden + .mCSB_scrollTools ~ .mCSB_scrollTools.mCSB_scrollTools_horizontal, + .mCS-dir-rtl > .mCustomScrollBox.mCSB_vertical_horizontal.mCSB_inside > .mCSB_scrollTools.mCSB_scrollTools_horizontal{ right: 0; } + + /* RTL direction/left-side scrollbar */ + .mCS-dir-rtl > .mCustomScrollBox.mCSB_vertical_horizontal.mCSB_inside > .mCSB_scrollTools.mCSB_scrollTools_horizontal{ left: 20px; } + + /* non-visible scrollbar/RTL direction/left-side scrollbar */ + .mCS-dir-rtl > .mCustomScrollBox.mCSB_vertical_horizontal.mCSB_inside > .mCSB_container_wrapper.mCS_no_scrollbar_y.mCS_y_hidden + .mCSB_scrollTools ~ .mCSB_scrollTools.mCSB_scrollTools_horizontal{ left: 0; } + + .mCS-dir-rtl > .mCSB_inside > .mCSB_container_wrapper{ /* RTL direction/left-side scrollbar */ + margin-right: 0; + margin-left: 30px; + } + + .mCSB_container_wrapper.mCS_no_scrollbar_y.mCS_y_hidden > .mCSB_container{ padding-right: 0; } + + .mCSB_container_wrapper.mCS_no_scrollbar_x.mCS_x_hidden > .mCSB_container{ padding-bottom: 0; } + + .mCustomScrollBox.mCSB_vertical_horizontal.mCSB_inside > .mCSB_container_wrapper.mCS_no_scrollbar_y.mCS_y_hidden{ + margin-right: 0; /* non-visible scrollbar */ + margin-left: 0; + } + + /* non-visible horizontal scrollbar */ + .mCustomScrollBox.mCSB_vertical_horizontal.mCSB_inside > .mCSB_container_wrapper.mCS_no_scrollbar_x.mCS_x_hidden{ margin-bottom: 0; } + + + +/* +------------------------------------------------------------------------------------------------------------------------ +5. TRANSITIONS +------------------------------------------------------------------------------------------------------------------------ +*/ + + .mCSB_scrollTools, + .mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCSB_scrollTools .mCSB_buttonUp, + .mCSB_scrollTools .mCSB_buttonDown, + .mCSB_scrollTools .mCSB_buttonLeft, + .mCSB_scrollTools .mCSB_buttonRight{ + -webkit-transition: opacity .2s ease-in-out, background-color .2s ease-in-out; + -moz-transition: opacity .2s ease-in-out, background-color .2s ease-in-out; + -o-transition: opacity .2s ease-in-out, background-color .2s ease-in-out; + transition: opacity .2s ease-in-out, background-color .2s ease-in-out; + } + + .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger_bar, /* auto-expanded scrollbar */ + .mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerRail, + .mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger_bar, + .mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerRail{ + -webkit-transition: width .2s ease-out .2s, height .2s ease-out .2s, + margin-left .2s ease-out .2s, margin-right .2s ease-out .2s, + margin-top .2s ease-out .2s, margin-bottom .2s ease-out .2s, + opacity .2s ease-in-out, background-color .2s ease-in-out; + -moz-transition: width .2s ease-out .2s, height .2s ease-out .2s, + margin-left .2s ease-out .2s, margin-right .2s ease-out .2s, + margin-top .2s ease-out .2s, margin-bottom .2s ease-out .2s, + opacity .2s ease-in-out, background-color .2s ease-in-out; + -o-transition: width .2s ease-out .2s, height .2s ease-out .2s, + margin-left .2s ease-out .2s, margin-right .2s ease-out .2s, + margin-top .2s ease-out .2s, margin-bottom .2s ease-out .2s, + opacity .2s ease-in-out, background-color .2s ease-in-out; + transition: width .2s ease-out .2s, height .2s ease-out .2s, + margin-left .2s ease-out .2s, margin-right .2s ease-out .2s, + margin-top .2s ease-out .2s, margin-bottom .2s ease-out .2s, + opacity .2s ease-in-out, background-color .2s ease-in-out; + } + + + +/* +------------------------------------------------------------------------------------------------------------------------ +6. SCROLLBAR COLORS, OPACITY AND BACKGROUNDS +------------------------------------------------------------------------------------------------------------------------ +*/ + + /* + ---------------------------------------- + 6.1 THEMES + ---------------------------------------- + */ + + /* default theme ("light") */ + + .mCSB_scrollTools{ opacity: 0.75; filter: "alpha(opacity=75)"; -ms-filter: "alpha(opacity=75)"; } + + .mCS-autoHide > .mCustomScrollBox > .mCSB_scrollTools, + .mCS-autoHide > .mCustomScrollBox ~ .mCSB_scrollTools{ opacity: 0; filter: "alpha(opacity=0)"; -ms-filter: "alpha(opacity=0)"; } + + .mCustomScrollbar > .mCustomScrollBox > .mCSB_scrollTools.mCSB_scrollTools_onDrag, + .mCustomScrollbar > .mCustomScrollBox ~ .mCSB_scrollTools.mCSB_scrollTools_onDrag, + .mCustomScrollBox:hover > .mCSB_scrollTools, + .mCustomScrollBox:hover ~ .mCSB_scrollTools, + .mCS-autoHide:hover > .mCustomScrollBox > .mCSB_scrollTools, + .mCS-autoHide:hover > .mCustomScrollBox ~ .mCSB_scrollTools{ opacity: 1; filter: "alpha(opacity=100)"; -ms-filter: "alpha(opacity=100)"; } + + .mCSB_scrollTools .mCSB_draggerRail{ + background-color: #000; background-color: rgba(0,0,0,0.4); + filter: "alpha(opacity=40)"; -ms-filter: "alpha(opacity=40)"; + } + + .mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + background-color: #fff; background-color: rgba(255,255,255,0.75); + filter: "alpha(opacity=75)"; -ms-filter: "alpha(opacity=75)"; + } + + .mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ + background-color: #fff; background-color: rgba(255,255,255,0.85); + filter: "alpha(opacity=85)"; -ms-filter: "alpha(opacity=85)"; + } + .mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ + background-color: #fff; background-color: rgba(255,255,255,0.9); + filter: "alpha(opacity=90)"; -ms-filter: "alpha(opacity=90)"; + } + + .mCSB_scrollTools .mCSB_buttonUp, + .mCSB_scrollTools .mCSB_buttonDown, + .mCSB_scrollTools .mCSB_buttonLeft, + .mCSB_scrollTools .mCSB_buttonRight{ + background-image: url(mCSB_buttons.png); /* css sprites */ + background-repeat: no-repeat; + opacity: 0.4; filter: "alpha(opacity=40)"; -ms-filter: "alpha(opacity=40)"; + } + + .mCSB_scrollTools .mCSB_buttonUp{ + background-position: 0 0; + /* + sprites locations + light: 0 0, -16px 0, -32px 0, -48px 0, 0 -72px, -16px -72px, -32px -72px + dark: -80px 0, -96px 0, -112px 0, -128px 0, -80px -72px, -96px -72px, -112px -72px + */ + } + + .mCSB_scrollTools .mCSB_buttonDown{ + background-position: 0 -20px; + /* + sprites locations + light: 0 -20px, -16px -20px, -32px -20px, -48px -20px, 0 -92px, -16px -92px, -32px -92px + dark: -80px -20px, -96px -20px, -112px -20px, -128px -20px, -80px -92px, -96px -92px, -112 -92px + */ + } + + .mCSB_scrollTools .mCSB_buttonLeft{ + background-position: 0 -40px; + /* + sprites locations + light: 0 -40px, -20px -40px, -40px -40px, -60px -40px, 0 -112px, -20px -112px, -40px -112px + dark: -80px -40px, -100px -40px, -120px -40px, -140px -40px, -80px -112px, -100px -112px, -120px -112px + */ + } + + .mCSB_scrollTools .mCSB_buttonRight{ + background-position: 0 -56px; + /* + sprites locations + light: 0 -56px, -20px -56px, -40px -56px, -60px -56px, 0 -128px, -20px -128px, -40px -128px + dark: -80px -56px, -100px -56px, -120px -56px, -140px -56px, -80px -128px, -100px -128px, -120px -128px + */ + } + + .mCSB_scrollTools .mCSB_buttonUp:hover, + .mCSB_scrollTools .mCSB_buttonDown:hover, + .mCSB_scrollTools .mCSB_buttonLeft:hover, + .mCSB_scrollTools .mCSB_buttonRight:hover{ opacity: 0.75; filter: "alpha(opacity=75)"; -ms-filter: "alpha(opacity=75)"; } + + .mCSB_scrollTools .mCSB_buttonUp:active, + .mCSB_scrollTools .mCSB_buttonDown:active, + .mCSB_scrollTools .mCSB_buttonLeft:active, + .mCSB_scrollTools .mCSB_buttonRight:active{ opacity: 0.9; filter: "alpha(opacity=90)"; -ms-filter: "alpha(opacity=90)"; } + + + /* theme: "dark" */ + + .mCS-dark.mCSB_scrollTools .mCSB_draggerRail{ background-color: #000; background-color: rgba(0,0,0,0.15); } + + .mCS-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.75); } + + .mCS-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: rgba(0,0,0,0.85); } + + .mCS-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: rgba(0,0,0,0.9); } + + .mCS-dark.mCSB_scrollTools .mCSB_buttonUp{ background-position: -80px 0; } + + .mCS-dark.mCSB_scrollTools .mCSB_buttonDown{ background-position: -80px -20px; } + + .mCS-dark.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -80px -40px; } + + .mCS-dark.mCSB_scrollTools .mCSB_buttonRight{ background-position: -80px -56px; } + + /* ---------------------------------------- */ + + + + /* theme: "light-2", "dark-2" */ + + .mCS-light-2.mCSB_scrollTools .mCSB_draggerRail, + .mCS-dark-2.mCSB_scrollTools .mCSB_draggerRail{ + width: 4px; + background-color: #fff; background-color: rgba(255,255,255,0.1); + -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; + } + + .mCS-light-2.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-2.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + width: 4px; + background-color: #fff; background-color: rgba(255,255,255,0.75); + -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; + } + + .mCS-light-2.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-dark-2.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-light-2.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-2.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + width: 100%; + height: 4px; + margin: 6px auto; + } + + .mCS-light-2.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #fff; background-color: rgba(255,255,255,0.85); } + + .mCS-light-2.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-light-2.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #fff; background-color: rgba(255,255,255,0.9); } + + .mCS-light-2.mCSB_scrollTools .mCSB_buttonUp{ background-position: -32px 0; } + + .mCS-light-2.mCSB_scrollTools .mCSB_buttonDown{ background-position: -32px -20px; } + + .mCS-light-2.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -40px -40px; } + + .mCS-light-2.mCSB_scrollTools .mCSB_buttonRight{ background-position: -40px -56px; } + + + /* theme: "dark-2" */ + + .mCS-dark-2.mCSB_scrollTools .mCSB_draggerRail{ + background-color: #000; background-color: rgba(0,0,0,0.1); + -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; + } + + .mCS-dark-2.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + background-color: #000; background-color: rgba(0,0,0,0.75); + -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; + } + + .mCS-dark-2.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.85); } + + .mCS-dark-2.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-dark-2.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.9); } + + .mCS-dark-2.mCSB_scrollTools .mCSB_buttonUp{ background-position: -112px 0; } + + .mCS-dark-2.mCSB_scrollTools .mCSB_buttonDown{ background-position: -112px -20px; } + + .mCS-dark-2.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -120px -40px; } + + .mCS-dark-2.mCSB_scrollTools .mCSB_buttonRight{ background-position: -120px -56px; } + + /* ---------------------------------------- */ + + + + /* theme: "light-thick", "dark-thick" */ + + .mCS-light-thick.mCSB_scrollTools .mCSB_draggerRail, + .mCS-dark-thick.mCSB_scrollTools .mCSB_draggerRail{ + width: 4px; + background-color: #fff; background-color: rgba(255,255,255,0.1); + -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; + } + + .mCS-light-thick.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-thick.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + width: 6px; + background-color: #fff; background-color: rgba(255,255,255,0.75); + -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; + } + + .mCS-light-thick.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-dark-thick.mCSB_scrollTools_horizontal .mCSB_draggerRail{ + width: 100%; + height: 4px; + margin: 6px 0; + } + + .mCS-light-thick.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-thick.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + width: 100%; + height: 6px; + margin: 5px auto; + } + + .mCS-light-thick.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #fff; background-color: rgba(255,255,255,0.85); } + + .mCS-light-thick.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-light-thick.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #fff; background-color: rgba(255,255,255,0.9); } + + .mCS-light-thick.mCSB_scrollTools .mCSB_buttonUp{ background-position: -16px 0; } + + .mCS-light-thick.mCSB_scrollTools .mCSB_buttonDown{ background-position: -16px -20px; } + + .mCS-light-thick.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -20px -40px; } + + .mCS-light-thick.mCSB_scrollTools .mCSB_buttonRight{ background-position: -20px -56px; } + + + /* theme: "dark-thick" */ + + .mCS-dark-thick.mCSB_scrollTools .mCSB_draggerRail{ + background-color: #000; background-color: rgba(0,0,0,0.1); + -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; + } + + .mCS-dark-thick.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + background-color: #000; background-color: rgba(0,0,0,0.75); + -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; + } + + .mCS-dark-thick.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.85); } + + .mCS-dark-thick.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-dark-thick.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.9); } + + .mCS-dark-thick.mCSB_scrollTools .mCSB_buttonUp{ background-position: -96px 0; } + + .mCS-dark-thick.mCSB_scrollTools .mCSB_buttonDown{ background-position: -96px -20px; } + + .mCS-dark-thick.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -100px -40px; } + + .mCS-dark-thick.mCSB_scrollTools .mCSB_buttonRight{ background-position: -100px -56px; } + + /* ---------------------------------------- */ + + + + /* theme: "light-thin", "dark-thin" */ + + .mCS-light-thin.mCSB_scrollTools .mCSB_draggerRail{ background-color: #fff; background-color: rgba(255,255,255,0.1); } + + .mCS-light-thin.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-thin.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ width: 2px; } + + .mCS-light-thin.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-dark-thin.mCSB_scrollTools_horizontal .mCSB_draggerRail{ width: 100%; } + + .mCS-light-thin.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-thin.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + width: 100%; + height: 2px; + margin: 7px auto; + } + + + /* theme "dark-thin" */ + + .mCS-dark-thin.mCSB_scrollTools .mCSB_draggerRail{ background-color: #000; background-color: rgba(0,0,0,0.15); } + + .mCS-dark-thin.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.75); } + + .mCS-dark-thin.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.85); } + + .mCS-dark-thin.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-dark-thin.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.9); } + + .mCS-dark-thin.mCSB_scrollTools .mCSB_buttonUp{ background-position: -80px 0; } + + .mCS-dark-thin.mCSB_scrollTools .mCSB_buttonDown{ background-position: -80px -20px; } + + .mCS-dark-thin.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -80px -40px; } + + .mCS-dark-thin.mCSB_scrollTools .mCSB_buttonRight{ background-position: -80px -56px; } + + /* ---------------------------------------- */ + + + + /* theme "rounded", "rounded-dark", "rounded-dots", "rounded-dots-dark" */ + + .mCS-rounded.mCSB_scrollTools .mCSB_draggerRail{ background-color: #fff; background-color: rgba(255,255,255,0.15); } + + .mCS-rounded.mCSB_scrollTools .mCSB_dragger, + .mCS-rounded-dark.mCSB_scrollTools .mCSB_dragger, + .mCS-rounded-dots.mCSB_scrollTools .mCSB_dragger, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_dragger{ height: 14px; } + + .mCS-rounded.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dots.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + width: 14px; + margin: 0 1px; + } + + .mCS-rounded.mCSB_scrollTools_horizontal .mCSB_dragger, + .mCS-rounded-dark.mCSB_scrollTools_horizontal .mCSB_dragger, + .mCS-rounded-dots.mCSB_scrollTools_horizontal .mCSB_dragger, + .mCS-rounded-dots-dark.mCSB_scrollTools_horizontal .mCSB_dragger{ width: 14px; } + + .mCS-rounded.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dots.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dots-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + height: 14px; + margin: 1px 0; + } + + .mCS-rounded.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, + .mCS-rounded.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dark.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, + .mCS-rounded-dark.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar{ + width: 16px; /* auto-expanded scrollbar */ + height: 16px; + margin: -1px 0; + } + + .mCS-rounded.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-rounded.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail, + .mCS-rounded-dark.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-rounded-dark.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail{ width: 4px; /* auto-expanded scrollbar */ } + + .mCS-rounded.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, + .mCS-rounded.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dark.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded .mCSB_dragger_bar, + .mCS-rounded-dark.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_dragger .mCSB_dragger_bar{ + height: 16px; /* auto-expanded scrollbar */ + width: 16px; + margin: 0 -1px; + } + + .mCS-rounded.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-rounded.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail, + .mCS-rounded-dark.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-rounded-dark.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail{ + height: 4px; /* auto-expanded scrollbar */ + margin: 6px 0; + } + + .mCS-rounded.mCSB_scrollTools .mCSB_buttonUp{ background-position: 0 -72px; } + + .mCS-rounded.mCSB_scrollTools .mCSB_buttonDown{ background-position: 0 -92px; } + + .mCS-rounded.mCSB_scrollTools .mCSB_buttonLeft{ background-position: 0 -112px; } + + .mCS-rounded.mCSB_scrollTools .mCSB_buttonRight{ background-position: 0 -128px; } + + + /* theme "rounded-dark", "rounded-dots-dark" */ + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.75); } + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_draggerRail{ background-color: #000; background-color: rgba(0,0,0,0.15); } + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.85); } + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-rounded-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.9); } + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_buttonUp{ background-position: -80px -72px; } + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_buttonDown{ background-position: -80px -92px; } + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -80px -112px; } + + .mCS-rounded-dark.mCSB_scrollTools .mCSB_buttonRight{ background-position: -80px -128px; } + + + /* theme "rounded-dots", "rounded-dots-dark" */ + + .mCS-rounded-dots.mCSB_scrollTools_vertical .mCSB_draggerRail, + .mCS-rounded-dots-dark.mCSB_scrollTools_vertical .mCSB_draggerRail{ width: 4px; } + + .mCS-rounded-dots.mCSB_scrollTools .mCSB_draggerRail, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_draggerRail, + .mCS-rounded-dots.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-rounded-dots-dark.mCSB_scrollTools_horizontal .mCSB_draggerRail{ + background-color: transparent; + background-position: center; + } + + .mCS-rounded-dots.mCSB_scrollTools .mCSB_draggerRail, + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_draggerRail{ + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAANElEQVQYV2NkIAAYiVbw//9/Y6DiM1ANJoyMjGdBbLgJQAX/kU0DKgDLkaQAvxW4HEvQFwCRcxIJK1XznAAAAABJRU5ErkJggg=="); + background-repeat: repeat-y; + opacity: 0.3; + filter: "alpha(opacity=30)"; -ms-filter: "alpha(opacity=30)"; + } + + .mCS-rounded-dots.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-rounded-dots-dark.mCSB_scrollTools_horizontal .mCSB_draggerRail{ + height: 4px; + margin: 6px 0; + background-repeat: repeat-x; + } + + .mCS-rounded-dots.mCSB_scrollTools .mCSB_buttonUp{ background-position: -16px -72px; } + + .mCS-rounded-dots.mCSB_scrollTools .mCSB_buttonDown{ background-position: -16px -92px; } + + .mCS-rounded-dots.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -20px -112px; } + + .mCS-rounded-dots.mCSB_scrollTools .mCSB_buttonRight{ background-position: -20px -128px; } + + + /* theme "rounded-dots-dark" */ + + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_draggerRail{ + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAALElEQVQYV2NkIAAYSVFgDFR8BqrBBEifBbGRTfiPZhpYjiQFBK3A6l6CvgAAE9kGCd1mvgEAAAAASUVORK5CYII="); + } + + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_buttonUp{ background-position: -96px -72px; } + + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_buttonDown{ background-position: -96px -92px; } + + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -100px -112px; } + + .mCS-rounded-dots-dark.mCSB_scrollTools .mCSB_buttonRight{ background-position: -100px -128px; } + + /* ---------------------------------------- */ + + + + /* theme "3d", "3d-dark", "3d-thick", "3d-thick-dark" */ + + .mCS-3d.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + background-repeat: repeat-y; + background-image: -moz-linear-gradient(left, rgba(255,255,255,0.5) 0%, rgba(255,255,255,0) 100%); + background-image: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(255,255,255,0.5)), color-stop(100%,rgba(255,255,255,0))); + background-image: -webkit-linear-gradient(left, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + background-image: -o-linear-gradient(left, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + background-image: -ms-linear-gradient(left, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + background-image: linear-gradient(to right, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + } + + .mCS-3d.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + background-repeat: repeat-x; + background-image: -moz-linear-gradient(top, rgba(255,255,255,0.5) 0%, rgba(255,255,255,0) 100%); + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0.5)), color-stop(100%,rgba(255,255,255,0))); + background-image: -webkit-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + background-image: -o-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + background-image: -ms-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + background-image: linear-gradient(to bottom, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%); + } + + + /* theme "3d", "3d-dark" */ + + .mCS-3d.mCSB_scrollTools_vertical .mCSB_dragger, + .mCS-3d-dark.mCSB_scrollTools_vertical .mCSB_dragger{ height: 70px; } + + .mCS-3d.mCSB_scrollTools_horizontal .mCSB_dragger, + .mCS-3d-dark.mCSB_scrollTools_horizontal .mCSB_dragger{ width: 70px; } + + .mCS-3d.mCSB_scrollTools, + .mCS-3d-dark.mCSB_scrollTools{ + opacity: 1; + filter: "alpha(opacity=30)"; -ms-filter: "alpha(opacity=30)"; + } + + .mCS-3d.mCSB_scrollTools .mCSB_draggerRail, + .mCS-3d.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools .mCSB_draggerRail, + .mCS-3d-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ -webkit-border-radius: 16px; -moz-border-radius: 16px; border-radius: 16px; } + + .mCS-3d.mCSB_scrollTools .mCSB_draggerRail, + .mCS-3d-dark.mCSB_scrollTools .mCSB_draggerRail{ + width: 8px; + background-color: #000; background-color: rgba(0,0,0,0.2); + box-shadow: inset 1px 0 1px rgba(0,0,0,0.5), inset -1px 0 1px rgba(255,255,255,0.2); + } + + .mCS-3d.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar, + .mCS-3d.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-3d.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #555; } + + .mCS-3d.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ width: 8px; } + + .mCS-3d.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-3d-dark.mCSB_scrollTools_horizontal .mCSB_draggerRail{ + width: 100%; + height: 8px; + margin: 4px 0; + box-shadow: inset 0 1px 1px rgba(0,0,0,0.5), inset 0 -1px 1px rgba(255,255,255,0.2); + } + + .mCS-3d.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + width: 100%; + height: 8px; + margin: 4px auto; + } + + .mCS-3d.mCSB_scrollTools .mCSB_buttonUp{ background-position: -32px -72px; } + + .mCS-3d.mCSB_scrollTools .mCSB_buttonDown{ background-position: -32px -92px; } + + .mCS-3d.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -40px -112px; } + + .mCS-3d.mCSB_scrollTools .mCSB_buttonRight{ background-position: -40px -128px; } + + + /* theme "3d-dark" */ + + .mCS-3d-dark.mCSB_scrollTools .mCSB_draggerRail{ + background-color: #000; background-color: rgba(0,0,0,0.1); + box-shadow: inset 1px 0 1px rgba(0,0,0,0.1); + } + + .mCS-3d-dark.mCSB_scrollTools_horizontal .mCSB_draggerRail{ box-shadow: inset 0 1px 1px rgba(0,0,0,0.1); } + + .mCS-3d-dark.mCSB_scrollTools .mCSB_buttonUp{ background-position: -112px -72px; } + + .mCS-3d-dark.mCSB_scrollTools .mCSB_buttonDown{ background-position: -112px -92px; } + + .mCS-3d-dark.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -120px -112px; } + + .mCS-3d-dark.mCSB_scrollTools .mCSB_buttonRight{ background-position: -120px -128px; } + + /* ---------------------------------------- */ + + + + /* theme: "3d-thick", "3d-thick-dark" */ + + .mCS-3d-thick.mCSB_scrollTools, + .mCS-3d-thick-dark.mCSB_scrollTools{ + opacity: 1; + filter: "alpha(opacity=30)"; -ms-filter: "alpha(opacity=30)"; + } + + .mCS-3d-thick.mCSB_scrollTools, + .mCS-3d-thick-dark.mCSB_scrollTools, + .mCS-3d-thick.mCSB_scrollTools .mCSB_draggerContainer, + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_draggerContainer{ -webkit-border-radius: 7px; -moz-border-radius: 7px; border-radius: 7px; } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } + + .mCSB_inside + .mCS-3d-thick.mCSB_scrollTools_vertical, + .mCSB_inside + .mCS-3d-thick-dark.mCSB_scrollTools_vertical{ right: 1px; } + + .mCS-3d-thick.mCSB_scrollTools_vertical, + .mCS-3d-thick-dark.mCSB_scrollTools_vertical{ box-shadow: inset 1px 0 1px rgba(0,0,0,0.1), inset 0 0 14px rgba(0,0,0,0.5); } + + .mCS-3d-thick.mCSB_scrollTools_horizontal, + .mCS-3d-thick-dark.mCSB_scrollTools_horizontal{ + bottom: 1px; + box-shadow: inset 0 1px 1px rgba(0,0,0,0.1), inset 0 0 14px rgba(0,0,0,0.5); + } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + box-shadow: inset 1px 0 0 rgba(255,255,255,0.4); + width: 12px; + margin: 2px; + position: absolute; + height: auto; + top: 0; + bottom: 0; + left: 0; + right: 0; + } + + .mCS-3d-thick.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ box-shadow: inset 0 1px 0 rgba(255,255,255,0.4); } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar, + .mCS-3d-thick.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-3d-thick.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #555; } + + .mCS-3d-thick.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + height: 12px; + width: auto; + } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_draggerContainer{ + background-color: #000; background-color: rgba(0,0,0,0.05); + box-shadow: inset 1px 1px 16px rgba(0,0,0,0.1); + } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_draggerRail{ background-color: transparent; } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_buttonUp{ background-position: -32px -72px; } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_buttonDown{ background-position: -32px -92px; } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -40px -112px; } + + .mCS-3d-thick.mCSB_scrollTools .mCSB_buttonRight{ background-position: -40px -128px; } + + + /* theme: "3d-thick-dark" */ + + .mCS-3d-thick-dark.mCSB_scrollTools{ box-shadow: inset 0 0 14px rgba(0,0,0,0.2); } + + .mCS-3d-thick-dark.mCSB_scrollTools_horizontal{ box-shadow: inset 0 1px 1px rgba(0,0,0,0.1), inset 0 0 14px rgba(0,0,0,0.2); } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ box-shadow: inset 1px 0 0 rgba(255,255,255,0.4), inset -1px 0 0 rgba(0,0,0,0.2); } + + .mCS-3d-thick-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ box-shadow: inset 0 1px 0 rgba(255,255,255,0.4), inset 0 -1px 0 rgba(0,0,0,0.2); } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #777; } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_draggerContainer{ + background-color: #fff; background-color: rgba(0,0,0,0.05); + box-shadow: inset 1px 1px 16px rgba(0,0,0,0.1); + } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_draggerRail{ background-color: transparent; } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_buttonUp{ background-position: -112px -72px; } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_buttonDown{ background-position: -112px -92px; } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -120px -112px; } + + .mCS-3d-thick-dark.mCSB_scrollTools .mCSB_buttonRight{ background-position: -120px -128px; } + + /* ---------------------------------------- */ + + + + /* theme: "minimal", "minimal-dark" */ + + .mCSB_outside + .mCS-minimal.mCSB_scrollTools_vertical, + .mCSB_outside + .mCS-minimal-dark.mCSB_scrollTools_vertical{ + right: 0; + margin: 12px 0; + } + + .mCustomScrollBox.mCS-minimal + .mCSB_scrollTools.mCSB_scrollTools_horizontal, + .mCustomScrollBox.mCS-minimal + .mCSB_scrollTools + .mCSB_scrollTools.mCSB_scrollTools_horizontal, + .mCustomScrollBox.mCS-minimal-dark + .mCSB_scrollTools.mCSB_scrollTools_horizontal, + .mCustomScrollBox.mCS-minimal-dark + .mCSB_scrollTools + .mCSB_scrollTools.mCSB_scrollTools_horizontal{ + bottom: 0; + margin: 0 12px; + } + + /* RTL direction/left-side scrollbar */ + .mCS-dir-rtl > .mCSB_outside + .mCS-minimal.mCSB_scrollTools_vertical, + .mCS-dir-rtl > .mCSB_outside + .mCS-minimal-dark.mCSB_scrollTools_vertical{ + left: 0; + right: auto; + } + + .mCS-minimal.mCSB_scrollTools .mCSB_draggerRail, + .mCS-minimal-dark.mCSB_scrollTools .mCSB_draggerRail{ background-color: transparent; } + + .mCS-minimal.mCSB_scrollTools_vertical .mCSB_dragger, + .mCS-minimal-dark.mCSB_scrollTools_vertical .mCSB_dragger{ height: 50px; } + + .mCS-minimal.mCSB_scrollTools_horizontal .mCSB_dragger, + .mCS-minimal-dark.mCSB_scrollTools_horizontal .mCSB_dragger{ width: 50px; } + + .mCS-minimal.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + background-color: #fff; background-color: rgba(255,255,255,0.2); + filter: "alpha(opacity=20)"; -ms-filter: "alpha(opacity=20)"; + } + + .mCS-minimal.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-minimal.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ + background-color: #fff; background-color: rgba(255,255,255,0.5); + filter: "alpha(opacity=50)"; -ms-filter: "alpha(opacity=50)"; + } + + + /* theme: "minimal-dark" */ + + .mCS-minimal-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + background-color: #000; background-color: rgba(0,0,0,0.2); + filter: "alpha(opacity=20)"; -ms-filter: "alpha(opacity=20)"; + } + + .mCS-minimal-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-minimal-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ + background-color: #000; background-color: rgba(0,0,0,0.5); + filter: "alpha(opacity=50)"; -ms-filter: "alpha(opacity=50)"; + } + + /* ---------------------------------------- */ + + + + /* theme "light-3", "dark-3" */ + + .mCS-light-3.mCSB_scrollTools .mCSB_draggerRail, + .mCS-dark-3.mCSB_scrollTools .mCSB_draggerRail{ + width: 6px; + background-color: #000; background-color: rgba(0,0,0,0.2); + } + + .mCS-light-3.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-3.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ width: 6px; } + + .mCS-light-3.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-dark-3.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-light-3.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-dark-3.mCSB_scrollTools_horizontal .mCSB_draggerRail{ + width: 100%; + height: 6px; + margin: 5px 0; + } + + .mCS-light-3.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-light-3.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail, + .mCS-dark-3.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-dark-3.mCSB_scrollTools_vertical.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail{ + width: 12px; + } + + .mCS-light-3.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-light-3.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail, + .mCS-dark-3.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_dragger.mCSB_dragger_onDrag_expanded + .mCSB_draggerRail, + .mCS-dark-3.mCSB_scrollTools_horizontal.mCSB_scrollTools_onDrag_expand .mCSB_draggerContainer:hover .mCSB_draggerRail{ + height: 12px; + margin: 2px 0; + } + + .mCS-light-3.mCSB_scrollTools .mCSB_buttonUp{ background-position: -32px -72px; } + + .mCS-light-3.mCSB_scrollTools .mCSB_buttonDown{ background-position: -32px -92px; } + + .mCS-light-3.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -40px -112px; } + + .mCS-light-3.mCSB_scrollTools .mCSB_buttonRight{ background-position: -40px -128px; } + + + /* theme "dark-3" */ + + .mCS-dark-3.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.75); } + + .mCS-dark-3.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.85); } + + .mCS-dark-3.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-dark-3.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.9); } + + .mCS-dark-3.mCSB_scrollTools .mCSB_draggerRail{ background-color: #000; background-color: rgba(0,0,0,0.1); } + + .mCS-dark-3.mCSB_scrollTools .mCSB_buttonUp{ background-position: -112px -72px; } + + .mCS-dark-3.mCSB_scrollTools .mCSB_buttonDown{ background-position: -112px -92px; } + + .mCS-dark-3.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -120px -112px; } + + .mCS-dark-3.mCSB_scrollTools .mCSB_buttonRight{ background-position: -120px -128px; } + + /* ---------------------------------------- */ + + + + /* theme "inset", "inset-dark", "inset-2", "inset-2-dark", "inset-3", "inset-3-dark" */ + + .mCS-inset.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-dark.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-2.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-3.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_draggerRail{ + width: 12px; + background-color: #000; background-color: rgba(0,0,0,0.2); + } + + .mCS-inset.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-2.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-3.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ + width: 6px; + margin: 3px 5px; + position: absolute; + height: auto; + top: 0; + bottom: 0; + left: 0; + right: 0; + } + + .mCS-inset.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-2.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-2-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-3.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-3-dark.mCSB_scrollTools_horizontal .mCSB_dragger .mCSB_dragger_bar{ + height: 6px; + margin: 5px 3px; + position: absolute; + width: auto; + top: 0; + bottom: 0; + left: 0; + right: 0; + } + + .mCS-inset.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-inset-dark.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-inset-2.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-inset-2-dark.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-inset-3.mCSB_scrollTools_horizontal .mCSB_draggerRail, + .mCS-inset-3-dark.mCSB_scrollTools_horizontal .mCSB_draggerRail{ + width: 100%; + height: 12px; + margin: 2px 0; + } + + .mCS-inset.mCSB_scrollTools .mCSB_buttonUp, + .mCS-inset-2.mCSB_scrollTools .mCSB_buttonUp, + .mCS-inset-3.mCSB_scrollTools .mCSB_buttonUp{ background-position: -32px -72px; } + + .mCS-inset.mCSB_scrollTools .mCSB_buttonDown, + .mCS-inset-2.mCSB_scrollTools .mCSB_buttonDown, + .mCS-inset-3.mCSB_scrollTools .mCSB_buttonDown{ background-position: -32px -92px; } + + .mCS-inset.mCSB_scrollTools .mCSB_buttonLeft, + .mCS-inset-2.mCSB_scrollTools .mCSB_buttonLeft, + .mCS-inset-3.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -40px -112px; } + + .mCS-inset.mCSB_scrollTools .mCSB_buttonRight, + .mCS-inset-2.mCSB_scrollTools .mCSB_buttonRight, + .mCS-inset-3.mCSB_scrollTools .mCSB_buttonRight{ background-position: -40px -128px; } + + + /* theme "inset-dark", "inset-2-dark", "inset-3-dark" */ + + .mCS-inset-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.75); } + + .mCS-inset-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.85); } + + .mCS-inset-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-inset-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.9); } + + .mCS-inset-dark.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_draggerRail{ background-color: #000; background-color: rgba(0,0,0,0.1); } + + .mCS-inset-dark.mCSB_scrollTools .mCSB_buttonUp, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_buttonUp, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_buttonUp{ background-position: -112px -72px; } + + .mCS-inset-dark.mCSB_scrollTools .mCSB_buttonDown, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_buttonDown, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_buttonDown{ background-position: -112px -92px; } + + .mCS-inset-dark.mCSB_scrollTools .mCSB_buttonLeft, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_buttonLeft, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_buttonLeft{ background-position: -120px -112px; } + + .mCS-inset-dark.mCSB_scrollTools .mCSB_buttonRight, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_buttonRight, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_buttonRight{ background-position: -120px -128px; } + + + /* theme "inset-2", "inset-2-dark" */ + + .mCS-inset-2.mCSB_scrollTools .mCSB_draggerRail, + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_draggerRail{ + background-color: transparent; + border-width: 1px; + border-style: solid; + border-color: #fff; + border-color: rgba(255,255,255,0.2); + -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; + } + + .mCS-inset-2-dark.mCSB_scrollTools .mCSB_draggerRail{ border-color: #000; border-color: rgba(0,0,0,0.2); } + + + /* theme "inset-3", "inset-3-dark" */ + + .mCS-inset-3.mCSB_scrollTools .mCSB_draggerRail{ background-color: #fff; background-color: rgba(255,255,255,0.6); } + + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_draggerRail{ background-color: #000; background-color: rgba(0,0,0,0.6); } + + .mCS-inset-3.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.75); } + + .mCS-inset-3.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.85); } + + .mCS-inset-3.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-inset-3.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #000; background-color: rgba(0,0,0,0.9); } + + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: #fff; background-color: rgba(255,255,255,0.75); } + + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger:hover .mCSB_dragger_bar{ background-color: #fff; background-color: rgba(255,255,255,0.85); } + + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger:active .mCSB_dragger_bar, + .mCS-inset-3-dark.mCSB_scrollTools .mCSB_dragger.mCSB_dragger_onDrag .mCSB_dragger_bar{ background-color: #fff; background-color: rgba(255,255,255,0.9); } + + /* ---------------------------------------- */ diff --git a/packages/wekan-scrollbar/jquery.mCustomScrollbar.js b/packages/wekan-scrollbar/jquery.mCustomScrollbar.js new file mode 100644 index 00000000..b7883579 --- /dev/null +++ b/packages/wekan-scrollbar/jquery.mCustomScrollbar.js @@ -0,0 +1,2423 @@ +/* +== malihu jquery custom scrollbar plugin == +Version: 3.1.3 +Plugin URI: http://manos.malihu.gr/jquery-custom-content-scroller +Author: malihu +Author URI: http://manos.malihu.gr +License: MIT License (MIT) +*/ + +/* +Copyright Manos Malihutsakis (email: manos@malihu.gr) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +/* +The code below is fairly long, fully commented and should be normally used in development. +For production, use either the minified jquery.mCustomScrollbar.min.js script or +the production-ready jquery.mCustomScrollbar.concat.min.js which contains the plugin +and dependencies (minified). +*/ + +(function(factory){ + if(typeof module!=="undefined" && module.exports){ + module.exports=factory; + }else{ + factory(jQuery,window,document); + } +}(function($){ +(function(init){ + var _rjs=typeof define==="function" && define.amd, /* RequireJS */ + _njs=typeof module !== "undefined" && module.exports; /* NodeJS */ + if(!_rjs){ + if(_njs){ + require("jquery-mousewheel")($); + }else{ + /* Only load locally jquery-mousewheel plugin. + (works when mCustomScrollbar fn is called on window load) */ + $.event.special.mousewheel; + } + } + init(); +}(function(){ + + /* + ---------------------------------------- + PLUGIN NAMESPACE, PREFIX, DEFAULT SELECTOR(S) + ---------------------------------------- + */ + + var pluginNS="mCustomScrollbar", + pluginPfx="mCS", + defaultSelector=".mCustomScrollbar", + + + + + + /* + ---------------------------------------- + DEFAULT OPTIONS + ---------------------------------------- + */ + + defaults={ + /* + set element/content width/height programmatically + values: boolean, pixels, percentage + option default + ------------------------------------- + setWidth false + setHeight false + */ + /* + set the initial css top property of content + values: string (e.g. "-100px", "10%" etc.) + */ + setTop:0, + /* + set the initial css left property of content + values: string (e.g. "-100px", "10%" etc.) + */ + setLeft:0, + /* + scrollbar axis (vertical and/or horizontal scrollbars) + values (string): "y", "x", "yx" + */ + axis:"y", + /* + position of scrollbar relative to content + values (string): "inside", "outside" ("outside" requires elements with position:relative) + */ + scrollbarPosition:"inside", + /* + scrolling inertia + values: integer (milliseconds) + */ + scrollInertia:950, + /* + auto-adjust scrollbar dragger length + values: boolean + */ + autoDraggerLength:true, + /* + auto-hide scrollbar when idle + values: boolean + option default + ------------------------------------- + autoHideScrollbar false + */ + /* + auto-expands scrollbar on mouse-over and dragging + values: boolean + option default + ------------------------------------- + autoExpandScrollbar false + */ + /* + always show scrollbar, even when there's nothing to scroll + values: integer (0=disable, 1=always show dragger rail and buttons, 2=always show dragger rail, dragger and buttons), boolean + */ + alwaysShowScrollbar:0, + /* + scrolling always snaps to a multiple of this number in pixels + values: integer, array ([y,x]) + option default + ------------------------------------- + snapAmount null + */ + /* + when snapping, snap with this number in pixels as an offset + values: integer + */ + snapOffset:0, + /* + mouse-wheel scrolling + */ + mouseWheel:{ + /* + enable mouse-wheel scrolling + values: boolean + */ + enable:true, + /* + scrolling amount in pixels + values: "auto", integer + */ + scrollAmount:"auto", + /* + mouse-wheel scrolling axis + the default scrolling direction when both vertical and horizontal scrollbars are present + values (string): "y", "x" + */ + axis:"y", + /* + prevent the default behaviour which automatically scrolls the parent element(s) when end of scrolling is reached + values: boolean + option default + ------------------------------------- + preventDefault null + */ + /* + the reported mouse-wheel delta value. The number of lines (translated to pixels) one wheel notch scrolls. + values: "auto", integer + "auto" uses the default OS/browser value + */ + deltaFactor:"auto", + /* + normalize mouse-wheel delta to -1 or 1 (disables mouse-wheel acceleration) + values: boolean + option default + ------------------------------------- + normalizeDelta null + */ + /* + invert mouse-wheel scrolling direction + values: boolean + option default + ------------------------------------- + invert null + */ + /* + the tags that disable mouse-wheel when cursor is over them + */ + disableOver:["select","option","keygen","datalist","textarea"] + }, + /* + scrollbar buttons + */ + scrollButtons:{ + /* + enable scrollbar buttons + values: boolean + option default + ------------------------------------- + enable null + */ + /* + scrollbar buttons scrolling type + values (string): "stepless", "stepped" + */ + scrollType:"stepless", + /* + scrolling amount in pixels + values: "auto", integer + */ + scrollAmount:"auto" + /* + tabindex of the scrollbar buttons + values: false, integer + option default + ------------------------------------- + tabindex null + */ + }, + /* + keyboard scrolling + */ + keyboard:{ + /* + enable scrolling via keyboard + values: boolean + */ + enable:true, + /* + keyboard scrolling type + values (string): "stepless", "stepped" + */ + scrollType:"stepless", + /* + scrolling amount in pixels + values: "auto", integer + */ + scrollAmount:"auto" + }, + /* + enable content touch-swipe scrolling + values: boolean, integer, string (number) + integer values define the axis-specific minimum amount required for scrolling momentum + */ + contentTouchScroll:25, + /* + enable/disable document (default) touch-swipe scrolling + */ + documentTouchScroll:true, + /* + advanced option parameters + */ + advanced:{ + /* + auto-expand content horizontally (for "x" or "yx" axis) + values: boolean, integer (the value 2 forces the non scrollHeight/scrollWidth method, the value 3 forces the scrollHeight/scrollWidth method) + option default + ------------------------------------- + autoExpandHorizontalScroll null + */ + /* + auto-scroll to elements with focus + */ + autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']", + /* + auto-update scrollbars on content, element or viewport resize + should be true for fluid layouts/elements, adding/removing content dynamically, hiding/showing elements, content with images etc. + values: boolean + */ + updateOnContentResize:true, + /* + auto-update scrollbars each time each image inside the element is fully loaded + values: "auto", boolean + */ + updateOnImageLoad:"auto", + /* + auto-update scrollbars based on the amount and size changes of specific selectors + useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size + values: boolean, string (e.g. "ul li" will auto-update scrollbars each time list-items inside the element are changed) + a value of true (boolean) will auto-update scrollbars each time any element is changed + option default + ------------------------------------- + updateOnSelectorChange null + */ + /* + extra selectors that'll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc. (e.g. "selector-1, selector-2") + option default + ------------------------------------- + extraDraggableSelectors null + */ + /* + extra selectors that'll release scrollbar dragging upon mouseup, pointerup, touchend etc. (e.g. "selector-1, selector-2") + option default + ------------------------------------- + releaseDraggableSelectors null + */ + /* + auto-update timeout + values: integer (milliseconds) + */ + autoUpdateTimeout:60 + }, + /* + scrollbar theme + values: string (see CSS/plugin URI for a list of ready-to-use themes) + */ + theme:"light", + /* + user defined callback functions + */ + callbacks:{ + /* + Available callbacks: + callback default + ------------------------------------- + onCreate null + onInit null + onScrollStart null + onScroll null + onTotalScroll null + onTotalScrollBack null + whileScrolling null + onOverflowY null + onOverflowX null + onOverflowYNone null + onOverflowXNone null + onImageLoad null + onSelectorChange null + onBeforeUpdate null + onUpdate null + */ + onTotalScrollOffset:0, + onTotalScrollBackOffset:0, + alwaysTriggerOffsets:true + } + /* + add scrollbar(s) on all elements matching the current selector, now and in the future + values: boolean, string + string values: "on" (enable), "once" (disable after first invocation), "off" (disable) + liveSelector values: string (selector) + option default + ------------------------------------- + live false + liveSelector null + */ + }, + + + + + + /* + ---------------------------------------- + VARS, CONSTANTS + ---------------------------------------- + */ + + totalInstances=0, /* plugin instances amount */ + liveTimers={}, /* live option timers */ + oldIE=(window.attachEvent && !window.addEventListener) ? 1 : 0, /* detect IE < 9 */ + touchActive=false,touchable, /* global touch vars (for touch and pointer events) */ + /* general plugin classes */ + classes=[ + "mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar", + "mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer", + "mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight" + ], + + + + + + /* + ---------------------------------------- + METHODS + ---------------------------------------- + */ + + methods={ + + /* + plugin initialization method + creates the scrollbar(s), plugin data object and options + ---------------------------------------- + */ + + init:function(options){ + + var options=$.extend(true,{},defaults,options), + selector=_selector.call(this); /* validate selector */ + + /* + if live option is enabled, monitor for elements matching the current selector and + apply scrollbar(s) when found (now and in the future) + */ + if(options.live){ + var liveSelector=options.liveSelector || this.selector || defaultSelector, /* live selector(s) */ + $liveSelector=$(liveSelector); /* live selector(s) as jquery object */ + if(options.live==="off"){ + /* + disable live if requested + usage: $(selector).mCustomScrollbar({live:"off"}); + */ + removeLiveTimers(liveSelector); + return; + } + liveTimers[liveSelector]=setTimeout(function(){ + /* call mCustomScrollbar fn on live selector(s) every half-second */ + $liveSelector.mCustomScrollbar(options); + if(options.live==="once" && $liveSelector.length){ + /* disable live after first invocation */ + removeLiveTimers(liveSelector); + } + },500); + }else{ + removeLiveTimers(liveSelector); + } + + /* options backward compatibility (for versions < 3.0.0) and normalization */ + options.setWidth=(options.set_width) ? options.set_width : options.setWidth; + options.setHeight=(options.set_height) ? options.set_height : options.setHeight; + options.axis=(options.horizontalScroll) ? "x" : _findAxis(options.axis); + options.scrollInertia=options.scrollInertia>0 && options.scrollInertia<17 ? 17 : options.scrollInertia; + if(typeof options.mouseWheel!=="object" && options.mouseWheel==true){ /* old school mouseWheel option (non-object) */ + options.mouseWheel={enable:true,scrollAmount:"auto",axis:"y",preventDefault:false,deltaFactor:"auto",normalizeDelta:false,invert:false} + } + options.mouseWheel.scrollAmount=!options.mouseWheelPixels ? options.mouseWheel.scrollAmount : options.mouseWheelPixels; + options.mouseWheel.normalizeDelta=!options.advanced.normalizeMouseWheelDelta ? options.mouseWheel.normalizeDelta : options.advanced.normalizeMouseWheelDelta; + options.scrollButtons.scrollType=_findScrollButtonsType(options.scrollButtons.scrollType); + + _theme(options); /* theme-specific options */ + + /* plugin constructor */ + return $(selector).each(function(){ + + var $this=$(this); + + if(!$this.data(pluginPfx)){ /* prevent multiple instantiations */ + + /* store options and create objects in jquery data */ + $this.data(pluginPfx,{ + idx:++totalInstances, /* instance index */ + opt:options, /* options */ + scrollRatio:{y:null,x:null}, /* scrollbar to content ratio */ + overflowed:null, /* overflowed axis */ + contentReset:{y:null,x:null}, /* object to check when content resets */ + bindEvents:false, /* object to check if events are bound */ + tweenRunning:false, /* object to check if tween is running */ + sequential:{}, /* sequential scrolling object */ + langDir:$this.css("direction"), /* detect/store direction (ltr or rtl) */ + cbOffsets:null, /* object to check whether callback offsets always trigger */ + /* + object to check how scrolling events where last triggered + "internal" (default - triggered by this script), "external" (triggered by other scripts, e.g. via scrollTo method) + usage: object.data("mCS").trigger + */ + trigger:null, + /* + object to check for changes in elements in order to call the update method automatically + */ + poll:{size:{o:0,n:0},img:{o:0,n:0},change:{o:0,n:0}} + }); + + var d=$this.data(pluginPfx),o=d.opt, + /* HTML data attributes */ + htmlDataAxis=$this.data("mcs-axis"),htmlDataSbPos=$this.data("mcs-scrollbar-position"),htmlDataTheme=$this.data("mcs-theme"); + + if(htmlDataAxis){o.axis=htmlDataAxis;} /* usage example: data-mcs-axis="y" */ + if(htmlDataSbPos){o.scrollbarPosition=htmlDataSbPos;} /* usage example: data-mcs-scrollbar-position="outside" */ + if(htmlDataTheme){ /* usage example: data-mcs-theme="minimal" */ + o.theme=htmlDataTheme; + _theme(o); /* theme-specific options */ + } + + _pluginMarkup.call(this); /* add plugin markup */ + + if(d && o.callbacks.onCreate && typeof o.callbacks.onCreate==="function"){o.callbacks.onCreate.call(this);} /* callbacks: onCreate */ + + $("#mCSB_"+d.idx+"_container img:not(."+classes[2]+")").addClass(classes[2]); /* flag loaded images */ + + methods.update.call(null,$this); /* call the update method */ + + } + + }); + + }, + /* ---------------------------------------- */ + + + + /* + plugin update method + updates content and scrollbar(s) values, events and status + ---------------------------------------- + usage: $(selector).mCustomScrollbar("update"); + */ + + update:function(el,cb){ + + var selector=el || _selector.call(this); /* validate selector */ + + return $(selector).each(function(){ + + var $this=$(this); + + if($this.data(pluginPfx)){ /* check if plugin has initialized */ + + var d=$this.data(pluginPfx),o=d.opt, + mCSB_container=$("#mCSB_"+d.idx+"_container"), + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")]; + + if(!mCSB_container.length){return;} + + if(d.tweenRunning){_stop($this);} /* stop any running tweens while updating */ + + if(cb && d && o.callbacks.onBeforeUpdate && typeof o.callbacks.onBeforeUpdate==="function"){o.callbacks.onBeforeUpdate.call(this);} /* callbacks: onBeforeUpdate */ + + /* if element was disabled or destroyed, remove class(es) */ + if($this.hasClass(classes[3])){$this.removeClass(classes[3]);} + if($this.hasClass(classes[4])){$this.removeClass(classes[4]);} + + /* css flexbox fix, detect/set max-height */ + mCustomScrollBox.css("max-height","none"); + if(mCustomScrollBox.height()!==$this.height()){mCustomScrollBox.css("max-height",$this.height());} + + _expandContentHorizontally.call(this); /* expand content horizontally */ + + if(o.axis!=="y" && !o.advanced.autoExpandHorizontalScroll){ + mCSB_container.css("width",_contentWidth(mCSB_container)); + } + + d.overflowed=_overflowed.call(this); /* determine if scrolling is required */ + + _scrollbarVisibility.call(this); /* show/hide scrollbar(s) */ + + /* auto-adjust scrollbar dragger length analogous to content */ + if(o.autoDraggerLength){_setDraggerLength.call(this);} + + _scrollRatio.call(this); /* calculate and store scrollbar to content ratio */ + + _bindEvents.call(this); /* bind scrollbar events */ + + /* reset scrolling position and/or events */ + var to=[Math.abs(mCSB_container[0].offsetTop),Math.abs(mCSB_container[0].offsetLeft)]; + if(o.axis!=="x"){ /* y/yx axis */ + if(!d.overflowed[0]){ /* y scrolling is not required */ + _resetContentPosition.call(this); /* reset content position */ + if(o.axis==="y"){ + _unbindEvents.call(this); + }else if(o.axis==="yx" && d.overflowed[1]){ + _scrollTo($this,to[1].toString(),{dir:"x",dur:0,overwrite:"none"}); + } + }else if(mCSB_dragger[0].height()>mCSB_dragger[0].parent().height()){ + _resetContentPosition.call(this); /* reset content position */ + }else{ /* y scrolling is required */ + _scrollTo($this,to[0].toString(),{dir:"y",dur:0,overwrite:"none"}); + d.contentReset.y=null; + } + } + if(o.axis!=="y"){ /* x/yx axis */ + if(!d.overflowed[1]){ /* x scrolling is not required */ + _resetContentPosition.call(this); /* reset content position */ + if(o.axis==="x"){ + _unbindEvents.call(this); + }else if(o.axis==="yx" && d.overflowed[0]){ + _scrollTo($this,to[0].toString(),{dir:"y",dur:0,overwrite:"none"}); + } + }else if(mCSB_dragger[1].width()>mCSB_dragger[1].parent().width()){ + _resetContentPosition.call(this); /* reset content position */ + }else{ /* x scrolling is required */ + _scrollTo($this,to[1].toString(),{dir:"x",dur:0,overwrite:"none"}); + d.contentReset.x=null; + } + } + + /* callbacks: onImageLoad, onSelectorChange, onUpdate */ + if(cb && d){ + if(cb===2 && o.callbacks.onImageLoad && typeof o.callbacks.onImageLoad==="function"){ + o.callbacks.onImageLoad.call(this); + }else if(cb===3 && o.callbacks.onSelectorChange && typeof o.callbacks.onSelectorChange==="function"){ + o.callbacks.onSelectorChange.call(this); + }else if(o.callbacks.onUpdate && typeof o.callbacks.onUpdate==="function"){ + o.callbacks.onUpdate.call(this); + } + } + + _autoUpdate.call(this); /* initialize automatic updating (for dynamic content, fluid layouts etc.) */ + + } + + }); + + }, + /* ---------------------------------------- */ + + + + /* + plugin scrollTo method + triggers a scrolling event to a specific value + ---------------------------------------- + usage: $(selector).mCustomScrollbar("scrollTo",value,options); + */ + + scrollTo:function(val,options){ + + /* prevent silly things like $(selector).mCustomScrollbar("scrollTo",undefined); */ + if(typeof val=="undefined" || val==null){return;} + + var selector=_selector.call(this); /* validate selector */ + + return $(selector).each(function(){ + + var $this=$(this); + + if($this.data(pluginPfx)){ /* check if plugin has initialized */ + + var d=$this.data(pluginPfx),o=d.opt, + /* method default options */ + methodDefaults={ + trigger:"external", /* method is by default triggered externally (e.g. from other scripts) */ + scrollInertia:o.scrollInertia, /* scrolling inertia (animation duration) */ + scrollEasing:"mcsEaseInOut", /* animation easing */ + moveDragger:false, /* move dragger instead of content */ + timeout:60, /* scroll-to delay */ + callbacks:true, /* enable/disable callbacks */ + onStart:true, + onUpdate:true, + onComplete:true + }, + methodOptions=$.extend(true,{},methodDefaults,options), + to=_arr.call(this,val),dur=methodOptions.scrollInertia>0 && methodOptions.scrollInertia<17 ? 17 : methodOptions.scrollInertia; + + /* translate yx values to actual scroll-to positions */ + to[0]=_to.call(this,to[0],"y"); + to[1]=_to.call(this,to[1],"x"); + + /* + check if scroll-to value moves the dragger instead of content. + Only pixel values apply on dragger (e.g. 100, "100px", "-=100" etc.) + */ + if(methodOptions.moveDragger){ + to[0]*=d.scrollRatio.y; + to[1]*=d.scrollRatio.x; + } + + methodOptions.dur=_isTabHidden() ? 0 : dur; //skip animations if browser tab is hidden + + setTimeout(function(){ + /* do the scrolling */ + if(to[0]!==null && typeof to[0]!=="undefined" && o.axis!=="x" && d.overflowed[0]){ /* scroll y */ + methodOptions.dir="y"; + methodOptions.overwrite="all"; + _scrollTo($this,to[0].toString(),methodOptions); + } + if(to[1]!==null && typeof to[1]!=="undefined" && o.axis!=="y" && d.overflowed[1]){ /* scroll x */ + methodOptions.dir="x"; + methodOptions.overwrite="none"; + _scrollTo($this,to[1].toString(),methodOptions); + } + },methodOptions.timeout); + + } + + }); + + }, + /* ---------------------------------------- */ + + + + /* + plugin stop method + stops scrolling animation + ---------------------------------------- + usage: $(selector).mCustomScrollbar("stop"); + */ + stop:function(){ + + var selector=_selector.call(this); /* validate selector */ + + return $(selector).each(function(){ + + var $this=$(this); + + if($this.data(pluginPfx)){ /* check if plugin has initialized */ + + _stop($this); + + } + + }); + + }, + /* ---------------------------------------- */ + + + + /* + plugin disable method + temporarily disables the scrollbar(s) + ---------------------------------------- + usage: $(selector).mCustomScrollbar("disable",reset); + reset (boolean): resets content position to 0 + */ + disable:function(r){ + + var selector=_selector.call(this); /* validate selector */ + + return $(selector).each(function(){ + + var $this=$(this); + + if($this.data(pluginPfx)){ /* check if plugin has initialized */ + + var d=$this.data(pluginPfx); + + _autoUpdate.call(this,"remove"); /* remove automatic updating */ + + _unbindEvents.call(this); /* unbind events */ + + if(r){_resetContentPosition.call(this);} /* reset content position */ + + _scrollbarVisibility.call(this,true); /* show/hide scrollbar(s) */ + + $this.addClass(classes[3]); /* add disable class */ + + } + + }); + + }, + /* ---------------------------------------- */ + + + + /* + plugin destroy method + completely removes the scrollbar(s) and returns the element to its original state + ---------------------------------------- + usage: $(selector).mCustomScrollbar("destroy"); + */ + destroy:function(){ + + var selector=_selector.call(this); /* validate selector */ + + return $(selector).each(function(){ + + var $this=$(this); + + if($this.data(pluginPfx)){ /* check if plugin has initialized */ + + var d=$this.data(pluginPfx),o=d.opt, + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + scrollbar=$(".mCSB_"+d.idx+"_scrollbar"); + + if(o.live){removeLiveTimers(o.liveSelector || $(selector).selector);} /* remove live timers */ + + _autoUpdate.call(this,"remove"); /* remove automatic updating */ + + _unbindEvents.call(this); /* unbind events */ + + _resetContentPosition.call(this); /* reset content position */ + + $this.removeData(pluginPfx); /* remove plugin data object */ + + _delete(this,"mcs"); /* delete callbacks object */ + + /* remove plugin markup */ + scrollbar.remove(); /* remove scrollbar(s) first (those can be either inside or outside plugin's inner wrapper) */ + mCSB_container.find("img."+classes[2]).removeClass(classes[2]); /* remove loaded images flag */ + mCustomScrollBox.replaceWith(mCSB_container.contents()); /* replace plugin's inner wrapper with the original content */ + /* remove plugin classes from the element and add destroy class */ + $this.removeClass(pluginNS+" _"+pluginPfx+"_"+d.idx+" "+classes[6]+" "+classes[7]+" "+classes[5]+" "+classes[3]).addClass(classes[4]); + + } + + }); + + } + /* ---------------------------------------- */ + + }, + + + + + + /* + ---------------------------------------- + FUNCTIONS + ---------------------------------------- + */ + + /* validates selector (if selector is invalid or undefined uses the default one) */ + _selector=function(){ + return (typeof $(this)!=="object" || $(this).length<1) ? defaultSelector : this; + }, + /* -------------------- */ + + + /* changes options according to theme */ + _theme=function(obj){ + var fixedSizeScrollbarThemes=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"], + nonExpandedScrollbarThemes=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"], + disabledScrollButtonsThemes=["minimal","minimal-dark"], + enabledAutoHideScrollbarThemes=["minimal","minimal-dark"], + scrollbarPositionOutsideThemes=["minimal","minimal-dark"]; + obj.autoDraggerLength=$.inArray(obj.theme,fixedSizeScrollbarThemes) > -1 ? false : obj.autoDraggerLength; + obj.autoExpandScrollbar=$.inArray(obj.theme,nonExpandedScrollbarThemes) > -1 ? false : obj.autoExpandScrollbar; + obj.scrollButtons.enable=$.inArray(obj.theme,disabledScrollButtonsThemes) > -1 ? false : obj.scrollButtons.enable; + obj.autoHideScrollbar=$.inArray(obj.theme,enabledAutoHideScrollbarThemes) > -1 ? true : obj.autoHideScrollbar; + obj.scrollbarPosition=$.inArray(obj.theme,scrollbarPositionOutsideThemes) > -1 ? "outside" : obj.scrollbarPosition; + }, + /* -------------------- */ + + + /* live option timers removal */ + removeLiveTimers=function(selector){ + if(liveTimers[selector]){ + clearTimeout(liveTimers[selector]); + _delete(liveTimers,selector); + } + }, + /* -------------------- */ + + + /* normalizes axis option to valid values: "y", "x", "yx" */ + _findAxis=function(val){ + return (val==="yx" || val==="xy" || val==="auto") ? "yx" : (val==="x" || val==="horizontal") ? "x" : "y"; + }, + /* -------------------- */ + + + /* normalizes scrollButtons.scrollType option to valid values: "stepless", "stepped" */ + _findScrollButtonsType=function(val){ + return (val==="stepped" || val==="pixels" || val==="step" || val==="click") ? "stepped" : "stepless"; + }, + /* -------------------- */ + + + /* generates plugin markup */ + _pluginMarkup=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + expandClass=o.autoExpandScrollbar ? " "+classes[1]+"_expand" : "", + scrollbar=["<div id='mCSB_"+d.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+d.idx+"_scrollbar mCS-"+o.theme+" mCSB_scrollTools_vertical"+expandClass+"'><div class='"+classes[12]+"'><div id='mCSB_"+d.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>","<div id='mCSB_"+d.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+d.idx+"_scrollbar mCS-"+o.theme+" mCSB_scrollTools_horizontal"+expandClass+"'><div class='"+classes[12]+"'><div id='mCSB_"+d.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"], + wrapperClass=o.axis==="yx" ? "mCSB_vertical_horizontal" : o.axis==="x" ? "mCSB_horizontal" : "mCSB_vertical", + scrollbars=o.axis==="yx" ? scrollbar[0]+scrollbar[1] : o.axis==="x" ? scrollbar[1] : scrollbar[0], + contentWrapper=o.axis==="yx" ? "<div id='mCSB_"+d.idx+"_container_wrapper' class='mCSB_container_wrapper' />" : "", + autoHideClass=o.autoHideScrollbar ? " "+classes[6] : "", + scrollbarDirClass=(o.axis!=="x" && d.langDir==="rtl") ? " "+classes[7] : ""; + if(o.setWidth){$this.css("width",o.setWidth);} /* set element width */ + if(o.setHeight){$this.css("height",o.setHeight);} /* set element height */ + o.setLeft=(o.axis!=="y" && d.langDir==="rtl") ? "989999px" : o.setLeft; /* adjust left position for rtl direction */ + $this.addClass(pluginNS+" _"+pluginPfx+"_"+d.idx+autoHideClass+scrollbarDirClass).wrapInner("<div id='mCSB_"+d.idx+"' class='mCustomScrollBox mCS-"+o.theme+" "+wrapperClass+"'><div id='mCSB_"+d.idx+"_container' class='mCSB_container' style='position:relative; top:"+o.setTop+"; left:"+o.setLeft+";' dir="+d.langDir+" /></div>"); + var mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"); + if(o.axis!=="y" && !o.advanced.autoExpandHorizontalScroll){ + mCSB_container.css("width",_contentWidth(mCSB_container)); + } + if(o.scrollbarPosition==="outside"){ + if($this.css("position")==="static"){ /* requires elements with non-static position */ + $this.css("position","relative"); + } + $this.css("overflow","visible"); + mCustomScrollBox.addClass("mCSB_outside").after(scrollbars); + }else{ + mCustomScrollBox.addClass("mCSB_inside").append(scrollbars); + mCSB_container.wrap(contentWrapper); + } + _scrollButtons.call(this); /* add scrollbar buttons */ + /* minimum dragger length */ + var mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")]; + mCSB_dragger[0].css("min-height",mCSB_dragger[0].height()); + mCSB_dragger[1].css("min-width",mCSB_dragger[1].width()); + }, + /* -------------------- */ + + + /* calculates content width */ + _contentWidth=function(el){ + var val=[el[0].scrollWidth,Math.max.apply(Math,el.children().map(function(){return $(this).outerWidth(true);}).get())],w=el.parent().width(); + return val[0]>w ? val[0] : val[1]>w ? val[1] : "100%"; + }, + /* -------------------- */ + + + /* expands content horizontally */ + _expandContentHorizontally=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + mCSB_container=$("#mCSB_"+d.idx+"_container"); + if(o.advanced.autoExpandHorizontalScroll && o.axis!=="y"){ + /* calculate scrollWidth */ + mCSB_container.css({"width":"auto","min-width":0,"overflow-x":"scroll"}); + var w=Math.ceil(mCSB_container[0].scrollWidth); + if(o.advanced.autoExpandHorizontalScroll===3 || (o.advanced.autoExpandHorizontalScroll!==2 && w>mCSB_container.parent().width())){ + mCSB_container.css({"width":w,"min-width":"100%","overflow-x":"inherit"}); + }else{ + /* + wrap content with an infinite width div and set its position to absolute and width to auto. + Setting width to auto before calculating the actual width is important! + We must let the browser set the width as browser zoom values are impossible to calculate. + */ + mCSB_container.css({"overflow-x":"inherit","position":"absolute"}) + .wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />") + .css({ /* set actual width, original position and un-wrap */ + /* + get the exact width (with decimals) and then round-up. + Using jquery outerWidth() will round the width value which will mess up with inner elements that have non-integer width + */ + "width":(Math.ceil(mCSB_container[0].getBoundingClientRect().right+0.4)-Math.floor(mCSB_container[0].getBoundingClientRect().left)), + "min-width":"100%", + "position":"relative" + }).unwrap(); + } + } + }, + /* -------------------- */ + + + /* adds scrollbar buttons */ + _scrollButtons=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + mCSB_scrollTools=$(".mCSB_"+d.idx+"_scrollbar:first"), + tabindex=!_isNumeric(o.scrollButtons.tabindex) ? "" : "tabindex='"+o.scrollButtons.tabindex+"'", + btnHTML=[ + "<a href='#' class='"+classes[13]+"' oncontextmenu='return false;' "+tabindex+" />", + "<a href='#' class='"+classes[14]+"' oncontextmenu='return false;' "+tabindex+" />", + "<a href='#' class='"+classes[15]+"' oncontextmenu='return false;' "+tabindex+" />", + "<a href='#' class='"+classes[16]+"' oncontextmenu='return false;' "+tabindex+" />" + ], + btn=[(o.axis==="x" ? btnHTML[2] : btnHTML[0]),(o.axis==="x" ? btnHTML[3] : btnHTML[1]),btnHTML[2],btnHTML[3]]; + if(o.scrollButtons.enable){ + mCSB_scrollTools.prepend(btn[0]).append(btn[1]).next(".mCSB_scrollTools").prepend(btn[2]).append(btn[3]); + } + }, + /* -------------------- */ + + + /* auto-adjusts scrollbar dragger length */ + _setDraggerLength=function(){ + var $this=$(this),d=$this.data(pluginPfx), + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")], + ratio=[mCustomScrollBox.height()/mCSB_container.outerHeight(false),mCustomScrollBox.width()/mCSB_container.outerWidth(false)], + l=[ + parseInt(mCSB_dragger[0].css("min-height")),Math.round(ratio[0]*mCSB_dragger[0].parent().height()), + parseInt(mCSB_dragger[1].css("min-width")),Math.round(ratio[1]*mCSB_dragger[1].parent().width()) + ], + h=oldIE && (l[1]<l[0]) ? l[0] : l[1],w=oldIE && (l[3]<l[2]) ? l[2] : l[3]; + mCSB_dragger[0].css({ + "height":h,"max-height":(mCSB_dragger[0].parent().height()-10) + }).find(".mCSB_dragger_bar").css({"line-height":l[0]+"px"}); + mCSB_dragger[1].css({ + "width":w,"max-width":(mCSB_dragger[1].parent().width()-10) + }); + }, + /* -------------------- */ + + + /* calculates scrollbar to content ratio */ + _scrollRatio=function(){ + var $this=$(this),d=$this.data(pluginPfx), + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")], + scrollAmount=[mCSB_container.outerHeight(false)-mCustomScrollBox.height(),mCSB_container.outerWidth(false)-mCustomScrollBox.width()], + ratio=[ + scrollAmount[0]/(mCSB_dragger[0].parent().height()-mCSB_dragger[0].height()), + scrollAmount[1]/(mCSB_dragger[1].parent().width()-mCSB_dragger[1].width()) + ]; + d.scrollRatio={y:ratio[0],x:ratio[1]}; + }, + /* -------------------- */ + + + /* toggles scrolling classes */ + _onDragClasses=function(el,action,xpnd){ + var expandClass=xpnd ? classes[0]+"_expanded" : "", + scrollbar=el.closest(".mCSB_scrollTools"); + if(action==="active"){ + el.toggleClass(classes[0]+" "+expandClass); scrollbar.toggleClass(classes[1]); + el[0]._draggable=el[0]._draggable ? 0 : 1; + }else{ + if(!el[0]._draggable){ + if(action==="hide"){ + el.removeClass(classes[0]); scrollbar.removeClass(classes[1]); + }else{ + el.addClass(classes[0]); scrollbar.addClass(classes[1]); + } + } + } + }, + /* -------------------- */ + + + /* checks if content overflows its container to determine if scrolling is required */ + _overflowed=function(){ + var $this=$(this),d=$this.data(pluginPfx), + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + contentHeight=d.overflowed==null ? mCSB_container.height() : mCSB_container.outerHeight(false), + contentWidth=d.overflowed==null ? mCSB_container.width() : mCSB_container.outerWidth(false), + h=mCSB_container[0].scrollHeight,w=mCSB_container[0].scrollWidth; + if(h>contentHeight){contentHeight=h;} + if(w>contentWidth){contentWidth=w;} + return [contentHeight>mCustomScrollBox.height(),contentWidth>mCustomScrollBox.width()]; + }, + /* -------------------- */ + + + /* resets content position to 0 */ + _resetContentPosition=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")]; + _stop($this); /* stop any current scrolling before resetting */ + if((o.axis!=="x" && !d.overflowed[0]) || (o.axis==="y" && d.overflowed[0])){ /* reset y */ + mCSB_dragger[0].add(mCSB_container).css("top",0); + _scrollTo($this,"_resetY"); + } + if((o.axis!=="y" && !d.overflowed[1]) || (o.axis==="x" && d.overflowed[1])){ /* reset x */ + var cx=dx=0; + if(d.langDir==="rtl"){ /* adjust left position for rtl direction */ + cx=mCustomScrollBox.width()-mCSB_container.outerWidth(false); + dx=Math.abs(cx/d.scrollRatio.x); + } + mCSB_container.css("left",cx); + mCSB_dragger[1].css("left",dx); + _scrollTo($this,"_resetX"); + } + }, + /* -------------------- */ + + + /* binds scrollbar events */ + _bindEvents=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt; + if(!d.bindEvents){ /* check if events are already bound */ + _draggable.call(this); + if(o.contentTouchScroll){_contentDraggable.call(this);} + _selectable.call(this); + if(o.mouseWheel.enable){ /* bind mousewheel fn when plugin is available */ + function _mwt(){ + mousewheelTimeout=setTimeout(function(){ + if(!$.event.special.mousewheel){ + _mwt(); + }else{ + clearTimeout(mousewheelTimeout); + _mousewheel.call($this[0]); + } + },100); + } + var mousewheelTimeout; + _mwt(); + } + _draggerRail.call(this); + _wrapperScroll.call(this); + if(o.advanced.autoScrollOnFocus){_focus.call(this);} + if(o.scrollButtons.enable){_buttons.call(this);} + if(o.keyboard.enable){_keyboard.call(this);} + d.bindEvents=true; + } + }, + /* -------------------- */ + + + /* unbinds scrollbar events */ + _unbindEvents=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + namespace=pluginPfx+"_"+d.idx, + sb=".mCSB_"+d.idx+"_scrollbar", + sel=$("#mCSB_"+d.idx+",#mCSB_"+d.idx+"_container,#mCSB_"+d.idx+"_container_wrapper,"+sb+" ."+classes[12]+",#mCSB_"+d.idx+"_dragger_vertical,#mCSB_"+d.idx+"_dragger_horizontal,"+sb+">a"), + mCSB_container=$("#mCSB_"+d.idx+"_container"); + if(o.advanced.releaseDraggableSelectors){sel.add($(o.advanced.releaseDraggableSelectors));} + if(o.advanced.extraDraggableSelectors){sel.add($(o.advanced.extraDraggableSelectors));} + if(d.bindEvents){ /* check if events are bound */ + /* unbind namespaced events from document/selectors */ + $(document).add($(!_canAccessIFrame() || top.document)).unbind("."+namespace); + sel.each(function(){ + $(this).unbind("."+namespace); + }); + /* clear and delete timeouts/objects */ + clearTimeout($this[0]._focusTimeout); _delete($this[0],"_focusTimeout"); + clearTimeout(d.sequential.step); _delete(d.sequential,"step"); + clearTimeout(mCSB_container[0].onCompleteTimeout); _delete(mCSB_container[0],"onCompleteTimeout"); + d.bindEvents=false; + } + }, + /* -------------------- */ + + + /* toggles scrollbar visibility */ + _scrollbarVisibility=function(disabled){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + contentWrapper=$("#mCSB_"+d.idx+"_container_wrapper"), + content=contentWrapper.length ? contentWrapper : $("#mCSB_"+d.idx+"_container"), + scrollbar=[$("#mCSB_"+d.idx+"_scrollbar_vertical"),$("#mCSB_"+d.idx+"_scrollbar_horizontal")], + mCSB_dragger=[scrollbar[0].find(".mCSB_dragger"),scrollbar[1].find(".mCSB_dragger")]; + if(o.axis!=="x"){ + if(d.overflowed[0] && !disabled){ + scrollbar[0].add(mCSB_dragger[0]).add(scrollbar[0].children("a")).css("display","block"); + content.removeClass(classes[8]+" "+classes[10]); + }else{ + if(o.alwaysShowScrollbar){ + if(o.alwaysShowScrollbar!==2){mCSB_dragger[0].css("display","none");} + content.removeClass(classes[10]); + }else{ + scrollbar[0].css("display","none"); + content.addClass(classes[10]); + } + content.addClass(classes[8]); + } + } + if(o.axis!=="y"){ + if(d.overflowed[1] && !disabled){ + scrollbar[1].add(mCSB_dragger[1]).add(scrollbar[1].children("a")).css("display","block"); + content.removeClass(classes[9]+" "+classes[11]); + }else{ + if(o.alwaysShowScrollbar){ + if(o.alwaysShowScrollbar!==2){mCSB_dragger[1].css("display","none");} + content.removeClass(classes[11]); + }else{ + scrollbar[1].css("display","none"); + content.addClass(classes[11]); + } + content.addClass(classes[9]); + } + } + if(!d.overflowed[0] && !d.overflowed[1]){ + $this.addClass(classes[5]); + }else{ + $this.removeClass(classes[5]); + } + }, + /* -------------------- */ + + + /* returns input coordinates of pointer, touch and mouse events (relative to document) */ + _coordinates=function(e){ + var t=e.type,o=e.target.ownerDocument!==document ? [$(frameElement).offset().top,$(frameElement).offset().left] : null, + io=_canAccessIFrame() && e.target.ownerDocument!==top.document ? [$(e.view.frameElement).offset().top,$(e.view.frameElement).offset().left] : [0,0]; + switch(t){ + case "pointerdown": case "MSPointerDown": case "pointermove": case "MSPointerMove": case "pointerup": case "MSPointerUp": + return o ? [e.originalEvent.pageY-o[0]+io[0],e.originalEvent.pageX-o[1]+io[1],false] : [e.originalEvent.pageY,e.originalEvent.pageX,false]; + break; + case "touchstart": case "touchmove": case "touchend": + var touch=e.originalEvent.touches[0] || e.originalEvent.changedTouches[0], + touches=e.originalEvent.touches.length || e.originalEvent.changedTouches.length; + return e.target.ownerDocument!==document ? [touch.screenY,touch.screenX,touches>1] : [touch.pageY,touch.pageX,touches>1]; + break; + default: + return o ? [e.pageY-o[0]+io[0],e.pageX-o[1]+io[1],false] : [e.pageY,e.pageX,false]; + } + }, + /* -------------------- */ + + + /* + SCROLLBAR DRAG EVENTS + scrolls content via scrollbar dragging + */ + _draggable=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + namespace=pluginPfx+"_"+d.idx, + draggerId=["mCSB_"+d.idx+"_dragger_vertical","mCSB_"+d.idx+"_dragger_horizontal"], + mCSB_container=$("#mCSB_"+d.idx+"_container"), + mCSB_dragger=$("#"+draggerId[0]+",#"+draggerId[1]), + draggable,dragY,dragX, + rds=o.advanced.releaseDraggableSelectors ? mCSB_dragger.add($(o.advanced.releaseDraggableSelectors)) : mCSB_dragger, + eds=o.advanced.extraDraggableSelectors ? $(!_canAccessIFrame() || top.document).add($(o.advanced.extraDraggableSelectors)) : $(!_canAccessIFrame() || top.document); + mCSB_dragger.bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace,function(e){ + e.stopImmediatePropagation(); + e.preventDefault(); + if(!_mouseBtnLeft(e)){return;} /* left mouse button only */ + touchActive=true; + if(oldIE){document.onselectstart=function(){return false;}} /* disable text selection for IE < 9 */ + _iframe(false); /* enable scrollbar dragging over iframes by disabling their events */ + _stop($this); + draggable=$(this); + var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left, + h=draggable.height()+offset.top,w=draggable.width()+offset.left; + if(y<h && y>0 && x<w && x>0){ + dragY=y; + dragX=x; + } + _onDragClasses(draggable,"active",o.autoExpandScrollbar); + }).bind("touchmove."+namespace,function(e){ + e.stopImmediatePropagation(); + e.preventDefault(); + var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left; + _drag(dragY,dragX,y,x); + }); + $(document).add(eds).bind("mousemove."+namespace+" pointermove."+namespace+" MSPointerMove."+namespace,function(e){ + if(draggable){ + var offset=draggable.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left; + if(dragY===y && dragX===x){return;} /* has it really moved? */ + _drag(dragY,dragX,y,x); + } + }).add(rds).bind("mouseup."+namespace+" touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace,function(e){ + if(draggable){ + _onDragClasses(draggable,"active",o.autoExpandScrollbar); + draggable=null; + } + touchActive=false; + if(oldIE){document.onselectstart=null;} /* enable text selection for IE < 9 */ + _iframe(true); /* enable iframes events */ + }); + function _iframe(evt){ + var el=mCSB_container.find("iframe"); + if(!el.length){return;} /* check if content contains iframes */ + var val=!evt ? "none" : "auto"; + el.css("pointer-events",val); /* for IE11, iframe's display property should not be "block" */ + } + function _drag(dragY,dragX,y,x){ + mCSB_container[0].idleTimer=o.scrollInertia<233 ? 250 : 0; + if(draggable.attr("id")===draggerId[1]){ + var dir="x",to=((draggable[0].offsetLeft-dragX)+x)*d.scrollRatio.x; + }else{ + var dir="y",to=((draggable[0].offsetTop-dragY)+y)*d.scrollRatio.y; + } + _scrollTo($this,to.toString(),{dir:dir,drag:true}); + } + }, + /* -------------------- */ + + + /* + TOUCH SWIPE EVENTS + scrolls content via touch swipe + Emulates the native touch-swipe scrolling with momentum found in iOS, Android and WP devices + */ + _contentDraggable=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + namespace=pluginPfx+"_"+d.idx, + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")], + draggable,dragY,dragX,touchStartY,touchStartX,touchMoveY=[],touchMoveX=[],startTime,runningTime,endTime,distance,speed,amount, + durA=0,durB,overwrite=o.axis==="yx" ? "none" : "all",touchIntent=[],touchDrag,docDrag, + iframe=mCSB_container.find("iframe"), + events=[ + "touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace, //start + "touchmove."+namespace+" pointermove."+namespace+" MSPointerMove."+namespace, //move + "touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace //end + ], + touchAction=document.body.style.touchAction!==undefined; + mCSB_container.bind(events[0],function(e){ + _onTouchstart(e); + }).bind(events[1],function(e){ + _onTouchmove(e); + }); + mCustomScrollBox.bind(events[0],function(e){ + _onTouchstart2(e); + }).bind(events[2],function(e){ + _onTouchend(e); + }); + if(iframe.length){ + iframe.each(function(){ + $(this).load(function(){ + /* bind events on accessible iframes */ + if(_canAccessIFrame(this)){ + $(this.contentDocument || this.contentWindow.document).bind(events[0],function(e){ + _onTouchstart(e); + _onTouchstart2(e); + }).bind(events[1],function(e){ + _onTouchmove(e); + }).bind(events[2],function(e){ + _onTouchend(e); + }); + } + }); + }); + } + function _onTouchstart(e){ + if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){touchable=0; return;} + touchable=1; touchDrag=0; docDrag=0; draggable=1; + $this.removeClass("mCS_touch_action"); + var offset=mCSB_container.offset(); + dragY=_coordinates(e)[0]-offset.top; + dragX=_coordinates(e)[1]-offset.left; + touchIntent=[_coordinates(e)[0],_coordinates(e)[1]]; + } + function _onTouchmove(e){ + if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){return;} + if(!o.documentTouchScroll){e.preventDefault();} + e.stopImmediatePropagation(); + if(docDrag && !touchDrag){return;} + if(draggable){ + runningTime=_getTime(); + var offset=mCustomScrollBox.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left, + easing="mcsLinearOut"; + touchMoveY.push(y); + touchMoveX.push(x); + touchIntent[2]=Math.abs(_coordinates(e)[0]-touchIntent[0]); touchIntent[3]=Math.abs(_coordinates(e)[1]-touchIntent[1]); + if(d.overflowed[0]){ + var limit=mCSB_dragger[0].parent().height()-mCSB_dragger[0].height(), + prevent=((dragY-y)>0 && (y-dragY)>-(limit*d.scrollRatio.y) && (touchIntent[3]*2<touchIntent[2] || o.axis==="yx")); + } + if(d.overflowed[1]){ + var limitX=mCSB_dragger[1].parent().width()-mCSB_dragger[1].width(), + preventX=((dragX-x)>0 && (x-dragX)>-(limitX*d.scrollRatio.x) && (touchIntent[2]*2<touchIntent[3] || o.axis==="yx")); + } + if(prevent || preventX){ /* prevent native document scrolling */ + if(!touchAction){e.preventDefault();} + touchDrag=1; + }else{ + docDrag=1; + $this.addClass("mCS_touch_action"); + } + if(touchAction){e.preventDefault();} + amount=o.axis==="yx" ? [(dragY-y),(dragX-x)] : o.axis==="x" ? [null,(dragX-x)] : [(dragY-y),null]; + mCSB_container[0].idleTimer=250; + if(d.overflowed[0]){_drag(amount[0],durA,easing,"y","all",true);} + if(d.overflowed[1]){_drag(amount[1],durA,easing,"x",overwrite,true);} + } + } + function _onTouchstart2(e){ + if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){touchable=0; return;} + touchable=1; + e.stopImmediatePropagation(); + _stop($this); + startTime=_getTime(); + var offset=mCustomScrollBox.offset(); + touchStartY=_coordinates(e)[0]-offset.top; + touchStartX=_coordinates(e)[1]-offset.left; + touchMoveY=[]; touchMoveX=[]; + } + function _onTouchend(e){ + if(!_pointerTouch(e) || touchActive || _coordinates(e)[2]){return;} + draggable=0; + e.stopImmediatePropagation(); + touchDrag=0; docDrag=0; + endTime=_getTime(); + var offset=mCustomScrollBox.offset(),y=_coordinates(e)[0]-offset.top,x=_coordinates(e)[1]-offset.left; + if((endTime-runningTime)>30){return;} + speed=1000/(endTime-startTime); + var easing="mcsEaseOut",slow=speed<2.5, + diff=slow ? [touchMoveY[touchMoveY.length-2],touchMoveX[touchMoveX.length-2]] : [0,0]; + distance=slow ? [(y-diff[0]),(x-diff[1])] : [y-touchStartY,x-touchStartX]; + var absDistance=[Math.abs(distance[0]),Math.abs(distance[1])]; + speed=slow ? [Math.abs(distance[0]/4),Math.abs(distance[1]/4)] : [speed,speed]; + var a=[ + Math.abs(mCSB_container[0].offsetTop)-(distance[0]*_m((absDistance[0]/speed[0]),speed[0])), + Math.abs(mCSB_container[0].offsetLeft)-(distance[1]*_m((absDistance[1]/speed[1]),speed[1])) + ]; + amount=o.axis==="yx" ? [a[0],a[1]] : o.axis==="x" ? [null,a[1]] : [a[0],null]; + durB=[(absDistance[0]*4)+o.scrollInertia,(absDistance[1]*4)+o.scrollInertia]; + var md=parseInt(o.contentTouchScroll) || 0; /* absolute minimum distance required */ + amount[0]=absDistance[0]>md ? amount[0] : 0; + amount[1]=absDistance[1]>md ? amount[1] : 0; + if(d.overflowed[0]){_drag(amount[0],durB[0],easing,"y",overwrite,false);} + if(d.overflowed[1]){_drag(amount[1],durB[1],easing,"x",overwrite,false);} + } + function _m(ds,s){ + var r=[s*1.5,s*2,s/1.5,s/2]; + if(ds>90){ + return s>4 ? r[0] : r[3]; + }else if(ds>60){ + return s>3 ? r[3] : r[2]; + }else if(ds>30){ + return s>8 ? r[1] : s>6 ? r[0] : s>4 ? s : r[2]; + }else{ + return s>8 ? s : r[3]; + } + } + function _drag(amount,dur,easing,dir,overwrite,drag){ + if(!amount){return;} + _scrollTo($this,amount.toString(),{dur:dur,scrollEasing:easing,dir:dir,overwrite:overwrite,drag:drag}); + } + }, + /* -------------------- */ + + + /* + SELECT TEXT EVENTS + scrolls content when text is selected + */ + _selectable=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential, + namespace=pluginPfx+"_"+d.idx, + mCSB_container=$("#mCSB_"+d.idx+"_container"), + wrapper=mCSB_container.parent(), + action; + mCSB_container.bind("mousedown."+namespace,function(e){ + if(touchable){return;} + if(!action){action=1; touchActive=true;} + }).add(document).bind("mousemove."+namespace,function(e){ + if(!touchable && action && _sel()){ + var offset=mCSB_container.offset(), + y=_coordinates(e)[0]-offset.top+mCSB_container[0].offsetTop,x=_coordinates(e)[1]-offset.left+mCSB_container[0].offsetLeft; + if(y>0 && y<wrapper.height() && x>0 && x<wrapper.width()){ + if(seq.step){_seq("off",null,"stepped");} + }else{ + if(o.axis!=="x" && d.overflowed[0]){ + if(y<0){ + _seq("on",38); + }else if(y>wrapper.height()){ + _seq("on",40); + } + } + if(o.axis!=="y" && d.overflowed[1]){ + if(x<0){ + _seq("on",37); + }else if(x>wrapper.width()){ + _seq("on",39); + } + } + } + } + }).bind("mouseup."+namespace+" dragend."+namespace,function(e){ + if(touchable){return;} + if(action){action=0; _seq("off",null);} + touchActive=false; + }); + function _sel(){ + return window.getSelection ? window.getSelection().toString() : + document.selection && document.selection.type!="Control" ? document.selection.createRange().text : 0; + } + function _seq(a,c,s){ + seq.type=s && action ? "stepped" : "stepless"; + seq.scrollAmount=10; + _sequentialScroll($this,a,c,"mcsLinearOut",s ? 60 : null); + } + }, + /* -------------------- */ + + + /* + MOUSE WHEEL EVENT + scrolls content via mouse-wheel + via mouse-wheel plugin (https://github.com/brandonaaron/jquery-mousewheel) + */ + _mousewheel=function(){ + if(!$(this).data(pluginPfx)){return;} /* Check if the scrollbar is ready to use mousewheel events (issue: #185) */ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + namespace=pluginPfx+"_"+d.idx, + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_dragger=[$("#mCSB_"+d.idx+"_dragger_vertical"),$("#mCSB_"+d.idx+"_dragger_horizontal")], + iframe=$("#mCSB_"+d.idx+"_container").find("iframe"); + if(iframe.length){ + iframe.each(function(){ + $(this).load(function(){ + /* bind events on accessible iframes */ + if(_canAccessIFrame(this)){ + $(this.contentDocument || this.contentWindow.document).bind("mousewheel."+namespace,function(e,delta){ + _onMousewheel(e,delta); + }); + } + }); + }); + } + mCustomScrollBox.bind("mousewheel."+namespace,function(e,delta){ + _onMousewheel(e,delta); + }); + function _onMousewheel(e,delta){ + _stop($this); + if(_disableMousewheel($this,e.target)){return;} /* disables mouse-wheel when hovering specific elements */ + var deltaFactor=o.mouseWheel.deltaFactor!=="auto" ? parseInt(o.mouseWheel.deltaFactor) : (oldIE && e.deltaFactor<100) ? 100 : e.deltaFactor || 100, + dur=o.scrollInertia; + if(o.axis==="x" || o.mouseWheel.axis==="x"){ + var dir="x", + px=[Math.round(deltaFactor*d.scrollRatio.x),parseInt(o.mouseWheel.scrollAmount)], + amount=o.mouseWheel.scrollAmount!=="auto" ? px[1] : px[0]>=mCustomScrollBox.width() ? mCustomScrollBox.width()*0.9 : px[0], + contentPos=Math.abs($("#mCSB_"+d.idx+"_container")[0].offsetLeft), + draggerPos=mCSB_dragger[1][0].offsetLeft, + limit=mCSB_dragger[1].parent().width()-mCSB_dragger[1].width(), + dlt=e.deltaX || e.deltaY || delta; + }else{ + var dir="y", + px=[Math.round(deltaFactor*d.scrollRatio.y),parseInt(o.mouseWheel.scrollAmount)], + amount=o.mouseWheel.scrollAmount!=="auto" ? px[1] : px[0]>=mCustomScrollBox.height() ? mCustomScrollBox.height()*0.9 : px[0], + contentPos=Math.abs($("#mCSB_"+d.idx+"_container")[0].offsetTop), + draggerPos=mCSB_dragger[0][0].offsetTop, + limit=mCSB_dragger[0].parent().height()-mCSB_dragger[0].height(), + dlt=e.deltaY || delta; + } + if((dir==="y" && !d.overflowed[0]) || (dir==="x" && !d.overflowed[1])){return;} + if(o.mouseWheel.invert || e.webkitDirectionInvertedFromDevice){dlt=-dlt;} + if(o.mouseWheel.normalizeDelta){dlt=dlt<0 ? -1 : 1;} + if((dlt>0 && draggerPos!==0) || (dlt<0 && draggerPos!==limit) || o.mouseWheel.preventDefault){ + e.stopImmediatePropagation(); + e.preventDefault(); + } + if(e.deltaFactor<2 && !o.mouseWheel.normalizeDelta){ + //very low deltaFactor values mean some kind of delta acceleration (e.g. osx trackpad), so adjusting scrolling accordingly + amount=e.deltaFactor; dur=17; + } + _scrollTo($this,(contentPos-(dlt*amount)).toString(),{dir:dir,dur:dur}); + } + }, + /* -------------------- */ + + + /* checks if iframe can be accessed */ + _canAccessIFrame=function(iframe){ + var html=null; + if(!iframe){ + try{ + var doc=top.document; + html=doc.body.innerHTML; + }catch(err){/* do nothing */} + return(html!==null); + }else{ + try{ + var doc=iframe.contentDocument || iframe.contentWindow.document; + html=doc.body.innerHTML; + }catch(err){/* do nothing */} + return(html!==null); + } + }, + /* -------------------- */ + + + /* disables mouse-wheel when hovering specific elements like select, datalist etc. */ + _disableMousewheel=function(el,target){ + var tag=target.nodeName.toLowerCase(), + tags=el.data(pluginPfx).opt.mouseWheel.disableOver, + /* elements that require focus */ + focusTags=["select","textarea"]; + return $.inArray(tag,tags) > -1 && !($.inArray(tag,focusTags) > -1 && !$(target).is(":focus")); + }, + /* -------------------- */ + + + /* + DRAGGER RAIL CLICK EVENT + scrolls content via dragger rail + */ + _draggerRail=function(){ + var $this=$(this),d=$this.data(pluginPfx), + namespace=pluginPfx+"_"+d.idx, + mCSB_container=$("#mCSB_"+d.idx+"_container"), + wrapper=mCSB_container.parent(), + mCSB_draggerContainer=$(".mCSB_"+d.idx+"_scrollbar ."+classes[12]), + clickable; + mCSB_draggerContainer.bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace,function(e){ + touchActive=true; + if(!$(e.target).hasClass("mCSB_dragger")){clickable=1;} + }).bind("touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace,function(e){ + touchActive=false; + }).bind("click."+namespace,function(e){ + if(!clickable){return;} + clickable=0; + if($(e.target).hasClass(classes[12]) || $(e.target).hasClass("mCSB_draggerRail")){ + _stop($this); + var el=$(this),mCSB_dragger=el.find(".mCSB_dragger"); + if(el.parent(".mCSB_scrollTools_horizontal").length>0){ + if(!d.overflowed[1]){return;} + var dir="x", + clickDir=e.pageX>mCSB_dragger.offset().left ? -1 : 1, + to=Math.abs(mCSB_container[0].offsetLeft)-(clickDir*(wrapper.width()*0.9)); + }else{ + if(!d.overflowed[0]){return;} + var dir="y", + clickDir=e.pageY>mCSB_dragger.offset().top ? -1 : 1, + to=Math.abs(mCSB_container[0].offsetTop)-(clickDir*(wrapper.height()*0.9)); + } + _scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"}); + } + }); + }, + /* -------------------- */ + + + /* + FOCUS EVENT + scrolls content via element focus (e.g. clicking an input, pressing TAB key etc.) + */ + _focus=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + namespace=pluginPfx+"_"+d.idx, + mCSB_container=$("#mCSB_"+d.idx+"_container"), + wrapper=mCSB_container.parent(); + mCSB_container.bind("focusin."+namespace,function(e){ + var el=$(document.activeElement), + nested=mCSB_container.find(".mCustomScrollBox").length, + dur=0; + if(!el.is(o.advanced.autoScrollOnFocus)){return;} + _stop($this); + clearTimeout($this[0]._focusTimeout); + $this[0]._focusTimer=nested ? (dur+17)*nested : 0; + $this[0]._focusTimeout=setTimeout(function(){ + var to=[_childPos(el)[0],_childPos(el)[1]], + contentPos=[mCSB_container[0].offsetTop,mCSB_container[0].offsetLeft], + isVisible=[ + (contentPos[0]+to[0]>=0 && contentPos[0]+to[0]<wrapper.height()-el.outerHeight(false)), + (contentPos[1]+to[1]>=0 && contentPos[0]+to[1]<wrapper.width()-el.outerWidth(false)) + ], + overwrite=(o.axis==="yx" && !isVisible[0] && !isVisible[1]) ? "none" : "all"; + if(o.axis!=="x" && !isVisible[0]){ + _scrollTo($this,to[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:overwrite,dur:dur}); + } + if(o.axis!=="y" && !isVisible[1]){ + _scrollTo($this,to[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:overwrite,dur:dur}); + } + },$this[0]._focusTimer); + }); + }, + /* -------------------- */ + + + /* sets content wrapper scrollTop/scrollLeft always to 0 */ + _wrapperScroll=function(){ + var $this=$(this),d=$this.data(pluginPfx), + namespace=pluginPfx+"_"+d.idx, + wrapper=$("#mCSB_"+d.idx+"_container").parent(); + wrapper.bind("scroll."+namespace,function(e){ + if(wrapper.scrollTop()!==0 || wrapper.scrollLeft()!==0){ + $(".mCSB_"+d.idx+"_scrollbar").css("visibility","hidden"); /* hide scrollbar(s) */ + } + }); + }, + /* -------------------- */ + + + /* + BUTTONS EVENTS + scrolls content via up, down, left and right buttons + */ + _buttons=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential, + namespace=pluginPfx+"_"+d.idx, + sel=".mCSB_"+d.idx+"_scrollbar", + btn=$(sel+">a"); + btn.bind("mousedown."+namespace+" touchstart."+namespace+" pointerdown."+namespace+" MSPointerDown."+namespace+" mouseup."+namespace+" touchend."+namespace+" pointerup."+namespace+" MSPointerUp."+namespace+" mouseout."+namespace+" pointerout."+namespace+" MSPointerOut."+namespace+" click."+namespace,function(e){ + e.preventDefault(); + if(!_mouseBtnLeft(e)){return;} /* left mouse button only */ + var btnClass=$(this).attr("class"); + seq.type=o.scrollButtons.scrollType; + switch(e.type){ + case "mousedown": case "touchstart": case "pointerdown": case "MSPointerDown": + if(seq.type==="stepped"){return;} + touchActive=true; + d.tweenRunning=false; + _seq("on",btnClass); + break; + case "mouseup": case "touchend": case "pointerup": case "MSPointerUp": + case "mouseout": case "pointerout": case "MSPointerOut": + if(seq.type==="stepped"){return;} + touchActive=false; + if(seq.dir){_seq("off",btnClass);} + break; + case "click": + if(seq.type!=="stepped" || d.tweenRunning){return;} + _seq("on",btnClass); + break; + } + function _seq(a,c){ + seq.scrollAmount=o.scrollButtons.scrollAmount; + _sequentialScroll($this,a,c); + } + }); + }, + /* -------------------- */ + + + /* + KEYBOARD EVENTS + scrolls content via keyboard + Keys: up arrow, down arrow, left arrow, right arrow, PgUp, PgDn, Home, End + */ + _keyboard=function(){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt,seq=d.sequential, + namespace=pluginPfx+"_"+d.idx, + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + wrapper=mCSB_container.parent(), + editables="input,textarea,select,datalist,keygen,[contenteditable='true']", + iframe=mCSB_container.find("iframe"), + events=["blur."+namespace+" keydown."+namespace+" keyup."+namespace]; + if(iframe.length){ + iframe.each(function(){ + $(this).load(function(){ + /* bind events on accessible iframes */ + if(_canAccessIFrame(this)){ + $(this.contentDocument || this.contentWindow.document).bind(events[0],function(e){ + _onKeyboard(e); + }); + } + }); + }); + } + mCustomScrollBox.attr("tabindex","0").bind(events[0],function(e){ + _onKeyboard(e); + }); + function _onKeyboard(e){ + switch(e.type){ + case "blur": + if(d.tweenRunning && seq.dir){_seq("off",null);} + break; + case "keydown": case "keyup": + var code=e.keyCode ? e.keyCode : e.which,action="on"; + if((o.axis!=="x" && (code===38 || code===40)) || (o.axis!=="y" && (code===37 || code===39))){ + /* up (38), down (40), left (37), right (39) arrows */ + if(((code===38 || code===40) && !d.overflowed[0]) || ((code===37 || code===39) && !d.overflowed[1])){return;} + if(e.type==="keyup"){action="off";} + if(!$(document.activeElement).is(editables)){ + e.preventDefault(); + e.stopImmediatePropagation(); + _seq(action,code); + } + }else if(code===33 || code===34){ + /* PgUp (33), PgDn (34) */ + if(d.overflowed[0] || d.overflowed[1]){ + e.preventDefault(); + e.stopImmediatePropagation(); + } + if(e.type==="keyup"){ + _stop($this); + var keyboardDir=code===34 ? -1 : 1; + if(o.axis==="x" || (o.axis==="yx" && d.overflowed[1] && !d.overflowed[0])){ + var dir="x",to=Math.abs(mCSB_container[0].offsetLeft)-(keyboardDir*(wrapper.width()*0.9)); + }else{ + var dir="y",to=Math.abs(mCSB_container[0].offsetTop)-(keyboardDir*(wrapper.height()*0.9)); + } + _scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"}); + } + }else if(code===35 || code===36){ + /* End (35), Home (36) */ + if(!$(document.activeElement).is(editables)){ + if(d.overflowed[0] || d.overflowed[1]){ + e.preventDefault(); + e.stopImmediatePropagation(); + } + if(e.type==="keyup"){ + if(o.axis==="x" || (o.axis==="yx" && d.overflowed[1] && !d.overflowed[0])){ + var dir="x",to=code===35 ? Math.abs(wrapper.width()-mCSB_container.outerWidth(false)) : 0; + }else{ + var dir="y",to=code===35 ? Math.abs(wrapper.height()-mCSB_container.outerHeight(false)) : 0; + } + _scrollTo($this,to.toString(),{dir:dir,scrollEasing:"mcsEaseInOut"}); + } + } + } + break; + } + function _seq(a,c){ + seq.type=o.keyboard.scrollType; + seq.scrollAmount=o.keyboard.scrollAmount; + if(seq.type==="stepped" && d.tweenRunning){return;} + _sequentialScroll($this,a,c); + } + } + }, + /* -------------------- */ + + + /* scrolls content sequentially (used when scrolling via buttons, keyboard arrows etc.) */ + _sequentialScroll=function(el,action,trigger,e,s){ + var d=el.data(pluginPfx),o=d.opt,seq=d.sequential, + mCSB_container=$("#mCSB_"+d.idx+"_container"), + once=seq.type==="stepped" ? true : false, + steplessSpeed=o.scrollInertia < 26 ? 26 : o.scrollInertia, /* 26/1.5=17 */ + steppedSpeed=o.scrollInertia < 1 ? 17 : o.scrollInertia; + switch(action){ + case "on": + seq.dir=[ + (trigger===classes[16] || trigger===classes[15] || trigger===39 || trigger===37 ? "x" : "y"), + (trigger===classes[13] || trigger===classes[15] || trigger===38 || trigger===37 ? -1 : 1) + ]; + _stop(el); + if(_isNumeric(trigger) && seq.type==="stepped"){return;} + _on(once); + break; + case "off": + _off(); + if(once || (d.tweenRunning && seq.dir)){ + _on(true); + } + break; + } + + /* starts sequence */ + function _on(once){ + if(o.snapAmount){seq.scrollAmount=!(o.snapAmount instanceof Array) ? o.snapAmount : seq.dir[0]==="x" ? o.snapAmount[1] : o.snapAmount[0];} /* scrolling snapping */ + var c=seq.type!=="stepped", /* continuous scrolling */ + t=s ? s : !once ? 1000/60 : c ? steplessSpeed/1.5 : steppedSpeed, /* timer */ + m=!once ? 2.5 : c ? 7.5 : 40, /* multiplier */ + contentPos=[Math.abs(mCSB_container[0].offsetTop),Math.abs(mCSB_container[0].offsetLeft)], + ratio=[d.scrollRatio.y>10 ? 10 : d.scrollRatio.y,d.scrollRatio.x>10 ? 10 : d.scrollRatio.x], + amount=seq.dir[0]==="x" ? contentPos[1]+(seq.dir[1]*(ratio[1]*m)) : contentPos[0]+(seq.dir[1]*(ratio[0]*m)), + px=seq.dir[0]==="x" ? contentPos[1]+(seq.dir[1]*parseInt(seq.scrollAmount)) : contentPos[0]+(seq.dir[1]*parseInt(seq.scrollAmount)), + to=seq.scrollAmount!=="auto" ? px : amount, + easing=e ? e : !once ? "mcsLinear" : c ? "mcsLinearOut" : "mcsEaseInOut", + onComplete=!once ? false : true; + if(once && t<17){ + to=seq.dir[0]==="x" ? contentPos[1] : contentPos[0]; + } + _scrollTo(el,to.toString(),{dir:seq.dir[0],scrollEasing:easing,dur:t,onComplete:onComplete}); + if(once){ + seq.dir=false; + return; + } + clearTimeout(seq.step); + seq.step=setTimeout(function(){ + _on(); + },t); + } + /* stops sequence */ + function _off(){ + clearTimeout(seq.step); + _delete(seq,"step"); + _stop(el); + } + }, + /* -------------------- */ + + + /* returns a yx array from value */ + _arr=function(val){ + var o=$(this).data(pluginPfx).opt,vals=[]; + if(typeof val==="function"){val=val();} /* check if the value is a single anonymous function */ + /* check if value is object or array, its length and create an array with yx values */ + if(!(val instanceof Array)){ /* object value (e.g. {y:"100",x:"100"}, 100 etc.) */ + vals[0]=val.y ? val.y : val.x || o.axis==="x" ? null : val; + vals[1]=val.x ? val.x : val.y || o.axis==="y" ? null : val; + }else{ /* array value (e.g. [100,100]) */ + vals=val.length>1 ? [val[0],val[1]] : o.axis==="x" ? [null,val[0]] : [val[0],null]; + } + /* check if array values are anonymous functions */ + if(typeof vals[0]==="function"){vals[0]=vals[0]();} + if(typeof vals[1]==="function"){vals[1]=vals[1]();} + return vals; + }, + /* -------------------- */ + + + /* translates values (e.g. "top", 100, "100px", "#id") to actual scroll-to positions */ + _to=function(val,dir){ + if(val==null || typeof val=="undefined"){return;} + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + mCSB_container=$("#mCSB_"+d.idx+"_container"), + wrapper=mCSB_container.parent(), + t=typeof val; + if(!dir){dir=o.axis==="x" ? "x" : "y";} + var contentLength=dir==="x" ? mCSB_container.outerWidth(false) : mCSB_container.outerHeight(false), + contentPos=dir==="x" ? mCSB_container[0].offsetLeft : mCSB_container[0].offsetTop, + cssProp=dir==="x" ? "left" : "top"; + switch(t){ + case "function": /* this currently is not used. Consider removing it */ + return val(); + break; + case "object": /* js/jquery object */ + var obj=val.jquery ? val : $(val); + if(!obj.length){return;} + return dir==="x" ? _childPos(obj)[1] : _childPos(obj)[0]; + break; + case "string": case "number": + if(_isNumeric(val)){ /* numeric value */ + return Math.abs(val); + }else if(val.indexOf("%")!==-1){ /* percentage value */ + return Math.abs(contentLength*parseInt(val)/100); + }else if(val.indexOf("-=")!==-1){ /* decrease value */ + return Math.abs(contentPos-parseInt(val.split("-=")[1])); + }else if(val.indexOf("+=")!==-1){ /* inrease value */ + var p=(contentPos+parseInt(val.split("+=")[1])); + return p>=0 ? 0 : Math.abs(p); + }else if(val.indexOf("px")!==-1 && _isNumeric(val.split("px")[0])){ /* pixels string value (e.g. "100px") */ + return Math.abs(val.split("px")[0]); + }else{ + if(val==="top" || val==="left"){ /* special strings */ + return 0; + }else if(val==="bottom"){ + return Math.abs(wrapper.height()-mCSB_container.outerHeight(false)); + }else if(val==="right"){ + return Math.abs(wrapper.width()-mCSB_container.outerWidth(false)); + }else if(val==="first" || val==="last"){ + var obj=mCSB_container.find(":"+val); + return dir==="x" ? _childPos(obj)[1] : _childPos(obj)[0]; + }else{ + if($(val).length){ /* jquery selector */ + return dir==="x" ? _childPos($(val))[1] : _childPos($(val))[0]; + }else{ /* other values (e.g. "100em") */ + mCSB_container.css(cssProp,val); + methods.update.call(null,$this[0]); + return; + } + } + } + break; + } + }, + /* -------------------- */ + + + /* calls the update method automatically */ + _autoUpdate=function(rem){ + var $this=$(this),d=$this.data(pluginPfx),o=d.opt, + mCSB_container=$("#mCSB_"+d.idx+"_container"); + if(rem){ + /* + removes autoUpdate timer + usage: _autoUpdate.call(this,"remove"); + */ + clearTimeout(mCSB_container[0].autoUpdate); + _delete(mCSB_container[0],"autoUpdate"); + return; + } + upd(); + function upd(){ + clearTimeout(mCSB_container[0].autoUpdate); + if($this.parents("html").length===0){ + /* check element in dom tree */ + $this=null; + return; + } + mCSB_container[0].autoUpdate=setTimeout(function(){ + /* update on specific selector(s) length and size change */ + if(o.advanced.updateOnSelectorChange){ + d.poll.change.n=sizesSum(); + if(d.poll.change.n!==d.poll.change.o){ + d.poll.change.o=d.poll.change.n; + doUpd(3); + return; + } + } + /* update on main element and scrollbar size changes */ + if(o.advanced.updateOnContentResize){ + d.poll.size.n=$this[0].scrollHeight+$this[0].scrollWidth+mCSB_container[0].offsetHeight+$this[0].offsetHeight+$this[0].offsetWidth; + if(d.poll.size.n!==d.poll.size.o){ + d.poll.size.o=d.poll.size.n; + doUpd(1); + return; + } + } + /* update on image load */ + if(o.advanced.updateOnImageLoad){ + if(!(o.advanced.updateOnImageLoad==="auto" && o.axis==="y")){ //by default, it doesn't run on vertical content + d.poll.img.n=mCSB_container.find("img").length; + if(d.poll.img.n!==d.poll.img.o){ + d.poll.img.o=d.poll.img.n; + mCSB_container.find("img").each(function(){ + imgLoader(this); + }); + return; + } + } + } + if(o.advanced.updateOnSelectorChange || o.advanced.updateOnContentResize || o.advanced.updateOnImageLoad){upd();} + },o.advanced.autoUpdateTimeout); + } + /* a tiny image loader */ + function imgLoader(el){ + if($(el).hasClass(classes[2])){doUpd(); return;} + var img=new Image(); + function createDelegate(contextObject,delegateMethod){ + return function(){return delegateMethod.apply(contextObject,arguments);} + } + function imgOnLoad(){ + this.onload=null; + $(el).addClass(classes[2]); + doUpd(2); + } + img.onload=createDelegate(img,imgOnLoad); + img.src=el.src; + } + /* returns the total height and width sum of all elements matching the selector */ + function sizesSum(){ + if(o.advanced.updateOnSelectorChange===true){o.advanced.updateOnSelectorChange="*";} + var total=0,sel=mCSB_container.find(o.advanced.updateOnSelectorChange); + if(o.advanced.updateOnSelectorChange && sel.length>0){sel.each(function(){total+=this.offsetHeight+this.offsetWidth;});} + return total; + } + /* calls the update method */ + function doUpd(cb){ + clearTimeout(mCSB_container[0].autoUpdate); + methods.update.call(null,$this[0],cb); + } + }, + /* -------------------- */ + + + /* snaps scrolling to a multiple of a pixels number */ + _snapAmount=function(to,amount,offset){ + return (Math.round(to/amount)*amount-offset); + }, + /* -------------------- */ + + + /* stops content and scrollbar animations */ + _stop=function(el){ + var d=el.data(pluginPfx), + sel=$("#mCSB_"+d.idx+"_container,#mCSB_"+d.idx+"_container_wrapper,#mCSB_"+d.idx+"_dragger_vertical,#mCSB_"+d.idx+"_dragger_horizontal"); + sel.each(function(){ + _stopTween.call(this); + }); + }, + /* -------------------- */ + + + /* + ANIMATES CONTENT + This is where the actual scrolling happens + */ + _scrollTo=function(el,to,options){ + var d=el.data(pluginPfx),o=d.opt, + defaults={ + trigger:"internal", + dir:"y", + scrollEasing:"mcsEaseOut", + drag:false, + dur:o.scrollInertia, + overwrite:"all", + callbacks:true, + onStart:true, + onUpdate:true, + onComplete:true + }, + options=$.extend(defaults,options), + dur=[options.dur,(options.drag ? 0 : options.dur)], + mCustomScrollBox=$("#mCSB_"+d.idx), + mCSB_container=$("#mCSB_"+d.idx+"_container"), + wrapper=mCSB_container.parent(), + totalScrollOffsets=o.callbacks.onTotalScrollOffset ? _arr.call(el,o.callbacks.onTotalScrollOffset) : [0,0], + totalScrollBackOffsets=o.callbacks.onTotalScrollBackOffset ? _arr.call(el,o.callbacks.onTotalScrollBackOffset) : [0,0]; + d.trigger=options.trigger; + if(wrapper.scrollTop()!==0 || wrapper.scrollLeft()!==0){ /* always reset scrollTop/Left */ + $(".mCSB_"+d.idx+"_scrollbar").css("visibility","visible"); + wrapper.scrollTop(0).scrollLeft(0); + } + if(to==="_resetY" && !d.contentReset.y){ + /* callbacks: onOverflowYNone */ + if(_cb("onOverflowYNone")){o.callbacks.onOverflowYNone.call(el[0]);} + d.contentReset.y=1; + } + if(to==="_resetX" && !d.contentReset.x){ + /* callbacks: onOverflowXNone */ + if(_cb("onOverflowXNone")){o.callbacks.onOverflowXNone.call(el[0]);} + d.contentReset.x=1; + } + if(to==="_resetY" || to==="_resetX"){return;} + if((d.contentReset.y || !el[0].mcs) && d.overflowed[0]){ + /* callbacks: onOverflowY */ + if(_cb("onOverflowY")){o.callbacks.onOverflowY.call(el[0]);} + d.contentReset.x=null; + } + if((d.contentReset.x || !el[0].mcs) && d.overflowed[1]){ + /* callbacks: onOverflowX */ + if(_cb("onOverflowX")){o.callbacks.onOverflowX.call(el[0]);} + d.contentReset.x=null; + } + if(o.snapAmount){ /* scrolling snapping */ + var snapAmount=!(o.snapAmount instanceof Array) ? o.snapAmount : options.dir==="x" ? o.snapAmount[1] : o.snapAmount[0]; + to=_snapAmount(to,snapAmount,o.snapOffset); + } + switch(options.dir){ + case "x": + var mCSB_dragger=$("#mCSB_"+d.idx+"_dragger_horizontal"), + property="left", + contentPos=mCSB_container[0].offsetLeft, + limit=[ + mCustomScrollBox.width()-mCSB_container.outerWidth(false), + mCSB_dragger.parent().width()-mCSB_dragger.width() + ], + scrollTo=[to,to===0 ? 0 : (to/d.scrollRatio.x)], + tso=totalScrollOffsets[1], + tsbo=totalScrollBackOffsets[1], + totalScrollOffset=tso>0 ? tso/d.scrollRatio.x : 0, + totalScrollBackOffset=tsbo>0 ? tsbo/d.scrollRatio.x : 0; + break; + case "y": + var mCSB_dragger=$("#mCSB_"+d.idx+"_dragger_vertical"), + property="top", + contentPos=mCSB_container[0].offsetTop, + limit=[ + mCustomScrollBox.height()-mCSB_container.outerHeight(false), + mCSB_dragger.parent().height()-mCSB_dragger.height() + ], + scrollTo=[to,to===0 ? 0 : (to/d.scrollRatio.y)], + tso=totalScrollOffsets[0], + tsbo=totalScrollBackOffsets[0], + totalScrollOffset=tso>0 ? tso/d.scrollRatio.y : 0, + totalScrollBackOffset=tsbo>0 ? tsbo/d.scrollRatio.y : 0; + break; + } + if(scrollTo[1]<0 || (scrollTo[0]===0 && scrollTo[1]===0)){ + scrollTo=[0,0]; + }else if(scrollTo[1]>=limit[1]){ + scrollTo=[limit[0],limit[1]]; + }else{ + scrollTo[0]=-scrollTo[0]; + } + if(!el[0].mcs){ + _mcs(); /* init mcs object (once) to make it available before callbacks */ + if(_cb("onInit")){o.callbacks.onInit.call(el[0]);} /* callbacks: onInit */ + } + clearTimeout(mCSB_container[0].onCompleteTimeout); + _tweenTo(mCSB_dragger[0],property,Math.round(scrollTo[1]),dur[1],options.scrollEasing); + if(!d.tweenRunning && ((contentPos===0 && scrollTo[0]>=0) || (contentPos===limit[0] && scrollTo[0]<=limit[0]))){return;} + _tweenTo(mCSB_container[0],property,Math.round(scrollTo[0]),dur[0],options.scrollEasing,options.overwrite,{ + onStart:function(){ + if(options.callbacks && options.onStart && !d.tweenRunning){ + /* callbacks: onScrollStart */ + if(_cb("onScrollStart")){_mcs(); o.callbacks.onScrollStart.call(el[0]);} + d.tweenRunning=true; + _onDragClasses(mCSB_dragger); + d.cbOffsets=_cbOffsets(); + } + },onUpdate:function(){ + if(options.callbacks && options.onUpdate){ + /* callbacks: whileScrolling */ + if(_cb("whileScrolling")){_mcs(); o.callbacks.whileScrolling.call(el[0]);} + } + },onComplete:function(){ + if(options.callbacks && options.onComplete){ + if(o.axis==="yx"){clearTimeout(mCSB_container[0].onCompleteTimeout);} + var t=mCSB_container[0].idleTimer || 0; + mCSB_container[0].onCompleteTimeout=setTimeout(function(){ + /* callbacks: onScroll, onTotalScroll, onTotalScrollBack */ + if(_cb("onScroll")){_mcs(); o.callbacks.onScroll.call(el[0]);} + if(_cb("onTotalScroll") && scrollTo[1]>=limit[1]-totalScrollOffset && d.cbOffsets[0]){_mcs(); o.callbacks.onTotalScroll.call(el[0]);} + if(_cb("onTotalScrollBack") && scrollTo[1]<=totalScrollBackOffset && d.cbOffsets[1]){_mcs(); o.callbacks.onTotalScrollBack.call(el[0]);} + d.tweenRunning=false; + mCSB_container[0].idleTimer=0; + _onDragClasses(mCSB_dragger,"hide"); + },t); + } + } + }); + /* checks if callback function exists */ + function _cb(cb){ + return d && o.callbacks[cb] && typeof o.callbacks[cb]==="function"; + } + /* checks whether callback offsets always trigger */ + function _cbOffsets(){ + return [o.callbacks.alwaysTriggerOffsets || contentPos>=limit[0]+tso,o.callbacks.alwaysTriggerOffsets || contentPos<=-tsbo]; + } + /* + populates object with useful values for the user + values: + content: this.mcs.content + content top position: this.mcs.top + content left position: this.mcs.left + dragger top position: this.mcs.draggerTop + dragger left position: this.mcs.draggerLeft + scrolling y percentage: this.mcs.topPct + scrolling x percentage: this.mcs.leftPct + scrolling direction: this.mcs.direction + */ + function _mcs(){ + var cp=[mCSB_container[0].offsetTop,mCSB_container[0].offsetLeft], /* content position */ + dp=[mCSB_dragger[0].offsetTop,mCSB_dragger[0].offsetLeft], /* dragger position */ + cl=[mCSB_container.outerHeight(false),mCSB_container.outerWidth(false)], /* content length */ + pl=[mCustomScrollBox.height(),mCustomScrollBox.width()]; /* content parent length */ + el[0].mcs={ + content:mCSB_container, /* original content wrapper as jquery object */ + top:cp[0],left:cp[1],draggerTop:dp[0],draggerLeft:dp[1], + topPct:Math.round((100*Math.abs(cp[0]))/(Math.abs(cl[0])-pl[0])),leftPct:Math.round((100*Math.abs(cp[1]))/(Math.abs(cl[1])-pl[1])), + direction:options.dir + }; + /* + this refers to the original element containing the scrollbar(s) + usage: this.mcs.top, this.mcs.leftPct etc. + */ + } + }, + /* -------------------- */ + + + /* + CUSTOM JAVASCRIPT ANIMATION TWEEN + Lighter and faster than jquery animate() and css transitions + Animates top/left properties and includes easings + */ + _tweenTo=function(el,prop,to,duration,easing,overwrite,callbacks){ + if(!el._mTween){el._mTween={top:{},left:{}};} + var callbacks=callbacks || {}, + onStart=callbacks.onStart || function(){},onUpdate=callbacks.onUpdate || function(){},onComplete=callbacks.onComplete || function(){}, + startTime=_getTime(),_delay,progress=0,from=el.offsetTop,elStyle=el.style,_request,tobj=el._mTween[prop]; + if(prop==="left"){from=el.offsetLeft;} + var diff=to-from; + tobj.stop=0; + if(overwrite!=="none"){_cancelTween();} + _startTween(); + function _step(){ + if(tobj.stop){return;} + if(!progress){onStart.call();} + progress=_getTime()-startTime; + _tween(); + if(progress>=tobj.time){ + tobj.time=(progress>tobj.time) ? progress+_delay-(progress-tobj.time) : progress+_delay-1; + if(tobj.time<progress+1){tobj.time=progress+1;} + } + if(tobj.time<duration){tobj.id=_request(_step);}else{onComplete.call();} + } + function _tween(){ + if(duration>0){ + tobj.currVal=_ease(tobj.time,from,diff,duration,easing); + elStyle[prop]=Math.round(tobj.currVal)+"px"; + }else{ + elStyle[prop]=to+"px"; + } + onUpdate.call(); + } + function _startTween(){ + _delay=1000/60; + tobj.time=progress+_delay; + _request=(!window.requestAnimationFrame) ? function(f){_tween(); return setTimeout(f,0.01);} : window.requestAnimationFrame; + tobj.id=_request(_step); + } + function _cancelTween(){ + if(tobj.id==null){return;} + if(!window.requestAnimationFrame){clearTimeout(tobj.id); + }else{window.cancelAnimationFrame(tobj.id);} + tobj.id=null; + } + function _ease(t,b,c,d,type){ + switch(type){ + case "linear": case "mcsLinear": + return c*t/d + b; + break; + case "mcsLinearOut": + t/=d; t--; return c * Math.sqrt(1 - t*t) + b; + break; + case "easeInOutSmooth": + t/=d/2; + if(t<1) return c/2*t*t + b; + t--; + return -c/2 * (t*(t-2) - 1) + b; + break; + case "easeInOutStrong": + t/=d/2; + if(t<1) return c/2 * Math.pow( 2, 10 * (t - 1) ) + b; + t--; + return c/2 * ( -Math.pow( 2, -10 * t) + 2 ) + b; + break; + case "easeInOut": case "mcsEaseInOut": + t/=d/2; + if(t<1) return c/2*t*t*t + b; + t-=2; + return c/2*(t*t*t + 2) + b; + break; + case "easeOutSmooth": + t/=d; t--; + return -c * (t*t*t*t - 1) + b; + break; + case "easeOutStrong": + return c * ( -Math.pow( 2, -10 * t/d ) + 1 ) + b; + break; + case "easeOut": case "mcsEaseOut": default: + var ts=(t/=d)*t,tc=ts*t; + return b+c*(0.499999999999997*tc*ts + -2.5*ts*ts + 5.5*tc + -6.5*ts + 4*t); + } + } + }, + /* -------------------- */ + + + /* returns current time */ + _getTime=function(){ + if(window.performance && window.performance.now){ + return window.performance.now(); + }else{ + if(window.performance && window.performance.webkitNow){ + return window.performance.webkitNow(); + }else{ + if(Date.now){return Date.now();}else{return new Date().getTime();} + } + } + }, + /* -------------------- */ + + + /* stops a tween */ + _stopTween=function(){ + var el=this; + if(!el._mTween){el._mTween={top:{},left:{}};} + var props=["top","left"]; + for(var i=0; i<props.length; i++){ + var prop=props[i]; + if(el._mTween[prop].id){ + if(!window.requestAnimationFrame){clearTimeout(el._mTween[prop].id); + }else{window.cancelAnimationFrame(el._mTween[prop].id);} + el._mTween[prop].id=null; + el._mTween[prop].stop=1; + } + } + }, + /* -------------------- */ + + + /* deletes a property (avoiding the exception thrown by IE) */ + _delete=function(c,m){ + try{delete c[m];}catch(e){c[m]=null;} + }, + /* -------------------- */ + + + /* detects left mouse button */ + _mouseBtnLeft=function(e){ + return !(e.which && e.which!==1); + }, + /* -------------------- */ + + + /* detects if pointer type event is touch */ + _pointerTouch=function(e){ + var t=e.originalEvent.pointerType; + return !(t && t!=="touch" && t!==2); + }, + /* -------------------- */ + + + /* checks if value is numeric */ + _isNumeric=function(val){ + return !isNaN(parseFloat(val)) && isFinite(val); + }, + /* -------------------- */ + + + /* returns element position according to content */ + _childPos=function(el){ + var p=el.parents(".mCSB_container"); + return [el.offset().top-p.offset().top,el.offset().left-p.offset().left]; + }, + /* -------------------- */ + + + /* checks if browser tab is hidden/inactive via Page Visibility API */ + _isTabHidden=function(){ + var prop=_getHiddenProp(); + if(!prop) return false; + return document[prop]; + function _getHiddenProp(){ + var pfx=["webkit","moz","ms","o"]; + if("hidden" in document) return "hidden"; //natively supported + for(var i=0; i<pfx.length; i++){ //prefixed + if((pfx[i]+"Hidden") in document) + return pfx[i]+"Hidden"; + } + return null; //not supported + } + }; + /* -------------------- */ + + + + + + /* + ---------------------------------------- + PLUGIN SETUP + ---------------------------------------- + */ + + /* plugin constructor functions */ + $.fn[pluginNS]=function(method){ /* usage: $(selector).mCustomScrollbar(); */ + if(methods[method]){ + return methods[method].apply(this,Array.prototype.slice.call(arguments,1)); + }else if(typeof method==="object" || !method){ + return methods.init.apply(this,arguments); + }else{ + $.error("Method "+method+" does not exist"); + } + }; + $[pluginNS]=function(method){ /* usage: $.mCustomScrollbar(); */ + if(methods[method]){ + return methods[method].apply(this,Array.prototype.slice.call(arguments,1)); + }else if(typeof method==="object" || !method){ + return methods.init.apply(this,arguments); + }else{ + $.error("Method "+method+" does not exist"); + } + }; + + /* + allow setting plugin default options. + usage: $.mCustomScrollbar.defaults.scrollInertia=500; + to apply any changed default options on default selectors (below), use inside document ready fn + e.g.: $(document).ready(function(){ $.mCustomScrollbar.defaults.scrollInertia=500; }); + */ + $[pluginNS].defaults=defaults; + + /* + add window object (window.mCustomScrollbar) + usage: if(window.mCustomScrollbar){console.log("custom scrollbar plugin loaded");} + */ + window[pluginNS]=true; + + $(window).load(function(){ + + $(defaultSelector)[pluginNS](); /* add scrollbars automatically on default selector */ + + /* extend jQuery expressions */ + $.extend($.expr[":"],{ + /* checks if element is within scrollable viewport */ + mcsInView:$.expr[":"].mcsInView || function(el){ + var $el=$(el),content=$el.parents(".mCSB_container"),wrapper,cPos; + if(!content.length){return;} + wrapper=content.parent(); + cPos=[content[0].offsetTop,content[0].offsetLeft]; + return cPos[0]+_childPos($el)[0]>=0 && cPos[0]+_childPos($el)[0]<wrapper.height()-$el.outerHeight(false) && + cPos[1]+_childPos($el)[1]>=0 && cPos[1]+_childPos($el)[1]<wrapper.width()-$el.outerWidth(false); + }, + /* checks if element is overflowed having visible scrollbar(s) */ + mcsOverflow:$.expr[":"].mcsOverflow || function(el){ + var d=$(el).data(pluginPfx); + if(!d){return;} + return d.overflowed[0] || d.overflowed[1]; + } + }); + + }); + +}))})); diff --git a/packages/wekan-scrollbar/jquery.mousewheel.js b/packages/wekan-scrollbar/jquery.mousewheel.js new file mode 100644 index 00000000..3eadb7ed --- /dev/null +++ b/packages/wekan-scrollbar/jquery.mousewheel.js @@ -0,0 +1,221 @@ +/*! + * jQuery Mousewheel 3.1.13 + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + */ + +(function (factory) { + if ( typeof define === 'function' && define.amd ) { + // AMD. Register as an anonymous module. + define(['jquery'], factory); + } else if (typeof exports === 'object') { + // Node/CommonJS style for Browserify + module.exports = factory; + } else { + // Browser globals + factory(jQuery); + } +}(function ($) { + + var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], + toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? + ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], + slice = Array.prototype.slice, + nullLowestDeltaTimeout, lowestDelta; + + if ( $.event.fixHooks ) { + for ( var i = toFix.length; i; ) { + $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; + } + } + + var special = $.event.special.mousewheel = { + version: '3.1.12', + + setup: function() { + if ( this.addEventListener ) { + for ( var i = toBind.length; i; ) { + this.addEventListener( toBind[--i], handler, false ); + } + } else { + this.onmousewheel = handler; + } + // Store the line height and page height for this particular element + $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); + $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); + }, + + teardown: function() { + if ( this.removeEventListener ) { + for ( var i = toBind.length; i; ) { + this.removeEventListener( toBind[--i], handler, false ); + } + } else { + this.onmousewheel = null; + } + // Clean up the data we added to the element + $.removeData(this, 'mousewheel-line-height'); + $.removeData(this, 'mousewheel-page-height'); + }, + + getLineHeight: function(elem) { + var $elem = $(elem), + $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); + if (!$parent.length) { + $parent = $('body'); + } + return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16; + }, + + getPageHeight: function(elem) { + return $(elem).height(); + }, + + settings: { + adjustOldDeltas: true, // see shouldAdjustOldDeltas() below + normalizeOffset: true // calls getBoundingClientRect for each event + } + }; + + $.fn.extend({ + mousewheel: function(fn) { + return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); + }, + + unmousewheel: function(fn) { + return this.unbind('mousewheel', fn); + } + }); + + + function handler(event) { + var orgEvent = event || window.event, + args = slice.call(arguments, 1), + delta = 0, + deltaX = 0, + deltaY = 0, + absDelta = 0, + offsetX = 0, + offsetY = 0; + event = $.event.fix(orgEvent); + event.type = 'mousewheel'; + + // Old school scrollwheel delta + if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } + if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } + if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } + if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } + + // Firefox < 17 horizontal scrolling related to DOMMouseScroll event + if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { + deltaX = deltaY * -1; + deltaY = 0; + } + + // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy + delta = deltaY === 0 ? deltaX : deltaY; + + // New school wheel delta (wheel event) + if ( 'deltaY' in orgEvent ) { + deltaY = orgEvent.deltaY * -1; + delta = deltaY; + } + if ( 'deltaX' in orgEvent ) { + deltaX = orgEvent.deltaX; + if ( deltaY === 0 ) { delta = deltaX * -1; } + } + + // No change actually happened, no reason to go any further + if ( deltaY === 0 && deltaX === 0 ) { return; } + + // Need to convert lines and pages to pixels if we aren't already in pixels + // There are three delta modes: + // * deltaMode 0 is by pixels, nothing to do + // * deltaMode 1 is by lines + // * deltaMode 2 is by pages + if ( orgEvent.deltaMode === 1 ) { + var lineHeight = $.data(this, 'mousewheel-line-height'); + delta *= lineHeight; + deltaY *= lineHeight; + deltaX *= lineHeight; + } else if ( orgEvent.deltaMode === 2 ) { + var pageHeight = $.data(this, 'mousewheel-page-height'); + delta *= pageHeight; + deltaY *= pageHeight; + deltaX *= pageHeight; + } + + // Store lowest absolute delta to normalize the delta values + absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); + + if ( !lowestDelta || absDelta < lowestDelta ) { + lowestDelta = absDelta; + + // Adjust older deltas if necessary + if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { + lowestDelta /= 40; + } + } + + // Adjust older deltas if necessary + if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { + // Divide all the things by 40! + delta /= 40; + deltaX /= 40; + deltaY /= 40; + } + + // Get a whole, normalized value for the deltas + delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); + deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); + deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); + + // Normalise offsetX and offsetY properties + if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { + var boundingRect = this.getBoundingClientRect(); + offsetX = event.clientX - boundingRect.left; + offsetY = event.clientY - boundingRect.top; + } + + // Add information to the event object + event.deltaX = deltaX; + event.deltaY = deltaY; + event.deltaFactor = lowestDelta; + event.offsetX = offsetX; + event.offsetY = offsetY; + // Go ahead and set deltaMode to 0 since we converted to pixels + // Although this is a little odd since we overwrite the deltaX/Y + // properties with normalized deltas. + event.deltaMode = 0; + + // Add event and delta to the front of the arguments + args.unshift(event, delta, deltaX, deltaY); + + // Clearout lowestDelta after sometime to better + // handle multiple device types that give different + // a different lowestDelta + // Ex: trackpad = 3 and mouse wheel = 120 + if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } + nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); + + return ($.event.dispatch || $.event.handle).apply(this, args); + } + + function nullLowestDelta() { + lowestDelta = null; + } + + function shouldAdjustOldDeltas(orgEvent, absDelta) { + // If this is an older event and the delta is divisable by 120, + // then we are assuming that the browser is treating this as an + // older mouse wheel event and that we should divide the deltas + // by 40 to try and get a more usable deltaFactor. + // Side note, this actually impacts the reported scroll distance + // in older browsers and can cause scrolling to be slower than native. + // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. + return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; + } + +})); diff --git a/packages/wekan-scrollbar/package.js b/packages/wekan-scrollbar/package.js new file mode 100644 index 00000000..0dfdce94 --- /dev/null +++ b/packages/wekan-scrollbar/package.js @@ -0,0 +1,21 @@ +Package.describe({ + summary: "A wrapper for Malihu Custom Scrollbar. Highly customizable custom scrollbar jQuery plugin", + version: "3.1.3", + git: "https://github.com/MaazAli/Meteor-Malihu-Custom-Scrollbar.git" +}); + +Package.onUse(function(api) { + api.versionsFrom('METEOR@0.9.0.1'); + + api.use('jquery'); + + // JS + api.addFiles('jquery.mousewheel.js', 'client'); + api.addFiles('jquery.mCustomScrollbar.js', 'client'); + + // CSS + + api.addFiles('jquery.mCustomScrollbar.css', 'client'); + +}); + diff --git a/packages/wekan-scrollbar/readme.md b/packages/wekan-scrollbar/readme.md new file mode 100644 index 00000000..0e2fbb5c --- /dev/null +++ b/packages/wekan-scrollbar/readme.md @@ -0,0 +1,17 @@ +## Meteor Wrapper for Malihu jQuery Custom Scrollbar plugin + +Add to your Meteor app + +``` +meteor add wekan:wekan-scrollbar +``` + +### OLD + +Add to your Meteor app + +``` +meteor add maazalik:malihu-jquery-custom-scrollbar +``` + +Compatible with Meteor v0.9.0.1 -- cgit v1.2.3-1-g7c22