hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
fcee81b17210ced16143e19f8d33c5abf8807590
972
js
JavaScript
lib/tasks/links.js
my5t3ry/inliner
00bb293f4d88da5abee9c953a9fefdefb87af6c4
[ "MIT" ]
791
2015-01-02T16:02:19.000Z
2022-03-28T12:50:16.000Z
lib/tasks/links.js
my5t3ry/inliner
00bb293f4d88da5abee9c953a9fefdefb87af6c4
[ "MIT" ]
165
2015-01-25T09:03:05.000Z
2022-03-30T19:55:25.000Z
lib/tasks/links.js
my5t3ry/inliner
00bb293f4d88da5abee9c953a9fefdefb87af6c4
[ "MIT" ]
156
2015-01-13T12:15:05.000Z
2022-03-30T19:48:27.000Z
module.exports = resolve; var debug = require('debug')('inliner'); var basename = require('path').basename; function resolve(inliner, todo, $) { debug('start %s links', todo.length); return todo.map(function links(link) { var url = $(link).attr('href'); if (inliner.options.skipAbsoluteUrls && (url.indexOf('//') === 0 || url.indexOf('http') === 0)) { debug('skipping remote links'); inliner.emit('progress', 'skipping remote links'); return false; } if (url.indexOf('http') !== 0) { url = inliner.resolve(inliner.url, url); } inliner.emit('progress', 'processing external css ' + basename(url)); return inliner.get(url).then(function then(res) { var css = res.body; inliner.jobs.done.links(); return inliner.cssImports(url, css) .then(inliner.cssImages.bind(inliner, url)); }).then(function then(css) { $(link).replaceWith('<style>' + css + '</style>'); }); }); }
33.517241
73
0.603909
fcee8969a3ee3abd814930dadf9ba4037a744350
28,524
js
JavaScript
src/encoded/static/components/testdata/workflow_run/awsem-partc.js
4dn-dcic/fourfron
29601961706d2371b982e57ae085e8ebec3b2714
[ "MIT" ]
11
2016-11-23T02:33:13.000Z
2021-06-18T14:21:20.000Z
src/encoded/static/components/testdata/workflow_run/awsem-partc.js
4dn-dcic/fourfron
29601961706d2371b982e57ae085e8ebec3b2714
[ "MIT" ]
1,159
2016-11-21T15:40:24.000Z
2022-03-29T03:18:38.000Z
src/encoded/static/components/testdata/workflow_run/awsem-partc.js
4dn-dcic/fourfron
29601961706d2371b982e57ae085e8ebec3b2714
[ "MIT" ]
5
2017-01-27T16:36:15.000Z
2019-06-14T14:39:54.000Z
const WorkflowRunDataBlob = { "lab":{ "uuid":"828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "link_id":"~labs~4dn-dcic-lab~", "@id":"/labs/4dn-dcic-lab/", "display_title":"4DN DCIC Lab, HMS", "principals_allowed":{ "view":[ "system.Everyone" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } }, "award":{ "@id":"/awards/1U01CA200059-01/", "link_id":"~awards~1U01CA200059-01~", "uuid":"b0b9c607-f8b4-4f02-93f4-9895b461334b", "display_title":"4D NUCLEOME NETWORK DATA COORDINATION AND INTEGRATION CENTER", "principals_allowed":{ "view":[ "system.Everyone" ], "edit":[ "group.admin" ], "audit":[ "system.Everyone" ] } }, "title":"hi-c-processing-partc/8 run 2017-08-14 17:27:52.701358", "status":"released to project", "aliases":[ ], "run_url":"https://console.aws.amazon.com/states/home?region=us-east-1#/executions/details/arn:aws:states:us-east-1:643366669028:execution:run_sbg_workflow_5:hic-partc_partC_rao26b22ed2d-7eee-4377-b85e-f43bb41747f1", "workflow":{ "uuid":"c6480905-49e5-4c33-afab-9ec90d65faf3", "@id":"/workflows/c6480905-49e5-4c33-afab-9ec90d65faf3/", "display_title":"hi-c-processing-partc/6 - 4DNWF06BPEF2", "workflow_type":"Hi-C data analysis", "title":"hi-c-processing-partc/6", "link_id":"~workflows~c6480905-49e5-4c33-afab-9ec90d65faf3~", "steps":[ { "name":"cool2mcool", "meta":{ "software_used":[ { "link_id":"~softwares~02d636b9-d8dd-4da9-950c-2ca994b23555~", "uuid":"02d636b9-d8dd-4da9-950c-2ca994b23555", "display_title":"cooler_0.7.4", "version":"0.7.4", "name":"cooler", "title":"cooler_0.7.4", "@id":"/softwares/02d636b9-d8dd-4da9-950c-2ca994b23555/", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } } ] } }, { "name":"extract_mcool_normvector_for_juicebox", "meta":{ "software_used":[ { "link_id":"~softwares~c91a2c9d-079c-4647-9951-da95f2c9baf1~", "uuid":"c91a2c9d-079c-4647-9951-da95f2c9baf1", "display_title":"mcool2hic_34b5430e8b9cfd8f01203e0821b68efe4897b18f", "name":"mcool2hic", "title":"mcool2hic_34b5430e8b9cfd8f01203e0821b68efe4897b18f", "@id":"/softwares/c91a2c9d-079c-4647-9951-da95f2c9baf1/", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } } ] } }, { "name":"add_hic_normvector_to_mcool", "meta":{ "software_used":[ { "link_id":"~softwares~02d636b9-d8dd-4da9-950c-2ca994b23555~", "uuid":"02d636b9-d8dd-4da9-950c-2ca994b23555", "display_title":"cooler_0.7.4", "version":"0.7.4", "name":"cooler", "title":"cooler_0.7.4", "@id":"/softwares/02d636b9-d8dd-4da9-950c-2ca994b23555/", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } } ] } } ], "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } }, "parameters":[ { "value":"8", "ordinal":1, "workflow_argument_name":"ncores" } ], "run_status":"complete", "input_files":[ { "value":{ "accession":"4DNFIO67APU1", "@id":"/files-fastq/4DNFIO67APU1/", "uuid":"46e82a90-49e5-4c33-afab-9ec90d65faa0", "link_id":"~files-fastq~4DNFIO67APU1~", "@type":[ "FileFastq", "File", "Item" ], "file_format":"fastq", "filename":"test_file1.fastq.gz", "display_title":"4DNFIO67APU1.fastq.gz", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } }, "ordinal":1, "workflow_argument_name":"input_hic" }, { "value":{ "accession":"4DNFIO67APT1", "@id":"/files-fastq/4DNFIO67APT1/", "uuid":"46e82a90-49e5-4c33-afab-9ec90d65faa1", "link_id":"~files-fastq~4DNFIO67APT1~", "@type":[ "FileFastq", "File", "Item" ], "file_format":"fastq", "filename":"test_file2.fastq.gz", "display_title":"4DNFIO67APT1.fastq.gz", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } }, "ordinal":1, "workflow_argument_name":"input_cool" } ], "sbg_task_id":"a99e804c-2cc9-4bef-ba4a-9ec2a39a80f6", "date_created":"2018-01-24T14:29:52.928403+00:00", "output_files":[ { "type":"Output processed file", "value":{ "link_id":"~files-processed~4DNFIMCOOL02~", "@id":"/files-processed/4DNFIMCOOL02/", "display_title":"4DNFIMCOOL02.mcool", "@type":[ "FileProcessed", "File", "Item" ], "file_format":"mcool", "accession":"4DNFIMCOOL02", "uuid":"d273d710-6b6d-4e43-a84c-5658a891c033", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } }, "format":"mcool", "status":"COMPLETED", "export_id":"B9H2LpQuS5O4P61FlSUYQSfdurJbjRhM", "extension":".mcool", "upload_key":"d273d710-6b6d-4e43-a84c-5658a891c033/4DNFIMCOOL02.mcool", "workflow_argument_name":"output_mcool" }, { "type":"Output processed file", "value":{ "link_id":"~files-processed~4DNFIAAAAAA2~", "@id":"/files-processed/4DNFIAAAAAA2/", "display_title":"4DNFIAAAAAA2.pairs.gz", "@type":[ "FileProcessed", "File", "Item" ], "file_format":"pairs", "accession":"4DNFIAAAAAA2", "uuid":"7f9eb396-5c1a-1111-aebf-28ea39d6a50f", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } }, "format":"normvector_juicerformat", "status":"COMPLETED", "export_id":"0NW3nlHzmPxL9fbL0Oh1BI9BERpu8HsQ", "extension":".normvector.juicerformat.gz", "upload_key":"7f9eb396-5c1a-1111-aebf-28ea39d6a50f/4DNFIAAAAAA2.normvector.juicerformat.gz", "workflow_argument_name":"output_normvector" } ], "run_platform":"SBG", "sbg_app_name":"hi-c-processing-partc/8", "sbg_import_ids":[ "4DNFIU59TRDY.hic", "4DNFIHKCL9SF.cool" ], "schema_version":"1", "project_release":"2018-01-24", "@id":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/", "@type":[ "WorkflowRunSbg", "WorkflowRun", "Item" ], "uuid":"0fe19e8e-c565-4c0c-8058-effe5d81f53b", "external_references":[ ], "display_title":"hi-c-processing-partc/8 run 2017-08-14 17:27:52.701358", "link_id":"~workflow-runs-sbg~0fe19e8e-c565-4c0c-8058-effe5d81f53b~", "principals_allowed":{ "view":[ "group.admin", "group.read-only-admin", "remoteuser.EMBED", "remoteuser.INDEXER", "viewing_group.4DN" ], "edit":[ "group.admin" ], "audit":[ "system.Everyone" ] }, "@context":"/terms/", "actions":[ { "name":"create", "title":"Create", "profile":"/profiles/WorkflowRunSbg.json", "href":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/#!create" }, { "name":"edit", "title":"Edit", "profile":"/profiles/WorkflowRunSbg.json", "href":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/#!edit" } ], "audit":{ "INTERNAL_ACTION":[ { "category":"mismatched status", "detail":"released to project /workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/ has uploaded subobject /files-fastq/4DNFIO67APT1/", "level":30, "level_name":"INTERNAL_ACTION", "path":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/", "name":"audit_item_status" }, { "category":"mismatched status", "detail":"released to project /workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/ has uploaded subobject /files-processed/4DNFIAAAAAA2/", "level":30, "level_name":"INTERNAL_ACTION", "path":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/", "name":"audit_item_status" }, { "category":"mismatched status", "detail":"released to project /workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/ has uploaded subobject /files-processed/4DNFIMCOOL02/", "level":30, "level_name":"INTERNAL_ACTION", "path":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/", "name":"audit_item_status" }, { "category":"mismatched status", "detail":"released to project /workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/ has in review by lab subobject /workflows/c6480905-49e5-4c33-afab-9ec90d65faf3/", "level":30, "level_name":"INTERNAL_ACTION", "path":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/", "name":"audit_item_status" }, { "category":"mismatched status", "detail":"released to project /workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/ has uploaded subobject /files-fastq/4DNFIO67APU1/", "level":30, "level_name":"INTERNAL_ACTION", "path":"/workflow-runs-sbg/0fe19e8e-c565-4c0c-8058-effe5d81f53b/", "name":"audit_item_status" } ] }, "steps":[ { "meta":{ "software_used":[ { "title":"cooler_0.7.4", "display_title":"cooler_0.7.4", "version":"0.7.4", "link_id":"~softwares~02d636b9-d8dd-4da9-950c-2ca994b23555~", "@id":"/softwares/02d636b9-d8dd-4da9-950c-2ca994b23555/", "name":"cooler", "uuid":"02d636b9-d8dd-4da9-950c-2ca994b23555", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } } ], "analysis_step_types":[ "aggregation", "normalization", "file format conversion" ] }, "name":"cool2mcool", "inputs":[ { "meta":{ "type":"data file", "global":true, "cardinality":"single", "file_format":"cool" }, "name":"input_cool", "source":[ { "name":"input_cool" } ], "run_data":{ "file":[ "46e82a90-49e5-4c33-afab-9ec90d65faa1" ], "type":"input", "meta":[ { "ordinal":1 } ] } }, { "meta":{ "type":"parameter", "global":true, "cardinality":"single" }, "name":"ncores", "source":[ { "name":"ncores" } ], "run_data":{ "value":[ "8" ], "type":"parameter", "meta":[ { "ordinal":1 } ] } } ], "outputs":[ { "meta":{ "type":"data file", "global":false, "cardinality":"single", "file_format":"mcool" }, "name":"output_mcool", "target":[ { "name":"input_mcool", "step":"add_hic_normvector_to_mcool" } ] } ] }, { "meta":{ "software_used":[ { "title":"mcool2hic_34b5430e8b9cfd8f01203e0821b68efe4897b18f", "display_title":"mcool2hic_34b5430e8b9cfd8f01203e0821b68efe4897b18f", "link_id":"~softwares~c91a2c9d-079c-4647-9951-da95f2c9baf1~", "@id":"/softwares/c91a2c9d-079c-4647-9951-da95f2c9baf1/", "name":"mcool2hic", "uuid":"c91a2c9d-079c-4647-9951-da95f2c9baf1", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } } ], "analysis_step_types":[ "file format conversion" ] }, "name":"extract_mcool_normvector_for_juicebox", "inputs":[ { "meta":{ "type":"data file", "global":false, "cardinality":"single", "file_format":"mcool" }, "name":"input_mcool", "source":[ { "name":"output_mcool", "step":"add_hic_normvector_to_mcool" } ] } ], "outputs":[ { "meta":{ "type":"data file", "global":true, "cardinality":"single", "file_format":"normvector_juicerformat" }, "name":"output_normvector", "target":[ { "name":"output_normvector" } ], "run_data":{ "file":[ "7f9eb396-5c1a-1111-aebf-28ea39d6a50f" ], "type":"output", "meta":[ { "format":"normvector_juicerformat", "status":"COMPLETED", "export_id":"0NW3nlHzmPxL9fbL0Oh1BI9BERpu8HsQ", "extension":".normvector.juicerformat.gz", "upload_key":"7f9eb396-5c1a-1111-aebf-28ea39d6a50f/4DNFIAAAAAA2.normvector.juicerformat.gz" } ] } } ] }, { "meta":{ "software_used":[ { "title":"cooler_0.7.4", "display_title":"cooler_0.7.4", "version":"0.7.4", "link_id":"~softwares~02d636b9-d8dd-4da9-950c-2ca994b23555~", "@id":"/softwares/02d636b9-d8dd-4da9-950c-2ca994b23555/", "name":"cooler", "uuid":"02d636b9-d8dd-4da9-950c-2ca994b23555", "principals_allowed":{ "view":[ "award.b0b9c607-f8b4-4f02-93f4-9895b461334b", "group.admin", "group.read-only-admin", "lab.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989", "remoteuser.EMBED", "remoteuser.INDEXER" ], "edit":[ "group.admin", "submits_for.828cd4fe-ebb0-4b36-a94a-d2e3a36cc989" ], "audit":[ "system.Everyone" ] } } ], "analysis_step_types":[ "file format conversion" ] }, "name":"add_hic_normvector_to_mcool", "inputs":[ { "meta":{ "type":"data file", "global":true, "cardinality":"single", "file_format":"hic" }, "name":"input_hic", "source":[ { "name":"input_hic" } ], "run_data":{ "file":[ "46e82a90-49e5-4c33-afab-9ec90d65faa0" ], "type":"input", "meta":[ { "ordinal":1 } ] } }, { "meta":{ "type":"data file", "global":false, "cardinality":"single", "file_format":"mcool" }, "name":"input_mcool", "source":[ { "name":"output_mcool", "step":"cool2mcool" } ] } ], "outputs":[ { "meta":{ "type":"data file", "global":true, "cardinality":"single", "file_format":"mcool" }, "name":"output_mcool", "target":[ { "name":"output_mcool" }, { "name":"input_mcool", "step":"extract_mcool_normvector_for_juicebox" } ], "run_data":{ "file":[ "d273d710-6b6d-4e43-a84c-5658a891c033" ], "type":"output", "meta":[ { "format":"mcool", "status":"COMPLETED", "export_id":"B9H2LpQuS5O4P61FlSUYQSfdurJbjRhM", "extension":".mcool", "upload_key":"d273d710-6b6d-4e43-a84c-5658a891c033/4DNFIMCOOL02.mcool" } ] } } ] } ] }; export default WorkflowRunDataBlob;
39.073973
220
0.359627
fcef3c1920c56b859b7e294732b225774d617bc5
4,573
js
JavaScript
notifications/slack.js
PHeonix25/lambci
96af18877413e0d6e689ed0efaf054593d377451
[ "MIT" ]
null
null
null
notifications/slack.js
PHeonix25/lambci
96af18877413e0d6e689ed0efaf054593d377451
[ "MIT" ]
null
null
null
notifications/slack.js
PHeonix25/lambci
96af18877413e0d6e689ed0efaf054593d377451
[ "MIT" ]
null
null
null
var async = require('async') var utils = require('../utils') var config = require('../utils/config') var log = require('../utils/log') var USER_AGENT = config.STACK exports.createClient = function(token, options, build) { return new SlackClient(token, options, build) } exports.SlackClient = SlackClient function SlackClient(token, options, build) { this.token = token this.channel = options.channel this.username = options.username this.iconUrl = options.iconUrl this.asUser = options.asUser this.lastTs = null // Most recent timestamp this.repo = build.repo this.branch = build.branch this.prNum = build.prNum this.commit = build.commit this.logUrl = build.logUrl this.statusQueue = async.queue(this.updateStatus.bind(this), 1) build.statusEmitter.on('start', (buildInfo) => { var status = { color: 'warning', title: `Build #${buildInfo.buildNum} started...`, } this.statusQueue.push(status, log.logIfErr) }) build.statusEmitter.on('finish', (err, buildInfo) => { var status = {}, elapsedTxt = utils.elapsedTxt(buildInfo.startedAt, buildInfo.endedAt) if (err) { var txt = err.message if (err.logTail) { txt = `${err.logTail}\n${txt}` } status.color = 'danger' status.title = `Build #${buildInfo.buildNum} failed (${elapsedTxt})` status.text = '```' + txt.replace(/```/g, "'''") + '```' // TODO: not sure best way to escape ``` } else { status.color = 'good' status.title = `Build #${buildInfo.buildNum} successful (${elapsedTxt})` } this.statusQueue.push(status, log.logIfErr) }) } SlackClient.prototype.updateStatus = function(status, cb) { var attachment = { color: status.color, // good, warning, danger title: status.title, title_link: status.url || this.logUrl, fallback: status.title, fields: [{ title: 'Repository', value: `<https://github.com/${this.repo}|${this.repo}>`, short: true, }, { title: this.prNum ? 'Pull Request' : 'Branch', value: this.prNum ? `<https://github.com/${this.repo}/pull/${this.prNum}|#${this.prNum}>` : `<https://github.com/${this.repo}/tree/${this.branch}|${this.branch}>`, short: true, }], } if (status.text) { attachment.text = status.text attachment.mrkdwn_in = ['text'] } this.update({attachments: JSON.stringify([attachment])}, cb) } SlackClient.prototype.postMessage = function(body, cb) { body = body || {} body.token = body.token || this.token body.channel = body.channel || this.channel body.username = body.username || this.username body.icon_url = body.icon_url || this.iconUrl body.as_user = body.as_user || this.asUser this.request({path: '/api/chat.postMessage', body: body}, (err, data) => { if (err) return cb(err) // If we're using `this.channel`, it might be the public channel name – // so update it to be the encoded name (C024BE91L) as a number of endpoints // (eg, chat.update) need this instead of the public name if (data && data.channel && body.channel == this.channel && data.channel != this.channel) { this.channel = data.channel } // Update most recent timestamp if (data && data.ts) { this.lastTs = data.ts } cb(null, data) }) } SlackClient.prototype.update = function(body, cb) { body = body || {} body.token = body.token || this.token body.channel = body.channel || this.channel // Must be the encoded ID, eg C024BE91L body.ts = body.ts || this.lastTs body.username = body.username || this.username body.icon_url = body.icon_url || this.iconUrl body.as_user = body.as_user || this.asUser if (!body.ts) { return this.postMessage(body, cb) } this.request({path: '/api/chat.update', body: body}, cb) } SlackClient.prototype.request = function(options, cb) { /* eslint dot-notation:0 */ options.host = 'slack.com' options.headers = options.headers || {} options.headers['Accept'] = 'application/json' options.headers['User-Agent'] = USER_AGENT if (options.body) { options.headers['Content-Type'] = 'application/x-www-form-urlencoded' } utils.request(options, function(err, res, data) { if (err) return cb(err) if (res.statusCode >= 400) { err = new Error(data) err.statusCode = res.statusCode return cb(err) } var json try { json = JSON.parse(data) } catch (e) { e.body = data return cb(e) } if (!json.ok) { return cb(new Error(json.error || data)) } cb(null, json) }) }
30.085526
103
0.635032
fcef4f70f48907f01c3c01591fe9c69c28a7aa3d
908
js
JavaScript
src/Topxia/WebBundle/Resources/public/js/controller/group/group_logo_crop.js
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
dce7114bde92d6ca9f4daed880b8163df4e6a1b2
[ "MIT" ]
null
null
null
src/Topxia/WebBundle/Resources/public/js/controller/group/group_logo_crop.js
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
dce7114bde92d6ca9f4daed880b8163df4e6a1b2
[ "MIT" ]
null
null
null
src/Topxia/WebBundle/Resources/public/js/controller/group/group_logo_crop.js
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
dce7114bde92d6ca9f4daed880b8163df4e6a1b2
[ "MIT" ]
null
null
null
define(function(require, exports, module) { var ImageCrop = require('edusoho.imagecrop'); exports.run = function() { var $form = $("#avatar-crop-form"), $picture = $("#avatar-crop"); var imageCrop = new ImageCrop({ element: "#logo-crop", group: 'group', cropedWidth: 200, cropedHeight: 200 }); imageCrop.on("afterCrop", function(response){ var url = $("#upload-picture-btn").data("url"); $.post(url, {images: response}, function(){ document.location.href=$("#upload-picture-btn").data("reloadUrl"); }); }); $("#upload-picture-btn").click(function(e){ e.stopPropagation(); imageCrop.crop({ imgs: { logo: [200, 200] } }); }) }; });
25.222222
82
0.461454
fcefda76ff4bfdba5f1031a64003f3cf271bd1d5
2,270
js
JavaScript
_next/static/chunks/react-syntax-highlighter_languages_highlight_rust.cb6ab459279f0ba8.js
zkeq/onedrive-vercel-index
3f8ce4f43ad2a628299fc6e1f22b060d52baee93
[ "MIT" ]
2
2022-03-14T06:54:33.000Z
2022-03-19T00:39:51.000Z
_next/static/chunks/react-syntax-highlighter_languages_highlight_rust.cb6ab459279f0ba8.js
zkeq/onedrive-vercel-index
3f8ce4f43ad2a628299fc6e1f22b060d52baee93
[ "MIT" ]
10
2022-01-30T14:41:35.000Z
2022-03-30T10:06:21.000Z
_next/static/chunks/react-syntax-highlighter_languages_highlight_rust.cb6ab459279f0ba8.js
zkeq/onedrive-vercel-index
3f8ce4f43ad2a628299fc6e1f22b060d52baee93
[ "MIT" ]
1
2022-03-14T06:55:42.000Z
2022-03-14T06:55:42.000Z
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[3478],{77077:function(e){e.exports=function(e){const n="([ui](8|16|32|64|128|size)|f(32|64))?",t="drop i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 str char bool Box Option Result String Vec Copy Send Sized Sync Drop Fn FnMut FnOnce ToOwned Clone Debug PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator Extend IntoIterator DoubleEndedIterator ExactSizeIterator SliceConcatExt ToString assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! debug_assert! debug_assert_eq! env! panic! file! format! format_args! include_bin! include_str! line! local_data_key! module_path! option_env! print! println! select! stringify! try! unimplemented! unreachable! vec! write! writeln! macro_rules! assert_ne! debug_assert_ne!";return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",keyword:"abstract as async await become box break const continue crate do dyn else enum extern false final fn for if impl in let loop macro match mod move mut override priv pub ref return self Self static struct super trait true try type typeof unsafe unsized use virtual where while yield",literal:"true false Some None Ok Err",built_in:t},illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.COMMENT("/\\*","\\*/",{contains:["self"]}),e.inherit(e.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"string",variants:[{begin:/r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'\\?(x\w{2}|u\w{4}|U\w{8}|.)'/}]},{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*/},{className:"number",variants:[{begin:"\\b0b([01_]+)"+n},{begin:"\\b0o([0-7_]+)"+n},{begin:"\\b0x([A-Fa-f0-9_]+)"+n},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+n}],relevance:0},{className:"function",beginKeywords:"fn",end:"(\\(|<)",excludeEnd:!0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"meta-string",begin:/"/,end:/"/}]},{className:"class",beginKeywords:"type",end:";",contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{endsParent:!0})],illegal:"\\S"},{className:"class",beginKeywords:"trait enum struct union",end:/\{/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{endsParent:!0})],illegal:"[\\w\\d]"},{begin:e.IDENT_RE+"::",keywords:{built_in:t}},{begin:"->"}]}}}}]);
2,270
2,270
0.707489
fcf004cd07b4247fe17f39af2f76c725fc3e065d
772
js
JavaScript
shared/isomorphic/containers/UIElements/Carousel/Carousel.styles.js
hoanglongla/Team6-FE
2a617ff9f29691237ec54f88d7b82b146d014bee
[ "Apache-2.0" ]
null
null
null
shared/isomorphic/containers/UIElements/Carousel/Carousel.styles.js
hoanglongla/Team6-FE
2a617ff9f29691237ec54f88d7b82b146d014bee
[ "Apache-2.0" ]
1
2021-09-03T04:59:53.000Z
2021-09-03T04:59:53.000Z
app/shared/isomorphic/containers/UIElements/Carousel/Carousel.styles.js
langhoangtien/lifetek-core
d7654e5296c129e9c84fa3af5ec391a62f0aa2fc
[ "MIT" ]
null
null
null
import styled from 'styled-components'; import { palette } from 'styled-theme'; import WithDirection from '@iso/lib/helpers/rtl'; const CarouselStyleWrapper = styled.div` .isoCarousalDemoContainer { width: 100%; display: flex; flex-flow: row wrap; } .ant-carousel { .slick-slider { direction: ${props => (props['data-rtl'] === 'rtl' ? 'ltr' : 'inherit')}; .slick-track { left: auto; right: 0; .slick-slide { text-align: center; height: 160px; line-height: 160px; background: ${palette('secondary', 4)}; color: #fff; overflow: hidden; float: left !important; } } } } `; export default WithDirection(CarouselStyleWrapper);
23.393939
79
0.569948
fcf0edcdc01e0b7be577195d7b1fea99971325ee
10,002
js
JavaScript
app/assets/javascripts/models/activity.js
mpushpav/chorus
4e726a5a082d019919af72f1f943bb8f109c1b4f
[ "Apache-2.0" ]
null
null
null
app/assets/javascripts/models/activity.js
mpushpav/chorus
4e726a5a082d019919af72f1f943bb8f109c1b4f
[ "Apache-2.0" ]
null
null
null
app/assets/javascripts/models/activity.js
mpushpav/chorus
4e726a5a082d019919af72f1f943bb8f109c1b4f
[ "Apache-2.0" ]
null
null
null
(function() { var CLASS_MAP = { "actor": "User", "dataset": "WorkspaceDataset", 'dataSource': 'DynamicDataSource', "gnipDataSource": "GnipDataSource", "newOwner": "User", "hdfsDataSource": "HdfsDataSource", "hdfsDataset": "HdfsDataset", "workfile": "Workfile", "workspace": "Workspace", "newUser" : "User", "noteObject" : "NoteObject", "hdfsEntry" : "HdfsEntry", "member": "User", "sourceDataset": "WorkspaceDataset", "schema": "Schema", "job": "Job", "jobResult": "JobResult" }; function makeAssociationMethod(associate, setupFunction) { return function() { var model; if ( associate === 'dataset' && this.get(associate)) { model = new chorus.models.DynamicDataset(this.get(associate)); } else { var className = CLASS_MAP[associate]; var modelClass = chorus.models[className]; model = new modelClass(this.get(associate)); } if (setupFunction) setupFunction.call(this, model); return model; }; } chorus.models.Activity = chorus.models.Base.extend({ constructorName: "Activity", urlTemplate: "activities/{{id}}", author: function() { if (!this._author) { if (this.has("author")) { this._author = new chorus.models.User(this.get("author")); } else if (this.has("actor")) { this._author = new chorus.models.User(this.get("actor")); } } return this._author; }, newOwner: makeAssociationMethod("newOwner"), workspace: makeAssociationMethod("workspace"), schema: makeAssociationMethod("schema"), actor: makeAssociationMethod("actor"), dataSource: makeAssociationMethod('dataSource'), gnipDataSource: makeAssociationMethod("gnipDataSource"), hdfsDataSource: makeAssociationMethod("hdfsDataSource"), workfile: makeAssociationMethod("workfile"), newUser: makeAssociationMethod("newUser"), member: makeAssociationMethod("member"), job: makeAssociationMethod("job"), jobResult: makeAssociationMethod("jobResult", function (model) { model.set({job: this.get("job")}, {silent: true}); }), dataset: makeAssociationMethod("dataset", function(model) { model.set({workspace: this.get("workspace")}, {silent: true}); }), importSource: makeAssociationMethod("sourceDataset", function(model) { model.set({workspace: this.get("workspace")}, {silent: true}); }), hdfsEntry: makeAssociationMethod("hdfsEntry", function(model) { var hdfsEntry = this.get("hdfsEntry"); model.set({ id : hdfsEntry.id, hdfsDataSource: hdfsEntry.hdfsDataSource }); }), hdfsDataset: makeAssociationMethod("hdfsDataset", function (model) { model.set({workspace: this.get("workspace")}, {silent: true}); }), noteObject: function() { var model; switch (this.get("actionType")) { case "NoteOnHdfsDataSource": model = new chorus.models.HdfsDataSource(); model.set(this.get("hdfsDataSource")); break; case "NoteOnDataSource": model = new chorus.models.DynamicDataSource(this.get("dataSource")); break; case "NoteOnGnipDataSource": model = new chorus.models.GnipDataSource(); model.set(this.get("gnipDataSource")); break; case "NoteOnHdfsFile": model = new chorus.models.HdfsEntry(); model.set(this.get("hdfsFile")); break; case "NoteOnWorkspace": model = new chorus.models.Workspace(); model.set(this.get("workspace")); break; case "NoteOnDataset": model = new chorus.models.DynamicDataset(this.get("dataset")); break; case "NoteOnWorkspaceDataset": model = new chorus.models.WorkspaceDataset(); model.set(this.get("dataset")); model.setWorkspace(this.get("workspace")); break; case "NoteOnWorkfile": model = new chorus.models.Workfile(); model.set(this.get("workfile")); break; } return model; }, comments: function() { this._comments || (this._comments = new chorus.collections.CommentSet( this.get("comments"), { entityType: this.collection && this.collection.attributes.entityType, entityId: this.collection && this.collection.attributes.entityId } )); return this._comments; }, promoteToInsight: function(options) { var insight = new chorus.models.Insight({ noteId: this.get("id"), action: "create" }); insight.bind("saved", function() { this.fetch(); if (options && options.success) { options.success(this); } }, this); insight.save({ validateBody: false }); }, demoteFromInsight: function() { this.set({isInsight: false}); new chorus.models.Insight({id: this.id, action: 'destroy'}).destroy(); }, publish: function() { var insight = new chorus.models.Insight({ noteId: this.get("id"), action: "publish" }); insight.bind("saved", function() { this.fetch(); }, this); insight.save({ validateBody: false }, {method: 'create'}); }, unpublish: function() { var insight = new chorus.models.Insight({ noteId: this.get("id"), action: "unpublish" }); insight.bind("saved", function() { this.fetch(); }, this); insight.save({ validateBody: false }, {method: 'create'}); }, toNote: function() { var comment = new chorus.models.Note({ id: this.id, body: this.get("body") }); return comment; }, attachments: function() { if (!this._attachments) { this._attachments = _.map(this.get("attachments"), function(attachment) { var klass; switch (attachment.entityType) { case 'workfile': klass = chorus.models.DynamicWorkfile; break; case 'dataset': klass = chorus.models.WorkspaceDataset; break; case 'work_flow_result': klass = chorus.models.WorkFlowResult; break; default: klass = chorus.models.Attachment; break; } return new klass(attachment); }); } return this._attachments; }, isNote: function() { return this.get("action") === "NOTE"; }, canBePromotedToInsight: function() { return this.isNote() && !this.isInsight(); }, canBeDemotedBy: function(user) { return this.isInsight() && (user.id === this.promoter().id || user.isAdmin() || user.id === this.workspace().owner().id); }, isInsight: function() { return this.get("isInsight"); }, isSubComment: function() { return this.get("action") === "SUB_COMMENT"; }, hasCommitMessage: function() { return this.get("commitMessage"); }, isUserGenerated: function () { return this.isNote() || this.isInsight() || this.isSubComment(); }, isPublished: function() { return this.get("isPublished"); }, isOwner: function() { return (this.actor().id === chorus.session.user().id); }, isFailure: function() { var failureActions = [ "CredentialsInvalid", "GnipStreamImportFailed", "FileImportFailed", "WorkspaceImportFailed", "SchemaImportFailed" ]; return _.contains(failureActions, this.get("action")); }, isSuccessfulImport: function() { var successActions = [ "GnipStreamImportSuccess", "FileImportSuccess", "WorkspaceImportSuccess", "SchemaImportSuccess" ]; return _.contains(successActions, this.get("action")); }, promoterLink: function() { var promoter = this.promoter(); return promoter ? Handlebars.helpers.userProfileLink(promoter) : "MISSING PROMOTER"; }, promoter: function () { return this.get("promotedBy") ? new chorus.models.User(this.get("promotedBy")) : null; }, promotionTimestamp:function() { return this.get("promotionTime") ? Handlebars.helpers.relativeTimestamp(this.get("promotionTime")) : null; }, reindexError: function() { if (this.isFailure()) { this.attributes['errorModelId'] = this.get("id"); } } }); })();
33.34
133
0.5022
fcf1908a784439d7a182849238543568453cf036
332
js
JavaScript
src/action-types/region.js
leogoesger/gutsy-client
4d2d107e6c537c6be9d5d1d34db2959553ca7733
[ "MIT" ]
null
null
null
src/action-types/region.js
leogoesger/gutsy-client
4d2d107e6c537c6be9d5d1d34db2959553ca7733
[ "MIT" ]
null
null
null
src/action-types/region.js
leogoesger/gutsy-client
4d2d107e6c537c6be9d5d1d34db2959553ca7733
[ "MIT" ]
null
null
null
const RegionTypes = { FETCH_REGIONS_OBJECT: 'FETCH_REGIONS_OBJECT', FETCH_REGIONS_SUCCESS: 'FETCH_REGIONS_SUCCESS', FETCH_REGIONS_FAIL: 'FETCH_REGIONS_FAIL', FETCH_REGION_OBJECT: 'FETCH_REGION_OBJECT', FETCH_REGION_SUCCESS: 'FETCH_REGION_SUCCESS', FETCH_REGION_FAIL: 'FETCH_REGION_FAIL', }; export default RegionTypes;
30.181818
49
0.813253
fcf1a0a40b93eebcdf6a7f6531a21fbf6fc783e7
862
js
JavaScript
packages/webpack-plugin/lib/platform/template/wx/component-config/form.js
hubvue/mpx
e65d3f565a1b980f2f47a1820b23698aee2dddc8
[ "Apache-2.0" ]
1
2021-06-25T15:36:18.000Z
2021-06-25T15:36:18.000Z
packages/webpack-plugin/lib/platform/template/wx/component-config/form.js
Casey-ckx/mpx
2d460f15e4ef5e7225dec8e666db4bf481fe256a
[ "Apache-2.0" ]
null
null
null
packages/webpack-plugin/lib/platform/template/wx/component-config/form.js
Casey-ckx/mpx
2d460f15e4ef5e7225dec8e666db4bf481fe256a
[ "Apache-2.0" ]
null
null
null
const TAG_NAME = 'form' module.exports = function ({ print }) { const aliPropLog = print({ platform: 'ali', tag: TAG_NAME, isError: false }) const baiduPropLog = print({ platform: 'baidu', tag: TAG_NAME, isError: false }) const qqPropLog = print({ platform: 'qq', tag: TAG_NAME, isError: false }) // const ttPropLog = print({ platform: 'bytedance', tag: TAG_NAME, isError: false }) const webPropLog = print({ platform: 'web', tag: TAG_NAME, isError: false }) return { test: TAG_NAME, web (tag, { el }) { // form全量使用内建组件 el.isBuiltIn = true return 'mpx-form' }, props: [ { test: /^(report-submit-timeout)$/, ali: aliPropLog, swan: baiduPropLog, qq: qqPropLog }, { test: /^(report-submit|report-submit-timeout)$/, web: webPropLog } ] } }
27.806452
86
0.582367
fcf1c259e79afab89f4164bf1e0a098e68e54e4d
701
js
JavaScript
web/js/ticket.js
EternalRat/EternalLobbies-Manager
97fd3d2d38821c14faa15d69d5d8f05728572fdb
[ "CC0-1.0", "MIT" ]
null
null
null
web/js/ticket.js
EternalRat/EternalLobbies-Manager
97fd3d2d38821c14faa15d69d5d8f05728572fdb
[ "CC0-1.0", "MIT" ]
null
null
null
web/js/ticket.js
EternalRat/EternalLobbies-Manager
97fd3d2d38821c14faa15d69d5d8f05728572fdb
[ "CC0-1.0", "MIT" ]
null
null
null
const { ipcRenderer, IpcRendererEvent } = require("electron"); const ipc = ipcRenderer; ipc.on('previewHTMLFile', /** * * @param {IpcRendererEvent} evt * @param {String} args */ (evt, args) => { var preview = document.getElementsByClassName('preview')[0]; if (preview.childElementCount !== 0) preview.innerHTML = ""; var html = args.slice(args.indexOf('<div class="ticket">'), args.lastIndexOf('</div>') + '</div>'.length); preview.innerHTML = html; }); minimizeTicketBtn.addEventListener('click', () => { ipc.send('minimizeTicketApp'); }); closeTicketBtn.addEventListener('click', () => { ipc.send('closeTicketApp'); });
29.208333
114
0.611983
fcf1d91f49488083f470f6f45d18f384f9ea77df
1,005
js
JavaScript
aggregatorcomparor/static/libs/jQuery/src/exports/amd.js
docking-org/aggregator-comparor
c142c9694e4891f2ed98eca5ffe36685205ac799
[ "MIT" ]
1
2015-08-25T23:10:53.000Z
2015-08-25T23:10:53.000Z
flaskapp/static/libs/jQuery/src/exports/amd.js
skipallmighty/flask-app
f3d6521767a18c91090c6fc3c97ed3a445f7287f
[ "BSD-3-Clause" ]
null
null
null
flaskapp/static/libs/jQuery/src/exports/amd.js
skipallmighty/flask-app
f3d6521767a18c91090c6fc3c97ed3a445f7287f
[ "BSD-3-Clause" ]
1
2021-01-18T01:35:13.000Z
2021-01-18T01:35:13.000Z
define([ "../core" ], function( jQuery ) { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } });
41.875
82
0.741294
fcf23881861f68f53d28843bca1fbd3a0387f8bb
1,895
js
JavaScript
d2l-tab-panel.js
d2lfederation/tabs
fda7cd24242b9dc83d5ea4f145d1a284dfa2405c
[ "Apache-2.0" ]
null
null
null
d2l-tab-panel.js
d2lfederation/tabs
fda7cd24242b9dc83d5ea4f145d1a284dfa2405c
[ "Apache-2.0" ]
null
null
null
d2l-tab-panel.js
d2lfederation/tabs
fda7cd24242b9dc83d5ea4f145d1a284dfa2405c
[ "Apache-2.0" ]
null
null
null
/** `d2l-tab-panel` Polymer-based web components for tab @demo demo/index.html */ /* FIXME(polymer-modulizer): the above comments were extracted from HTML and may be out of place here. Review them and then delete this comment! */ import '@polymer/polymer/polymer-legacy.js'; import { Polymer } from '@polymer/polymer/lib/legacy/polymer-fn.js'; const $_documentContainer = document.createElement('template'); $_documentContainer.innerHTML = `<dom-module id="d2l-tab-panel"> <template strip-whitespace=""> <style> :host { box-sizing: border-box; display: none; margin: 1.2rem 0; } :host([no-padding]) { margin: 0; } :host([selected]) { display: block; } </style> <slot></slot> </template> </dom-module>`; document.head.appendChild($_documentContainer.content); Polymer({ is: 'd2l-tab-panel', hostAttributes: { 'role': 'tabpanel' }, properties: { /** * Whether to exclude default padding from the panel. */ noPadding: { type: Boolean, reflectToAttribute: true }, /** * Indicates the selected tab. */ selected: { type: Boolean, observer: '_handleSelected', reflectToAttribute: true }, /** * Text for the tab. */ text: { type: String, observer: '_updateText' } }, attached: function() { if (this.selected) { requestAnimationFrame(function() { this._dispatchSelected(); }.bind(this)); } }, _dispatchSelected: function() { this.dispatchEvent(new CustomEvent( 'd2l-tab-panel-selected', { bubbles: true, composed: true } )); }, _handleSelected: function(newValue) { if (newValue) { this._dispatchSelected(); } }, _updateText: function() { this.setAttribute('aria-label', this.text); this.dispatchEvent(new CustomEvent( 'd2l-tab-panel-text-changed', { bubbles: true, composed: true, detail: { text: this.text } } )); } });
17.877358
95
0.644855
fcf252c31ed1a30478d2a467727a9f438905ed10
4,282
js
JavaScript
WebsiteFramework_src/WebSite/Extjs_lib/pkgs/data-xml.js
Jarrey/tbwebframework
c26241776b0dd04c6041e8d50f69d97a2b64a565
[ "Apache-2.0" ]
1
2016-05-06T13:37:57.000Z
2016-05-06T13:37:57.000Z
WebsiteFramework_src/WebSite/Extjs_lib/pkgs/data-xml.js
Jarrey/tbwebframework
c26241776b0dd04c6041e8d50f69d97a2b64a565
[ "Apache-2.0" ]
null
null
null
WebsiteFramework_src/WebSite/Extjs_lib/pkgs/data-xml.js
Jarrey/tbwebframework
c26241776b0dd04c6041e8d50f69d97a2b64a565
[ "Apache-2.0" ]
null
null
null
/* * Ext JS Library 3.1.0 * Copyright(c) 2006-2009 Ext JS, LLC * licensing@extjs.com * http://www.extjs.com/license */ Ext.data.XmlWriter=function(a){Ext.data.XmlWriter.superclass.constructor.apply(this,arguments);this.tpl=(typeof(this.tpl)==="string")?new Ext.XTemplate(this.tpl).compile():this.tpl.compile()};Ext.extend(Ext.data.XmlWriter,Ext.data.DataWriter,{documentRoot:"xrequest",forceDocumentRoot:false,root:"records",xmlVersion:"1.0",xmlEncoding:"ISO-8859-15",tpl:'<tpl for="."><?xml version="{version}" encoding="{encoding}"?><tpl if="documentRoot"><{documentRoot}><tpl for="baseParams"><tpl for="."><{name}>{value}</{name}</tpl></tpl></tpl><tpl if="records.length&gt;1"><{root}></tpl><tpl for="records"><{parent.record}><tpl for="."><{name}>{value}</{name}></tpl></{parent.record}></tpl><tpl if="records.length&gt;1"></{root}></tpl><tpl if="documentRoot"></{documentRoot}></tpl></tpl>',render:function(b,c,a){c=this.toArray(c);b.xmlData=this.tpl.applyTemplate({version:this.xmlVersion,encoding:this.xmlEncoding,documentRoot:(c.length>0||this.forceDocumentRoot===true)?this.documentRoot:false,record:this.meta.record,root:this.root,baseParams:c,records:(Ext.isArray(a[0]))?a:[a]})},createRecord:function(a){return this.toArray(this.toHash(a))},updateRecord:function(a){return this.toArray(this.toHash(a))},destroyRecord:function(b){var a={};a[this.meta.idProperty]=b.id;return this.toArray(a)}});Ext.data.XmlReader=function(a,b){a=a||{};Ext.applyIf(a,{idProperty:a.idProperty||a.idPath||a.id,successProperty:a.successProperty||a.success});Ext.data.XmlReader.superclass.constructor.call(this,a,b||a.fields)};Ext.extend(Ext.data.XmlReader,Ext.data.DataReader,{read:function(a){var b=a.responseXML;if(!b){throw {message:"XmlReader.read: XML Document not available"}}return this.readRecords(b)},readRecords:function(d){this.xmlData=d;var a=d.documentElement||d,c=Ext.DomQuery,f=0,e=true;if(this.meta.totalProperty){f=this.getTotal(a,0)}if(this.meta.successProperty){e=this.getSuccess(a)}var b=this.extractData(c.select(this.meta.record,a),true);return{success:e,records:b,totalRecords:f||b.length}},readResponse:function(e,a){var d=Ext.DomQuery,f=a.responseXML;var b=new Ext.data.Response({action:e,success:this.getSuccess(f),message:this.getMessage(f),data:this.extractData(d.select(this.meta.record,f)||d.select(this.meta.root,f),false),raw:f});if(Ext.isEmpty(b.success)){throw new Ext.data.DataReader.Error("successProperty-response",this.meta.successProperty)}if(e===Ext.data.Api.actions.create){var c=Ext.isDefined(b.data);if(c&&Ext.isEmpty(b.data)){throw new Ext.data.JsonReader.Error("root-empty",this.meta.root)}else{if(!c){throw new Ext.data.JsonReader.Error("root-undefined-response",this.meta.root)}}}return b},getSuccess:function(){return true},buildExtractors:function(){if(this.ef){return}var l=this.meta,h=this.recordType,e=h.prototype.fields,k=e.items,j=e.length;if(l.totalProperty){this.getTotal=this.createAccessor(l.totalProperty)}if(l.successProperty){this.getSuccess=this.createAccessor(l.successProperty)}if(l.messageProperty){this.getMessage=this.createAccessor(l.messageProperty)}this.getRoot=function(f){return(!Ext.isEmpty(f[this.meta.record]))?f[this.meta.record]:f[this.meta.root]};if(l.idPath||l.idProperty){var d=this.createAccessor(l.idPath||l.idProperty);this.getId=function(f){var g=d(f)||f.id;return(g===undefined||g==="")?null:g}}else{this.getId=function(){return null}}var c=[];for(var b=0;b<j;b++){e=k[b];var a=(e.mapping!==undefined&&e.mapping!==null)?e.mapping:e.name;c.push(this.createAccessor(a))}this.ef=c},createAccessor:function(){var a=Ext.DomQuery;return function(b){switch(b){case this.meta.totalProperty:return function(c,d){return a.selectNumber(b,c,d)};break;case this.meta.successProperty:return function(d,e){var c=a.selectValue(b,d,true);var f=c!==false&&c!=="false";return f};break;default:return function(c,d){return a.selectValue(b,c,d)};break}}}(),extractValues:function(h,d,a){var g,c={};for(var e=0;e<a;e++){g=d[e];var b=this.ef[e](h);c[g.name]=g.convert((b!==undefined)?b:g.defaultValue,h)}return c}});Ext.data.XmlStore=Ext.extend(Ext.data.Store,{constructor:function(a){Ext.data.XmlStore.superclass.constructor.call(this,Ext.apply(a,{reader:new Ext.data.XmlReader(a)}))}});Ext.reg("xmlstore",Ext.data.XmlStore);
611.714286
4,158
0.749883
fcf2a95b3c06f6162b65bfe4a22249ec2edbc7a8
1,868
js
JavaScript
src/js/main.js
yrtzaleman11/jquery-apod
1b2ae6a9b89fd8da61ec41cc95ce3b593cf6ae88
[ "MIT" ]
null
null
null
src/js/main.js
yrtzaleman11/jquery-apod
1b2ae6a9b89fd8da61ec41cc95ce3b593cf6ae88
[ "MIT" ]
null
null
null
src/js/main.js
yrtzaleman11/jquery-apod
1b2ae6a9b89fd8da61ec41cc95ce3b593cf6ae88
[ "MIT" ]
null
null
null
var apod = { //Create a random date randomDate: function(start, end) { //Randomize the date https://gist.github.com/miguelmota/5b67e03845d840c949c4 let date = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); //Format the date let d = date.getDate(); let m = date.getMonth() + 1; //In JS months start at 0 let y = date.getFullYear(); //Change the month and day strings so that they match the documented format. if(m < 10){ m = '0'+m } if(d < 10){ d = '0'+d } return `${y}-${m}-${d}`; }, // Application Constructor //Injects the results of the API call into the DOM buildDOM: function(result) { $("#apodTitle").text(result.title); if(result.media_type === 'video') { $("#apodImage").hide(); $("#apodVideo > iframe").attr("src", result.url).show(); }else{ $("#apodVideo").hide(); $("#apodImg").attr("src", result.url).attr('alt', result.title).show(); } $("#apodCopyright").text("Copyright: " + result.copyright); $("#apodDate").text("Date: " + result.date); $("#apodDesc").text(result.explanation); }, //Executes an AJAX call to an API. getRequest: function() { let _this = this; let date = this.randomDate(new Date(1995, 5, 16), new Date()); let url = "https://api.nasa.gov/planetary/apod?api_key=e1neM7gYxGE9hJ5BcZlrt9epGux7iUFKWSaYOdKq&date=" + date; $.ajax({ url: url }).done(function(result){ _this.buildDOM(result); }).fail(function(result){ console.log(result); }); }, // Initialization method. init: function() { this.getRequest(); }, }; apod.init(); /* https://learn.jquery.com/using-jquery-core/document-ready/ */ $(function() { $('#btnRandApod').on('click',function(){ apod.getRequest(); }); });
26.685714
114
0.584582
fcf2ee52677645b73d42e836a7b6e456900eeb3e
5,411
js
JavaScript
js/registerCard.js
eunjju1209/munch-PHP
076a70507b294bee282aa46a57e21e1f35c2bef2
[ "MIT" ]
null
null
null
js/registerCard.js
eunjju1209/munch-PHP
076a70507b294bee282aa46a57e21e1f35c2bef2
[ "MIT" ]
null
null
null
js/registerCard.js
eunjju1209/munch-PHP
076a70507b294bee282aa46a57e21e1f35c2bef2
[ "MIT" ]
null
null
null
$(function () { /** * 빌링키 발급 */ var issueBilling = function (params) { var resultCode = false; $.ajax({ url: '/Order/issueBilling', type: "POST", async: false, data: { expiry: params.expiry, birth: params.birth, pwd_2digit: params.pwd_2digit, card_number: params.card_number, customer_uid: params.customer_uid, card_last_num: params.card_last_num }, dataType: 'json', complete: function (result) { var data = result.responseJSON; if (data.code == 0) { resultCode = true; var card_info_html = '<div class="using_card">' + ' <b>사용중인 카드 정보</b>' + ' <br><span>' + data.response.card_name + ' (****-****-****-'+data.response.card_last_num+')</span>' + '</div>' + '<button type="button" class="btn-purple-square" id="changeCard">카드변경</button>'; $('#customer_uid').val(params.customer_uid); $('#register_card_form').html(''); $('#card_info_form').html(card_info_html); $('#changeCard').on('click', function () { changeHtml(); }) $('#register-card').hide(); $('#doPay').show(); } else if (data.message) { alert(data.message); } } }) return resultCode; } var issuedBillingKey = function () { var formData = formValidation(); if (!formData) { return false; } if (!issueBilling(formData)) { return false; } } var makeCustomerUid = function () { var default_data = []; default_data.push($('#member_idx').val()); default_data.push($('input[name="card_num[]"]').eq(3).val()); return default_data.join('_'); } var formValidation = function () { var params = {}; //카드번호 var card_input = $('input[name="card_num[]"]'); var card_num = []; for (var i = 0; i <= 3; i++) { if (!/^[0-9]*$/.test(card_input.eq(i).val()) || !card_input.eq(i).val() || card_input.eq(i).val().length !== 4) { alert('카드번호를 정확하게 입력해주세요.'); return false; } card_num[i] = card_input.eq(i).val(); } params.card_last_num = card_num[3]; if (card_num.length !== 4) { alert('카드번호가 정확하지 않습니다.'); return false; } var month = $('#validity_month'); var year = $('#validity_year'); if (!year.val()) { alert('유효기간을 입력해주세요.'); year.focus(); return false; } if (!month.val()) { alert('유효기간을 입력해주세요.'); month.focus(); return false; } var pwd = $('input[name="pwd_2digit"]'); if (!pwd.val() || !/^[0-9]*$/.test(pwd.val() || pwd.val().length !== 2)) { alert('비밀번호를 정확하게 입력해주세요.'); pwd.focus(); return false; } var birth = $('input[name="birthday"]'); if (!birth.val() || !/^[0-9]*$/.test(birth.val() || birth.val().length !== 6)) { alert('생년월일을 정확하게 입력해주세요.'); birth.focus(); return false; } params.card_number = card_num.join('-'); params.expiry = year.val() + '-' + month.val(); params.birth = birth.val(); params.pwd_2digit = pwd.val(); params.customer_uid = makeCustomerUid(); return params; } $('#register-card').on('click', function () { issuedBillingKey(); }); $('#changeCard').on('click', function () { changeHtml(); }) var changeHtml = function () { $.ajax({ type: 'get', url: '/Order/changeCardHtml', data:{ 'page' : $('#page').val() }, dataType: 'json', complete: function (contents) { if (!!contents.responseText) { $('#doPay').hide(); $('#changeCard').show(); $('#register-card').hide(); $('#customer_uid').val(''); $('#register_card_form').html(contents.responseText); $('#card_info_form').html(''); $('#register-card').on('click', function () { issuedBillingKey(); }); } else { alert('변경요청이 정상적이지 않습니다. 새로고침 후 재시도해주세요.'); } } }); } var changeCard = function () { $.ajax({ url: '/Order/changeCard', type: "POST", data: {customer_uid: $('#customer_uid').val()}, async: true, dataType: 'json', complete: function (result) { var data = result.responseJSON; if (data.code === 'success') { changeHtml(); } } }) } });
30.061111
129
0.419701
fcf378efb2de77b57001bed622f8c5bef4890e24
7,489
js
JavaScript
src/pages/our-style.js
BosEriko/talkpush-com
7d4e9c3b2fd135b166f7847ec89434b8f4de7a06
[ "MIT" ]
null
null
null
src/pages/our-style.js
BosEriko/talkpush-com
7d4e9c3b2fd135b166f7847ec89434b8f4de7a06
[ "MIT" ]
null
null
null
src/pages/our-style.js
BosEriko/talkpush-com
7d4e9c3b2fd135b166f7847ec89434b8f4de7a06
[ "MIT" ]
null
null
null
import React from 'react' import Helmet from 'react-helmet' import Link from 'gatsby-link' import styles from '../pages-style/our-style.module.scss' import phoneIcon from '../pages-images/our-style/phone-icon.svg' import talentIcon from '../pages-images/our-style/talent-icon.png' import cultureIcon from '../pages-images/our-style/culture-icon.svg' import joinIcon from '../pages-images/our-style/join-icon.svg' const pageVariables = { pageCode: 'our-style', pageDescription: 'Talkpush was built to give everyone a chance to let their talent talk. Removing barriers between job seekers and employers has been our mission from day one.', pageTitle: 'Our Style', } const OurStylePage = ({ siteTitle }) => ( <div className={styles.block}> <Helmet> <title>{pageVariables.pageTitle} - {siteTitle}</title> <meta name='description' content={pageVariables.pageDescription} /> <meta property='og:description' content={pageVariables.pageDescription} /> </Helmet> <div className={styles.blockHeader}></div> <div className={styles.blockContent}> <div className="container"> <div className={styles.blockContentDivider}> <div className={styles.blockContentDividerLeft}> <img src={talentIcon} alt="Talent" /> </div> <div className={styles.blockContentDividerRight}> <h2 className="global-hero-glow-green m-0 p-0">The world is our talent pool</h2> <p>We have offices in Hong Kong, Mexico City, Costa Rica, Delhi and Manila. All this traveling can be exhausting at times, but the effort is well worth it. First, it allows us to understand local markets better and to build recruitment experiences that are adapted to the local culture. Secondly, it means we attract a great diversity of talent. For each new role, we try to hire the best person, regardless of where he or she is located. Being so spread out also means we have to make an extra effort to stay connected, so we make extensive use of messaging and video to make sure everybody stays in the loop. We also get together a few times of year for some quality bonding time.</p> </div> </div> <div className={styles.blockContentDivider}> <div className={styles.blockContentDividerLeft}> <img src={phoneIcon} alt="Phone" /> </div> <div className={styles.blockContentDividerRight}> <h2 className="global-hero-glow-green m-0 p-0">Things that we believe in</h2> <p>Everyone has a voice. Everyone has something to offer. So how come so many candidates never get a chance to be heard? At Talkpush, we take down the invisible wall that stands between candidates and recruiters. We make it easier for conversations to start. We do our part in making the world a more connected and productive place by starting thousands of recruitment conversations every day.</p> <p>We are technologists and humanists. We believe software is designed to serve humans, not the other way around. Automation should be a gradual process built around the user. We design software which is human-centric and mobile-first.</p> <p>We also love speech. Actual spoken words. Why limit yourselves to the written word if candidates want to speak to you? Speech is more natural, intuitive and data-rich. Messaging is our preferred communication technology, because it allows for more conversations to happen simultaneously.</p> </div> </div> <div className={styles.blockContentDivider}> <div className={styles.blockContentDividerLeft}> <img src={cultureIcon} alt="Culture" /> </div> <div className={styles.blockContentDividerRight}> <h2 className="global-hero-glow-green m-0 p-0">Our work culture</h2> <p>Every day, Talkpush is making it easier for good companies to hire good people, and that makes us feel great. Admittedly, we have a short attention span but that’s because our days are packed. Making recruitment processes simple is a lot of work. We get it done, removing one barrier at a time.</p> <p>Some of us work from the office, some of us work from home. We don’t keep track of time. We don’t count the amount of vacation we take. Some of us wear suits, some of us wear shorts and sandals. We don’t think the work/life balance debate makes much sense. We come to work because we want to change the world every day, a little bit at a time. Honestly, it’s the only way to Live.</p> </div> </div> {/* <div className={styles.blockContentVideoHolder}> <h2 className="global-hero-glow-green m-0 p-0">A word from Max</h2> <div className={styles.blockContentVideoHolderVideo}> <iframe width="560" height="315" src="https://www.youtube.com/embed/gNISmYgHKC4" frameBorder="0" allowFullScreen></iframe> </div> </div> */} {/* <div className={styles.blockContentSpeech}> <span>Hi there. My name is Max Armbruster.</span> <p>"A decade ago, I used to interview hundreds of candidates over the phone every year. It was gruesome, unproductive, soul- drenching work but I could not find a technology that did not create an additional barrier between me and the candidates. So I just kept on calling...</p> <p>Eight years ago, I co-founded an Applicant Tracking Software company in Singapore. Meeting the largest employers in Asia, I noticed that many of them were choosing complicated job application processes with the specific purpose of limiting the number of candidates (less resumes to sift through...). It seemed like a wrong way to go about talent selection.</p> <p>Five years ago, I sold my company and joined SAP, the enterprise software leader. There, I got a better understanding on how complicated it is to make things simple, particularly for large enterprises. More stakeholders means more complexity, leaving everyone frustrated. I wanted to build a simple recruitment solution that made connecting with candidates as easy as making a phone call.</p> <p>In 2014, I partnered with experts in web and voice technology and we released the first Talkpush prototype. I founded the company and we signed our first client, a small call center. The rest, as they say, is history.</p> <p>Today, our software interviews more candidates than any chatbot in the world, and helps thousands of job seekers find work every year. The messaging revolution, allowing for asynchronous conversations to happen on Facebook Messenger, WeChat, WhatsApp and other chat platforms is fuelling new wave of productivity. We were very fortunate to be in this space at the right time.</p> <p>Tomorrow, we want to re-engineer your recruitment process. Do you wish to create more openness and more simplicity in your recruitment? If so, drop me a line!"</p> <span>Max</span> </div> */} <div className={styles.blockContentJoin}> <div className={styles.blockContentJoinIcon}> <img src={joinIcon} alt="Join Us" /> </div> <div className={styles.blockContentJoinDetails}> <h3>Join our growing team</h3> <p className="m-0 p-0">Join Talkpush and let's make recruitment fun together</p> <Link to="/jobs">Careers</Link> </div> </div> </div> </div> </div> ) export default OurStylePage
86.08046
698
0.708372
fcf48f6968937bfcff0243fcd8d889650c7ed918
1,119
js
JavaScript
src/routes.js
alanalv3s/Foodfy
b2a5d83e8f03db5d6628d29652e8dd6ac127e72d
[ "MIT" ]
null
null
null
src/routes.js
alanalv3s/Foodfy
b2a5d83e8f03db5d6628d29652e8dd6ac127e72d
[ "MIT" ]
1
2021-05-11T15:51:34.000Z
2021-05-11T15:51:34.000Z
src/routes.js
alanalv3s/Foodfy
b2a5d83e8f03db5d6628d29652e8dd6ac127e72d
[ "MIT" ]
null
null
null
const express = require('express') const routes = express.Router() const {recipes} = require('./data') const RecipesController = require('./app/controllers/RecipesController') // Admin routes.get('/admin', (req,res) => res.redirect(301, '/admin/recipes')) routes.get('/admin/recipes', RecipesController.index); routes.get('/admin/recipes/create', RecipesController.create); routes.get('/admin/recipes/:id', RecipesController.show); routes.get('/admin/recipes/:id/edit', RecipesController.edit); // routes.post('/admin/recipes', RecipesController.post) // routes.put('/admin/recipes', RecipesController.put) // routes.delete('/admin/recipes', RecipesController.delete) // Public routes.get('/', (req, res) => res.render('public/index', { recipes })) routes.get('/recipes', (req, res) => res.render('public/recipes/index', { recipes })) routes.get('/recipes/:recipe_index', (req, res) => { const { recipe_index } = req.params const recipe = recipes[recipe_index] res.render('public/recipes/show', { recipe }) }) routes.get('/about', (req, res) => res.render('public/about')) module.exports = routes
36.096774
85
0.701519
fcf4a2a82181558c25018c5412e71bf7885cee67
487
js
JavaScript
test/built-ins/Array/prototype/filter/15.4.4.20-1-10.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
1,849
2015-01-15T12:42:53.000Z
2022-03-30T21:23:59.000Z
test/built-ins/Array/prototype/filter/15.4.4.20-1-10.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
2,157
2015-01-06T05:01:55.000Z
2022-03-31T17:18:08.000Z
test/built-ins/Array/prototype/filter/15.4.4.20-1-10.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
411
2015-01-22T01:40:04.000Z
2022-03-28T19:19:16.000Z
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.prototype.filter description: Array.prototype.filter applied to the Math object ---*/ function callbackfn(val, idx, obj) { return '[object Math]' === Object.prototype.toString.call(obj); } Math.length = 1; Math[0] = 1; var newArr = Array.prototype.filter.call(Math, callbackfn); assert.sameValue(newArr[0], 1, 'newArr[0]');
27.055556
70
0.716632
fcf4f050e933e5c4841d789ac229c8371973e4fc
102
js
JavaScript
test/chunking-form/samples/dynamic-import-only-default/_expected/es/main.js
mistlog/rollup
6f28151f53adb7f91b3e635eeebb0eba5e5d621c
[ "0BSD", "MIT" ]
20
2020-05-20T08:29:38.000Z
2022-03-31T03:18:54.000Z
test/chunking-form/samples/dynamic-import-only-default/_expected/es/main.js
mistlog/rollup
6f28151f53adb7f91b3e635eeebb0eba5e5d621c
[ "0BSD", "MIT" ]
9
2020-03-18T12:12:44.000Z
2022-03-26T08:12:15.000Z
test/chunking-form/samples/dynamic-import-only-default/_expected/es/main.js
mistlog/rollup
6f28151f53adb7f91b3e635eeebb0eba5e5d621c
[ "0BSD", "MIT" ]
3
2021-06-16T08:48:14.000Z
2022-03-25T10:31:04.000Z
var main = Promise.all([import('./entry.js'), import('./generated-other.js')]); export default main;
25.5
79
0.676471
fcf56f3a66969b02fff19010fc01656ec746db64
3,296
js
JavaScript
client/src/app_component/Weather.js
manuelbiolatiri/auth_weatherapi
ad64206595fd698ed152187108350683ee77e17c
[ "MIT" ]
null
null
null
client/src/app_component/Weather.js
manuelbiolatiri/auth_weatherapi
ad64206595fd698ed152187108350683ee77e17c
[ "MIT" ]
1
2021-09-02T14:10:01.000Z
2021-09-02T14:10:01.000Z
client/src/app_component/Weather.js
manuelbiolatiri/auth_weatherapi
ad64206595fd698ed152187108350683ee77e17c
[ "MIT" ]
null
null
null
import React from "react"; import "bootstrap/dist/css/bootstrap.min.css"; import "./weather.style.css"; class Weather extends React.Component { handleClicked() { this.props.clickHandler(); } calculateTemp(degreesK, displayUnits) { if (displayUnits === "C") return Math.floor(degreesK - 273); else return Math.floor(((degreesK - 273) * 9) / 5 + 32); } render() { return ( <div> <div> <h1> {this.props.city && this.props.country && ( <p> {this.props.city}, {this.props.country} </p> )} </h1> {this.props.icon && ( <p> <img src={`http://openweathermap.org/img/w/${this.props.icon}.png`} alt="wthr img" size="40px" /> </p> )} <h1> {this.props.kelvinTemp && ( <p> <i className="fas fa-thermometer-three-quarters"></i>{" "} <span onClick={this.handleClicked.bind(this)}> {this.calculateTemp( this.props.kelvinTemp, this.props.displayUnits )} &deg; {this.props.displayUnits} </span> </p> )} </h1> <div className="row"> <div className="col-md-6"> <h4> {this.props.description && ( <p> {" "} <i className="fas fa-info"></i>{" "} <span>{this.props.description}</span> </p> )} </h4> <h5> {this.props.tempMin && this.props.tempMax && ( <p> {" "} <i className="fas fa-sort"></i> Min/Max:{" "} <span onClick={this.handleClicked.bind(this)}> {this.calculateTemp( this.props.tempMin, this.props.displayUnits )} &deg;{this.props.displayUnits} | {this.calculateTemp( this.props.tempMax, this.props.displayUnits )} &deg; {this.props.displayUnits} </span> </p> )} </h5> </div> <div className="col-md-6"> <h5> {this.props.humidity && ( <p> {" "} <i className="fas fa-water"></i> Humidity:{" "} <span>{this.props.humidity}%</span> </p> )} </h5> <h5> {this.props.pressure && ( <p> {" "} <i className="fas fa-tachometer-alt"></i> Pressure:{" "} <span>{this.props.pressure} hPa</span> </p> )} </h5> </div> </div> <h4> {this.props.error && ( <p> {" "} <i></i> <span>{this.props.error}</span> </p> )} </h4> </div> </div> ); } } export default Weather;
27.466667
78
0.37318
fcf7d633c8d4de8827f00b72865423449a88519a
531
js
JavaScript
packages/romanus-aux/src/validators.js
vladamon/romanus-numerus
86e694c440e95e3b00d08b901b776c81c46806d1
[ "MIT" ]
null
null
null
packages/romanus-aux/src/validators.js
vladamon/romanus-numerus
86e694c440e95e3b00d08b901b776c81c46806d1
[ "MIT" ]
null
null
null
packages/romanus-aux/src/validators.js
vladamon/romanus-numerus
86e694c440e95e3b00d08b901b776c81c46806d1
[ "MIT" ]
null
null
null
// source - https://www.oreilly.com/library/view/regular-expressions-cookbook/9780596802837/ch06s09.html export const romanNumberRegex = /^(?=[MDCLXVI])(M{0,3})(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$/ export const integerNumberRegex = /^[1-9]\d*$/ export const isValidInt = (intNumber) => { return integerNumberRegex.test(intNumber) } export const isValidRoman = (romanNumber) => { return romanNumberRegex.test(romanNumber) } export const isValidInput = (arg) => { return isValidInt(arg) || isValidRoman(arg) }
31.235294
105
0.702448
fcf813545c70d3bd583fa5d3211713305703ab0e
538
js
JavaScript
packages/bpk-svgs/dist/js/icons/sm/account-circle.js
tomcorke/backpack
f40d5b57671e211f8dc2098c18e35089880f81b2
[ "Apache-2.0" ]
null
null
null
packages/bpk-svgs/dist/js/icons/sm/account-circle.js
tomcorke/backpack
f40d5b57671e211f8dc2098c18e35089880f81b2
[ "Apache-2.0" ]
null
null
null
packages/bpk-svgs/dist/js/icons/sm/account-circle.js
tomcorke/backpack
f40d5b57671e211f8dc2098c18e35089880f81b2
[ "Apache-2.0" ]
null
null
null
import React from "react"; export default class SVG extends React.Component { render() { return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" style={{ width: "1.125rem", height: "1.125rem" }} {...this.props}><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm0 3c1.7 0 3 1.3 3 3s-1.3 3-3 3-3-1.3-3-3 1.4-3 3-3zm0 15c-2.4 0-4.7-1.1-6.2-3 .6-1.2 1.5-2.3 2.7-3.1.8-.6 1.7-.9 2.7-.9h1.6c1 0 1.9.3 2.7.9 1.2.8 2.1 1.9 2.7 3.1-1.4 1.9-3.7 3-6.2 3z" /></svg>; } }
53.8
287
0.581784
fcf8525e841cc808421cf09d9e2cbed552d68ff1
5,561
js
JavaScript
js/entities/entities.js
wangTheTiger/fog_test
a362db1755b193467587e366c111602c774e2e00
[ "MIT" ]
null
null
null
js/entities/entities.js
wangTheTiger/fog_test
a362db1755b193467587e366c111602c774e2e00
[ "MIT" ]
null
null
null
js/entities/entities.js
wangTheTiger/fog_test
a362db1755b193467587e366c111602c774e2e00
[ "MIT" ]
null
null
null
/** * Player Entity */ game.PlayerEntity = me.Entity.extend({ /** * constructor */ init:function (x, y, settings) { // call the constructor this._super(me.Entity, 'init', [x, y , settings]); // set the default horizontal & vertical speed (accel vector) this.body.setVelocity(3, 3); // set the display to follow our position on both axis me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); // set the entity body collision type this.body.collisionType=me.collision.types.PLAYER_OBJECT; //Player will collide with all the objects *filter level all_object* this.body.setCollisionMask(me.collision.types.ALL_OBJECT ); // ensure the player is updated even when outside of the viewport this.alwaysUpdate = true; // define a basic walking animation (using all frames) this.renderable.addAnimation("walk", [0, 1, 2, 3, 4, 5]); // define a standing animation (using the first frame) this.renderable.addAnimation("stand", [0]); // set the standing animation as default this.renderable.setCurrentAnimation("stand"); this.vulnerable=true; this.doingDamage=false; // disable gravity this.gravity = 0; this.facingTop=true; }, /** * update the entity */ update : function (dt) { this.doingDamage=false; this.isMovingX=false; this.isMovingY=false; if (me.input.isKeyPressed('left')) { if(this.renderable.angle!=0){ this.renderable.flipX(true); }else{ if(this.facingTop){ this.renderable.angle=1.57079633; this.renderable.flipX(false); }else{ this.renderable.angle=1.57079633;//90 Degrees to radians this.renderable.flipX(true); } } // update the entity velocity this.body.vel.x -= this.body.accel.x * me.timer.tick; // change to the walking animation if (!this.renderable.isCurrentAnimation("walk")) { this.renderable.setCurrentAnimation("walk"); } this.isMovingX=true; } else if (me.input.isKeyPressed('right')) { if(this.renderable.angle!=0){ this.renderable.flipX(false); }else{ if(this.facingTop){ this.renderable.angle=1.57079633; this.renderable.flipX(true); }else{ this.renderable.angle=1.57079633; this.renderable.flipX(false); } } // update the entity velocity this.body.vel.x += this.body.accel.x * me.timer.tick; // change to the walking animation if (!this.renderable.isCurrentAnimation("walk")) { this.renderable.setCurrentAnimation("walk"); } this.isMovingX=true; } else if (me.input.isKeyPressed('up')) { if(this.renderable.angle != 0){ this.renderable.angle=0; } this.renderable.flipY(false); this.facingTop=true; // update the entity velocity this.body.vel.y = -this.body.accel.y * me.timer.tick; // change to the walking animation if (!this.renderable.isCurrentAnimation("walk")) { this.renderable.setCurrentAnimation("walk"); } this.isMovingY=true; this.facingTop=true; }else if (me.input.isKeyPressed('down')) { if(this.renderable.angle != 0){ this.renderable.angle=0; } this.renderable.flipY(true); this.facingTop=false; // update the entity velocity this.body.vel.y = this.body.accel.y * me.timer.tick; // change to the walking animation if (!this.renderable.isCurrentAnimation("walk")) { this.renderable.setCurrentAnimation("walk"); } this.isMovingY=true; this.facingTop=false; } if(!this.isMovingX) { this.body.vel.x = 0; } if(!this.isMovingY){ this.body.vel.y = 0; } if(!this.isMovingX && !this.isMovingY){ // change to the standing animation this.renderable.setCurrentAnimation("stand"); } // apply physics to the body (this moves the entity) this.body.update(dt); // handle collisions against other shapes me.collision.check(this); //This method invokes as callback "this.onCollision" when a collision is found // return true if we moved or if the renderable was updated return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0); }, /** * colision handler * (called when colliding with other objects) * If the LightEntity exists on the room, it moves it along the player. */ onCollision : function (response, other) { var collision=false; switch (response.b.body.collisionType) { case me.collision.types.ACTION_OBJECT: break; case me.collision.types.WORLD_SHAPE: break; case me.collision.types.ENEMY_OBJECT: return true; //react to the collision break; default: // Do not respond to other objects (e.g. coins) return false; } // Make the object solid return true; } }); game.FogEntity = me.ImageLayer.extend({ init: function(name, width, height, image, z, ratio){ name = "fog"; width = 640; height = 480; image = "data/img/sprite/fog.png"; alpha = 0.9; z = 1; ratio = 0.2; //this.parent(name, width, height, image, z, ratio); this._super(me.ImageLayer, 'init', [name, width, height, image, z, ratio]); }, update: function(vpos) { this._super(me.ImageLayer, "update", [ vpos ]); this.pos.x = this.pos.x + this.ratio.x; //return true is absolutely required to redraw on each frame. return true; } });
27.805
107
0.630282
fcf8b3b075591195f9985a2b2471a9539a4c6768
97
js
JavaScript
distribution/FIXLIB/reference/type-search-index.js
ericfickes/FIXLIB
b316925eefc641bf231f4369a6a5fd88d85bb54c
[ "Apache-2.0" ]
1
2020-12-25T07:49:10.000Z
2020-12-25T07:49:10.000Z
distribution/FIXLIB/reference/type-search-index.js
ericfickes/FIXLIB
b316925eefc641bf231f4369a6a5fd88d85bb54c
[ "Apache-2.0" ]
null
null
null
distribution/FIXLIB/reference/type-search-index.js
ericfickes/FIXLIB
b316925eefc641bf231f4369a6a5fd88d85bb54c
[ "Apache-2.0" ]
null
null
null
typeSearchIndex = [{"l":"All Classes","url":"allclasses-index.html"},{"p":"fixlib","l":"Fixlib"}]
97
97
0.639175
fcf8e3dd5f565b5786ab910562aa1f6b338d4b48
6,130
js
JavaScript
public/scripts/loadTodos.js
AlulaLeak/todo-ai
adc0dac5c88ae8476449c94d1100cf8aa2cbcd3b
[ "MIT", "PostgreSQL", "Unlicense" ]
null
null
null
public/scripts/loadTodos.js
AlulaLeak/todo-ai
adc0dac5c88ae8476449c94d1100cf8aa2cbcd3b
[ "MIT", "PostgreSQL", "Unlicense" ]
null
null
null
public/scripts/loadTodos.js
AlulaLeak/todo-ai
adc0dac5c88ae8476449c94d1100cf8aa2cbcd3b
[ "MIT", "PostgreSQL", "Unlicense" ]
null
null
null
$(function () { $.ajax({ url: `/api/todos/all`, type: "GET", success: function (memoRows) { console.log("These are the memoRows", memoRows); function createMemoElement(todo) { return ` <ul class="list-group list-group-horizontal rounded-0 bg-transparent"> <li class="list-group-item d-flex align-items-center ps-0 pe-3 py-1 rounded-0 border-0 bg-transparent"> <div class="form-check"> <input class="form-check-input me-0" type="checkbox" value="" id="flexCheckChecked1" aria-label="..." checked /> </div> </li> <li class="list-group-item px-3 py-1 d-flex align-items-center flex-grow-1 border-0 bg-transparent"> <p class="lead fw-normal mb-0">${todo.memo}</p> </li> <li class="list-group-item ps-3 pe-0 py-1 rounded-0 border-0 bg-transparent"> <div class="d-flex flex-row justify-content-end mb-1"> <a href="#!" class="text-info" data-mdb-toggle="tooltip" title="Edit todo"><i class="fas fa-pencil-alt me-3"></i></a> <a href="#!" class="text-danger" data-mdb-toggle="tooltip" title="Delete todo"><i class="fas fa-trash-alt"></i></a> </div> <div class="text-end text-muted"> <a href="#!" class="text-muted" data-mdb-toggle="tooltip" title="Created date"> <p class="small mb-0"><i class="fas fa-info-circle me-2"></i>${todo.timestamp}</p></a> </div> </li> </ul> `; } let memoList = []; for (const memoSet of memoRows) { memoList.push(createMemoElement(memoSet)); } memoList = memoList.reverse().join("\n"); $("#todo-list").empty().append(memoList); // console.log(e) }, error: function (xhr, exception) { var msg = ""; if (xhr.status === 0) { msg = "Not connect.\n Verify Network." + xhr.responseText; } else if (xhr.status == 404) { msg = "Requested page not found. [404]" + xhr.responseText; } else if (xhr.status == 500) { msg = "Internal Server Error [500]." + xhr.responseText; } else if (exception === "parsererror") { msg = "Requested JSON parse failed."; } else if (exception === "timeout") { msg = "Time out error." + xhr.responseText; } else if (exception === "abort") { msg = "Ajax request aborted."; } else { msg = "Error:" + xhr.status + " " + xhr.responseText; } }, }); $(".submit-type").submit(function (e) { e.preventDefault(); console.log( "These are the e.currentTarget... from the submition:", e.currentTarget.attributes.value.nodeValue ); const endPoint = e.currentTarget.attributes.value.nodeValue; $.ajax({ url: `/api/todos/${endPoint}`, type: "GET", success: function (memoRows) { console.log("These are the memoRows in the ajax rewuest: ", memoRows); function createMemoElement(todo) { return ` <ul class="list-group list-group-horizontal rounded-0 bg-transparent"> <li class="list-group-item d-flex align-items-center ps-0 pe-3 py-1 rounded-0 border-0 bg-transparent"> <div class="form-check"> <input class="form-check-input me-0" type="checkbox" value="" id="flexCheckChecked1" aria-label="..." checked /> </div> </li> <li class="list-group-item px-3 py-1 d-flex align-items-center flex-grow-1 border-0 bg-transparent"> <p class="lead fw-normal mb-0">${todo.memo}</p> </li> <li class="list-group-item ps-3 pe-0 py-1 rounded-0 border-0 bg-transparent"> <div class="d-flex flex-row justify-content-end mb-1"> <a href="#!" class="text-info" data-mdb-toggle="tooltip" title="Edit todo"><i class="fas fa-pencil-alt me-3"></i></a> <a href="#!" class="text-danger" data-mdb-toggle="tooltip" title="Delete todo"><i class="fas fa-trash-alt"></i></a> </div> <div class="text-end text-muted"> <a href="#!" class="text-muted" data-mdb-toggle="tooltip" title="Created date"> <p class="small mb-0"><i class="fas fa-info-circle me-2"></i>${todo.timestamp}</p></a> </div> </li> </ul> `; } let memoList = []; for (const memoSet of memoRows) { memoList.push(createMemoElement(memoSet)); } memoList = memoList.join("\n"); $("#todo-list").empty().append(memoList).stop(); $("body").on("DOMNodeInserted", "table", function () { $("td:visible").translate("es", "en"); }); }, error: function (xhr, exception) { var msg = ""; if (xhr.status === 0) { msg = "Not connect.\n Verify Network." + xhr.responseText; } else if (xhr.status == 404) { msg = "Requested page not found. [404]" + xhr.responseText; } else if (xhr.status == 500) { msg = "Internal Server Error [500]." + xhr.responseText; } else if (exception === "parsererror") { msg = "Requested JSON parse failed."; } else if (exception === "timeout") { msg = "Time out error." + xhr.responseText; } else if (exception === "abort") { msg = "Ajax request aborted."; } else { msg = "Error:" + xhr.status + " " + xhr.responseText; } }, }); }); });
40.866667
139
0.490538
fcf93d93b820cea6d3d6148281813529e4f3d4cc
151
js
JavaScript
cypress/integration/mainPage.js
gmalewicz/golf-web
e4db12ee81addfe668c21fe0ec1fe496f306fca2
[ "MIT" ]
null
null
null
cypress/integration/mainPage.js
gmalewicz/golf-web
e4db12ee81addfe668c21fe0ec1fe496f306fca2
[ "MIT" ]
92
2021-01-17T09:33:18.000Z
2022-03-26T18:47:48.000Z
cypress/integration/mainPage.js
gmalewicz/golf-web
e4db12ee81addfe668c21fe0ec1fe496f306fca2
[ "MIT" ]
null
null
null
describe('Main page', () => { it('should display the main page', () => { cy.visit('http://localhost:4200/'); cy.contains('DGNG'); }) })
15.1
44
0.529801
fcf974ec72196dc4f2c40c757bb2ef06c8585efd
445
js
JavaScript
Java/Java-CachingSamples/AirportSample/WebContent/dojo/dojo/cldr/nls/az/currency.js
myhong0/sk-bmx-sample
c36886c9e2189030840c855b89e71d484089b968
[ "MIT" ]
null
null
null
Java/Java-CachingSamples/AirportSample/WebContent/dojo/dojo/cldr/nls/az/currency.js
myhong0/sk-bmx-sample
c36886c9e2189030840c855b89e71d484089b968
[ "MIT" ]
null
null
null
Java/Java-CachingSamples/AirportSample/WebContent/dojo/dojo/cldr/nls/az/currency.js
myhong0/sk-bmx-sample
c36886c9e2189030840c855b89e71d484089b968
[ "MIT" ]
3
2019-03-27T14:35:48.000Z
2020-06-30T22:45:08.000Z
//>>built define( "dojo/cldr/nls/az/currency", //begin v1.x content { "HKD_displayName": "Honk Konq dolları", "CHF_displayName": "İsveçriya frankası", "CAD_displayName": "Kanadiya dolları", "CNY_displayName": "Çin yuan renminbi", "AUD_displayName": "Avstraliya dolları", "JPY_displayName": "Yapon yeni", "USD_displayName": "ABŞ dolları", "GBP_displayName": "Britaniya paund sterlingi", "EUR_displayName": "Yevro" } //end v1.x content );
27.8125
49
0.721348
fcfaaa81753f1b174925f62c4017096e5645aac1
2,481
js
JavaScript
sketch22.js
asteriskman7/dakrtober2021
1ceb5ba79adb1ca0e1b85f78f67e7e95e43eeaca
[ "MIT" ]
1
2021-11-10T18:32:50.000Z
2021-11-10T18:32:50.000Z
sketch22.js
asteriskman7/darktober2021
1ceb5ba79adb1ca0e1b85f78f67e7e95e43eeaca
[ "MIT" ]
null
null
null
sketch22.js
asteriskman7/darktober2021
1ceb5ba79adb1ca0e1b85f78f67e7e95e43eeaca
[ "MIT" ]
null
null
null
'use strict'; class Sketch22 extends Sketch { constructor() { super(); this.scale = 1; this.width = Math.floor(this.canvas.width / this.scale); this.height = this.width; } load() { super.load(); } update() { } //from https://gist.github.com/vahidk/05184faf3d92a0aa1b46aeaa93b07786 //modified to expect s & l from 0 to 100 instead of 0 to 1 and accept h > 360 hslToRgb(h, s, l) { s /= 100; l /= 100; h %= 360; let c = (1 - Math.abs(2 * l - 1)) * s; let hp = h / 60.0; let x = c * (1 - Math.abs((hp % 2) - 1)); let rgb1; if (isNaN(h)) rgb1 = [0, 0, 0]; else if (hp <= 1) rgb1 = [c, x, 0]; else if (hp <= 2) rgb1 = [x, c, 0]; else if (hp <= 3) rgb1 = [0, c, x]; else if (hp <= 4) rgb1 = [0, x, c]; else if (hp <= 5) rgb1 = [x, 0, c]; else if (hp <= 6) rgb1 = [c, 0, x]; let m = l - c * 0.5; return { r: Math.round(255 * (rgb1[0] + m)), g: Math.round(255 * (rgb1[1] + m)), b: Math.round(255 * (rgb1[2] + m)) }; } draw(ctx, width, height, t, mousePoint) { ctx.fillStyle = `hsl(214, 60%, 27%)`; ctx.fillRect(0, 0, width, height); ctx.translate(width / 2 , height / 2); const img = ctx.getImageData(0, 0, width, height); const data = img.data; for (let x = 0; x < width; x++) { const u = x / width; for (let y = 0; y < height; y++) { const v = y / height; const i = (x + y * width) * 4; const d1 = Math.sqrt((u - 0.25) * (u - 0.25) + (v - 0.25) * (v - 0.25)); const d2 = Math.sqrt((u - 0.75) * (u - 0.75) + (v - 0.25) * (v - 0.25)); const p1 = {x: 0.25, y: 0.75}; const p2 = {x: 0.75, y: 0.75}; const d3 = (Math.abs( (p2.x - p1.x) * (p1.y - v) - (p1.x - u) * (p2.y - p1.y) )) / (Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y))); const d = Math.min(d3, Math.min(d1, d2)); const h = (this.lmap(Math.sin(t * 0.1), 1, -1, 30, 2055)) * d * 360; const s = 100 * (x ^ y) / 128; const l = ( d * 3) * 100; const rgb = this.hslToRgb(h, s, l); data[i + 0] = rgb.r; data[i + 1] = rgb.g; data[i + 2] = rgb.b; } } ctx.putImageData(img, 0, 0); } } app.sketches[22] = new Sketch22(); app.sketches[22].desc = `This mask has no point.`;
27.566667
86
0.446594
fcfac85e78127ea8d4926829f743c21eea10440a
378
js
JavaScript
src/components/GuestGuard.js
getsproud/react-app
893e7526380836a3b9f5f638a006c69e9fea87d2
[ "MIT" ]
null
null
null
src/components/GuestGuard.js
getsproud/react-app
893e7526380836a3b9f5f638a006c69e9fea87d2
[ "MIT" ]
null
null
null
src/components/GuestGuard.js
getsproud/react-app
893e7526380836a3b9f5f638a006c69e9fea87d2
[ "MIT" ]
null
null
null
import { Navigate } from 'react-router-dom'; import PropTypes from 'prop-types'; import useAuth from '../hooks/useAuth'; const GuestGuard = ({ children }) => { const { isAuthenticated } = useAuth(); if (isAuthenticated) { return <Navigate to="/" />; } return <>{children}</>; }; GuestGuard.propTypes = { children: PropTypes.node }; export default GuestGuard;
18.9
44
0.65873
fcfb5761013acf567ff2c6cb8f735744bdf9f076
200
js
JavaScript
docs/generated/docs/search/files_7.js
JohnySeven/SensESP
6ba911158c02f613b324c0d803b251faca95aff7
[ "Apache-2.0" ]
null
null
null
docs/generated/docs/search/files_7.js
JohnySeven/SensESP
6ba911158c02f613b324c0d803b251faca95aff7
[ "Apache-2.0" ]
2
2021-03-15T05:35:32.000Z
2021-03-27T02:36:16.000Z
docs/generated/docs/search/files_7.js
JohnySeven/SensESP
6ba911158c02f613b324c0d803b251faca95aff7
[ "Apache-2.0" ]
2
2021-03-14T14:36:50.000Z
2021-03-15T03:41:46.000Z
var searchData= [ ['http_2ecpp',['http.cpp',['../http_8cpp.html',1,'']]], ['http_2eh',['http.h',['../http_8h.html',1,'']]], ['hysteresis_2eh',['hysteresis.h',['../hysteresis_8h.html',1,'']]] ];
28.571429
68
0.56
fcfb8852fdd3df1b7e8204c628bcd31314caea6d
3,885
js
JavaScript
lib/recorder.js
flyskywhy/CodeceptJS
a6aa9bba3d501caa9ffb5b0b95e57265faa4d4c2
[ "MIT" ]
3
2018-12-14T23:57:47.000Z
2019-05-30T08:11:17.000Z
lib/recorder.js
rlewan/CodeceptJS
17d12e21edfc56ef80c7f9d3082cb421da94cdb3
[ "MIT" ]
null
null
null
lib/recorder.js
rlewan/CodeceptJS
17d12e21edfc56ef80c7f9d3082cb421da94cdb3
[ "MIT" ]
1
2018-12-14T23:57:57.000Z
2018-12-14T23:57:57.000Z
'use strict'; let promise; let running = false; let errFn; let next; let queueId = 0; let sessionId = null; let log = require('./output').log; let tasks = []; let oldPromises = []; /** * Singleton object to record all test steps as promises and run them in chain. */ module.exports = { /** * Start recording promises * * @api */ start() { running = true; errFn = null; this.reset(); }, isRunning() { return running; }, startUnlessRunning() { if (!this.isRunning()) { this.start(); } }, /** * Add error handler to catch rejected promises * * @api * @param {*} fn */ errHandler(fn) { errFn = fn; }, /** * Stops current promise chain, calls `catch`. * Resets recorder to initial state. * * @api */ reset() { if (promise && running) this.catch(); queueId++; sessionId = null; log(currentQueue() + `Starting recording promises`); promise = Promise.resolve(); oldPromises = []; tasks = []; this.session.running = false; }, session: { running: false, start(name) { log(currentQueue() + `Starting <${name}> session`); tasks.push('--->'); oldPromises.push(promise); this.running = true; sessionId = name; promise = Promise.resolve(); }, restore(name) { tasks.push('<---'); log(currentQueue() + `Finalize <${name}> session`); this.running = false; sessionId = null; promise = promise.then(() => oldPromises.pop()); }, catch(errFn) { promise = promise.catch(errFn); } }, /** * Adds a promise to a chain. * Promise description should be passed as first parameter. * * @param {*} taskName * @param {*} fn * @param {*} force */ add(taskName, fn = undefined, force = false) { if (typeof taskName === "function") { fn = taskName; taskName = fn.toString(); } if (!running && !force) { return; } tasks.push(taskName); log(currentQueue() + `Queued | ${taskName}`); // ensure a valid promise is always in chain return promise = Promise.resolve(promise).then(fn); }, catch(customErrFn) { return promise = promise.catch((err) => { log(currentQueue() + `Error | ${err}`); if (!(err instanceof Error)) { // strange things may happen err = new Error('[Wrapped Error] ' + JSON.stringify(err)); // we should be prepared for them } if (customErrFn) { customErrFn(err); } else if (errFn) { errFn(err); } this.stop(); }); }, catchWithoutStop(customErrFn) { return promise = promise.catch((err) => { log(currentQueue() + `Error | ${err}`); if (!(err instanceof Error)) { // strange things may happen err = new Error('[Wrapped Error] ' + JSON.stringify(err)); // we should be prepared for them } if (customErrFn) { customErrFn(err); } else if (errFn) { errFn(err); } }); }, /** * Adds a promise which throws an error into a chain * * @api * @param {*} err */ throw(err) { return this.add('throw error ' + err, function () { throw err; }); }, /** * Stops recording promises * @api */ stop() { log(currentQueue() + `Stopping recording promises`); var err = new Error(); running = false; }, /** * Get latest promise in chain. * * @api */ promise() { return promise; }, /** * Get a list of all chained tasks */ scheduled() { return tasks.join("\n"); }, /** * Get a state of current queue and tasks */ toString() { return `Queue: ${currentQueue()}\n\nTasks: ${this.scheduled()}`; } }; function currentQueue() { let session = ''; if (sessionId) session = `<${sessionId}> `; return `[${queueId}] ${session}`; }
19.720812
100
0.545946
fcfbdb19036b4a6b3eaaba25528dd32f5f0cde00
120,661
js
JavaScript
dist/components/MdDatepicker/index.js
olsn/vue-material
62bc3e528a60610659716cc5fdab71deac862301
[ "MIT" ]
null
null
null
dist/components/MdDatepicker/index.js
olsn/vue-material
62bc3e528a60610659716cc5fdab71deac862301
[ "MIT" ]
null
null
null
dist/components/MdDatepicker/index.js
olsn/vue-material
62bc3e528a60610659716cc5fdab71deac862301
[ "MIT" ]
null
null
null
/*! * vue-material v1.0.0-beta-11 * Made with <3 by marcosmoura 2020 * Released under the MIT License. */ !(function(t,e){var n,r;if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("vue"));else if("function"==typeof define&&define.amd)define(["vue"],e);else{n=e("object"==typeof exports?require("vue"):t.Vue);for(r in n)("object"==typeof exports?exports:t)[r]=n[r]}})("undefined"!=typeof self?self:this,(function(t){return (function(t){function e(r){if(n[r])return n[r].exports;var a=n[r]={i:r,l:!1,exports:{}};return t[r].call(a.exports,a,a.exports,e),a.l=!0,a.exports}var n={};return e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=527)})({0:function(t,e){t.exports=function(t,e,n,r,a,i){var o,s,u,c,l,d=t=t||{},f=typeof t.default;return"object"!==f&&"function"!==f||(o=t,d=t.default),s="function"==typeof d?d.options:d,e&&(s.render=e.render,s.staticRenderFns=e.staticRenderFns,s._compiled=!0),n&&(s.functional=!0),a&&(s._scopeId=a),i?(u=function(t){t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,t||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(i)},s._ssrRegister=u):r&&(u=r),u&&(c=s.functional,l=c?s.render:s.beforeCreate,c?(s._injectStyles=u,s.render=function(t,e){return u.call(e),l(t,e)}):s.beforeCreate=l?[].concat(l,u):[u]),{esModule:o,exports:d,options:s}}},1:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s;Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){var e={props:{mdTheme:null},computed:{$mdActiveTheme:function(){var t=i.default.enabled,e=i.default.getThemeName,n=i.default.getAncestorTheme;return t&&!1!==this.mdTheme?e(this.mdTheme||n(this)):null}}};return(0,s.default)(e,t)},a=n(4),i=r(a),o=n(6),s=r(o)},10:function(t,e,n){"use strict";function r(t){Object(a.a)(1,arguments);var e=Object.prototype.toString.call(t);return t instanceof Date||"object"==typeof t&&"[object Date]"===e?new Date(t.getTime()):"number"==typeof t||"[object Number]"===e?new Date(t):("string"!=typeof t&&"[object String]"!==e||"undefined"==typeof console||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as arguments. Please use `parseISO` to parse strings. See: https://git.io/fjule"),console.warn(Error().stack)),new Date(NaN))}e.a=r;var a=n(8)},11:function(t,e,n){(function(e){var r,a,i,o,s,u=n(15),c="undefined"==typeof window?e:window,l=["moz","webkit"],d="AnimationFrame",f=c["request"+d],h=c["cancel"+d]||c["cancelRequest"+d];for(r=0;!f&&r<l.length;r++)f=c[l[r]+"Request"+d],h=c[l[r]+"Cancel"+d]||c[l[r]+"CancelRequest"+d];f&&h||(a=0,i=0,o=[],s=1e3/60,f=function(t){if(0===o.length){var e=u(),n=Math.max(0,s-(e-a));a=n+e,setTimeout((function(){var t,e=o.slice(0);for(o.length=0,t=0;t<e.length;t++)if(!e[t].cancelled)try{e[t].callback(a)}catch(t){setTimeout((function(){throw t}),0)}}),Math.round(n))}return o.push({handle:++i,callback:t,cancelled:!1}),i},h=function(t){for(var e=0;e<o.length;e++)o[e].handle===t&&(o[e].cancelled=!0)}),t.exports=function(t){return f.call(c,t)},t.exports.cancel=function(){h.apply(c,arguments)},t.exports.polyfill=function(t){t||(t=c),t.requestAnimationFrame=f,t.cancelAnimationFrame=h}}).call(e,n(13))},12:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){return Math.random().toString(36).slice(4)};e.default=r},13:function(t,e){var n;n=(function(){return this})();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},14:function(t,e,n){"use strict";function r(t){n(34)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(21),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(38),u=n(0),c=!1,l=r,d=null,f=null,h=u(i.a,s.a,c,l,d,f),e.default=h.exports},142:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s,u,c,l,d,f,h,m,p,g,v,b,w,y,M,T,D,O,x,C,_,k,j;Object.defineProperty(e,"__esModule",{value:!0}),a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=Object.assign||function(t){var e,n,r;for(e=1;e<arguments.length;e++){n=arguments[e];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},o=n(2),s=r(o),u=n(329),c=r(u),l=n(330),d=r(l),f=n(331),h=r(f),m=n(143),p=r(m),g=n(9),v=r(g),b=n(59),w=r(b),y=n(332),M=r(y),T=n(350),D=r(T),O=n(352),x=r(O),C=n(63),_=r(C),k=n(54),j=r(k),e.default={name:"MdDatepicker",components:{MdOverlay:w.default,MdDateIcon:D.default,MdField:_.default,MdInput:j.default,MdDatepickerDialog:M.default},props:{value:[String,Number,Date],mdDisabledDates:[Array,Function],mdOpenOnFocus:{type:Boolean,default:!0},mdOverrideNative:{type:Boolean,default:!0},mdImmediately:{type:Boolean,default:!1},mdModelType:i({type:Function,default:Date},(0,v.default)("md-model-type",[Date,String,Number])),MdDebounce:{type:Number,default:1e3}},data:function(){return{showDialog:!1,inputDate:"",localDate:null}},computed:{locale:function(){return this.$material.locale},type:function(){return this.mdOverrideNative?"text":"date"},dateFormat:function(){return this.locale.dateFormat||"yyyy-MM-dd"},modelType:function(){return this.isModelTypeString?String:this.isModelTypeNumber?Number:this.isModelTypeDate?Date:this.mdModelType},isModelNull:function(){return null===this.value||void 0===this.value},isModelTypeString:function(){return"string"==typeof this.value},isModelTypeNumber:function(){return Number.isInteger(this.value)&&this.value>=0},isModelTypeDate:function(){return"object"===a(this.value)&&this.value instanceof Date&&(0,p.default)(this.value)},localString:function(){return this.localDate&&(0,d.default)(this.localDate,this.dateFormat)},localNumber:function(){return this.localDate&&+this.localDate},parsedInputDate:function(){var t=(0,h.default)(this.inputDate,this.dateFormat,new Date);return t&&(0,p.default)(t)?t:null},pattern:function(){return this.dateFormat.replace(/yyyy|MM|dd/g,(function(t){switch(t){case"yyyy":return"[0-9]{4}";case"MM":case"dd":return"[0-9]{2}"}}))}},watch:{inputDate:function(t){this.inputDateToLocalDate()},localDate:function(){this.inputDate=this.localString,this.modelType===Date&&this.$emit("input",this.localDate)},localString:function(){this.modelType===String&&this.$emit("input",this.localString)},localNumber:function(){this.modelType===Number&&this.$emit("input",this.localNumber)},value:{immediate:!0,handler:function(){this.valueDateToLocalDate()}},mdModelType:function(t){switch(t){case Date:this.$emit("input",this.localDate);break;case String:this.$emit("input",this.localString);break;case Number:this.$emit("input",this.localNumber)}},dateFormat:function(){this.localDate&&(this.inputDate=(0,d.default)(this.localDate,this.dateFormat))}},methods:{toggleDialog:function(){!c.default||this.mdOverrideNative?(this.showDialog=!this.showDialog,this.showDialog?this.$emit("md-opened"):this.$emit("md-closed")):this.$refs.input.$el.click()},onFocus:function(){this.mdOpenOnFocus&&this.toggleDialog()},inputDateToLocalDate:function(){this.inputDate?this.parsedInputDate&&(this.localDate=this.parsedInputDate):this.localDate=null},valueDateToLocalDate:function(){if(this.isModelNull)this.localDate=null;else if(this.isModelTypeNumber)this.localDate=new Date(this.value);else if(this.isModelTypeDate)this.localDate=this.value;else if(this.isModelTypeString){var t=(0,h.default)(this.value,this.dateFormat,new Date);(0,p.default)(t)?this.localDate=(0,h.default)(this.value,this.dateFormat,new Date):s.default.util.warn("The datepicker value is not a valid date. Given value: "+this.value+", format: "+this.dateFormat)}else s.default.util.warn("The datepicker value is not a valid date. Given value: "+this.value)}},created:function(){this.inputDateToLocalDate=(0,x.default)(this.inputDateToLocalDate,this.MdDebounce)}}},143:function(t,e,n){"use strict";function r(t){Object(i.a)(1,arguments);var e=Object(a.a)(t);return!isNaN(e)}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)},144:function(t,e,n){"use strict";function r(t,e,n){n=n||{};var r;return r="string"==typeof d[t]?d[t]:1===e?d[t].one:d[t].other.replace("{{count}}",e),n.addSuffix?n.comparison>0?"in "+r:r+" ago":r}function a(t){return function(e){var n=e||{},r=n.width?n.width+"":t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}function i(t,e,n,r){return v[t]}function o(t){return function(e,n){var r,a,i,o,s,u,c=n||{};return"formatting"==(c.context?c.context+"":"standalone")&&t.formattingValues?(a=t.defaultFormattingWidth||t.defaultWidth,i=c.width?c.width+"":a,r=t.formattingValues[i]||t.formattingValues[a]):(o=t.defaultWidth,s=c.width?c.width+"":t.defaultWidth,r=t.values[s]||t.values[o]),u=t.argumentCallback?t.argumentCallback(e):e,r[u]}}function s(t,e){var n=+t,r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"}function u(t){return function(e,n){var r,a,i,o=e+"",s=n||{},u=s.width,d=u&&t.matchPatterns[u]||t.matchPatterns[t.defaultMatchWidth],f=o.match(d);return f?(r=f[0],a=u&&t.parsePatterns[u]||t.parsePatterns[t.defaultParseWidth],i="[object Array]"===Object.prototype.toString.call(a)?l(a,(function(t){return t.test(o)})):c(a,(function(t){return t.test(o)})),i=t.valueCallback?t.valueCallback(i):i,i=s.valueCallback?s.valueCallback(i):i,{value:i,rest:o.slice(r.length)}):null}}function c(t,e){for(var n in t)if(t.hasOwnProperty(n)&&e(t[n]))return n}function l(t,e){for(var n=0;n<t.length;n++)if(e(t[n]))return n}var d={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},f={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},h={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},m={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},p={date:a({formats:f,defaultWidth:"full"}),time:a({formats:h,defaultWidth:"full"}),dateTime:a({formats:m,defaultWidth:"full"})},g=p,v={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},b={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},w={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},y={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},M={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},T={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},D={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},O={ordinalNumber:s,era:o({values:b,defaultWidth:"wide"}),quarter:o({values:w,defaultWidth:"wide",argumentCallback:function(t){return+t-1}}),month:o({values:y,defaultWidth:"wide"}),day:o({values:M,defaultWidth:"wide"}),dayPeriod:o({values:T,defaultWidth:"wide",formattingValues:D,defaultFormattingWidth:"wide"})},x=O,C=/^(\d+)(th|st|nd|rd)?/i,_=/\d+/i,k={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},j={any:[/^b/i,/^(a|c)/i]},P={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},E={any:[/1/i,/2/i,/3/i,/4/i]},S={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},F={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},N={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},U={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},L={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},A={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},H={ordinalNumber:(function(t){return function(e,n){var r,a,i,o=e+"",s=n||{},u=o.match(t.matchPattern);return u?(r=u[0],(a=o.match(t.parsePattern))?(i=t.valueCallback?t.valueCallback(a[0]):a[0],i=s.valueCallback?s.valueCallback(i):i,{value:i,rest:o.slice(r.length)}):null):null}})({matchPattern:C,parsePattern:_,valueCallback:function(t){return parseInt(t,10)}}),era:u({matchPatterns:k,defaultMatchWidth:"wide",parsePatterns:j,defaultParseWidth:"any"}),quarter:u({matchPatterns:P,defaultMatchWidth:"wide",parsePatterns:E,defaultParseWidth:"any",valueCallback:function(t){return t+1}}),month:u({matchPatterns:S,defaultMatchWidth:"wide",parsePatterns:F,defaultParseWidth:"any"}),day:u({matchPatterns:N,defaultMatchWidth:"wide",parsePatterns:U,defaultParseWidth:"any"}),dayPeriod:u({matchPatterns:L,defaultMatchWidth:"any",parsePatterns:A,defaultParseWidth:"any"})},Y=H,q={code:"en-US",formatDistance:r,formatLong:g,formatRelative:i,localize:x,match:Y,options:{weekStartsOn:0,firstWeekContainsDate:1}};e.a=q},145:function(t,e,n){"use strict";function r(t,e){var n,r;return Object(s.a)(2,arguments),n=Object(o.a)(t).getTime(),r=Object(i.a)(e),new Date(n+r)}function a(t,e){return Object(s.a)(2,arguments),r(t,-Object(i.a)(e))}var i=n(18),o=n(10),s=n(8);e.a=a},146:function(t,e,n){"use strict";function r(t){var e,n;return Object(c.a)(1,arguments),e=Object(u.a)(t),n=new Date(0),n.setUTCFullYear(e,0,4),n.setUTCHours(0,0,0,0),Object(s.a)(n)}function a(t){var e,n;return Object(c.a)(1,arguments),e=Object(o.a)(t),n=Object(s.a)(e).getTime()-r(e).getTime(),Math.round(n/i)+1}var i,o=n(10),s=n(65),u=n(147),c=n(8);e.a=a,i=6048e5},147:function(t,e,n){"use strict";function r(t){var e,n,r,s,u,c;return Object(o.a)(1,arguments),e=Object(a.a)(t),n=e.getUTCFullYear(),r=new Date(0),r.setUTCFullYear(n+1,0,4),r.setUTCHours(0,0,0,0),s=Object(i.a)(r),u=new Date(0),u.setUTCFullYear(n,0,4),u.setUTCHours(0,0,0,0),c=Object(i.a)(u),e.getTime()>=s.getTime()?n+1:e.getTime()>=c.getTime()?n:n-1}var a,i,o;e.a=r,a=n(10),i=n(65),o=n(8)},148:function(t,e,n){"use strict";function r(t,e){var n,r,a,i,o,d,f;return Object(l.a)(1,arguments),n=e||{},r=n.locale,a=r&&r.options&&r.options.firstWeekContainsDate,i=null==a?1:Object(u.a)(a),o=null==n.firstWeekContainsDate?i:Object(u.a)(n.firstWeekContainsDate),d=Object(c.a)(t,e),f=new Date(0),f.setUTCFullYear(d,0,o),f.setUTCHours(0,0,0,0),Object(s.a)(f,e)}function a(t,e){var n,a;return Object(l.a)(1,arguments),n=Object(o.a)(t),a=Object(s.a)(n,e).getTime()-r(n,e).getTime(),Math.round(a/i)+1}var i,o=n(10),s=n(66),u=n(18),c=n(94),l=n(8);e.a=a,i=6048e5},149:function(t,e,n){"use strict";function r(t,e){switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}}function a(t,e){switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}}function i(t,e){var n,i=t.match(/(P+)(p+)?/),o=i[1],s=i[2];if(!s)return r(t,e);switch(o){case"P":n=e.dateTime({width:"short"});break;case"PP":n=e.dateTime({width:"medium"});break;case"PPP":n=e.dateTime({width:"long"});break;case"PPPP":default:n=e.dateTime({width:"full"})}return n.replace("{{date}}",r(o,e)).replace("{{time}}",a(s,e))}var o={p:a,P:i};e.a=o},15:function(t,e,n){(function(e){(function(){var n,r,a,i,o,s;"undefined"!=typeof performance&&null!==performance&&performance.now?t.exports=function(){return performance.now()}:void 0!==e&&null!==e&&e.hrtime?(t.exports=function(){return(n()-o)/1e6},r=e.hrtime,n=function(){var t;return t=r(),1e9*t[0]+t[1]},i=n(),s=1e9*e.uptime(),o=i-s):Date.now?(t.exports=function(){return Date.now()-a},a=Date.now()):(t.exports=function(){return(new Date).getTime()-a},a=(new Date).getTime())}).call(this)}).call(e,n(16))},150:function(t,e,n){"use strict";function r(t){var e,n=new Date(t.getTime()),r=Math.ceil(n.getTimezoneOffset());return n.setSeconds(0,0),e=n.getTime()%a,r*a+e}e.a=r;var a=6e4},151:function(t,e,n){"use strict";function r(t){return-1!==o.indexOf(t)}function a(t){return-1!==s.indexOf(t)}function i(t){if("YYYY"===t)throw new RangeError("Use `yyyy` instead of `YYYY` for formatting years; see: https://git.io/fxCyr");if("YY"===t)throw new RangeError("Use `yy` instead of `YY` for formatting years; see: https://git.io/fxCyr");if("D"===t)throw new RangeError("Use `d` instead of `D` for formatting days of the month; see: https://git.io/fxCyr");if("DD"===t)throw new RangeError("Use `dd` instead of `DD` for formatting days of the month; see: https://git.io/fxCyr")}var o,s;e.a=r,e.b=a,e.c=i,o=["D","DD"],s=["YY","YYYY"]},152:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s,u,c,l,d,f,h,m,p,g,v,b,w,y,M,T,D,O,x,C,_,k,j,P,E,S,F,N,U,L,A,H,Y,q,$;Object.defineProperty(e,"__esModule",{value:!0}),a=n(153),i=r(a),o=n(334),s=r(o),u=n(335),c=r(u),l=n(336),d=r(l),f=n(337),h=r(f),m=n(97),p=r(m),g=n(338),v=r(g),b=n(339),w=r(b),y=n(340),M=r(y),T=n(341),D=r(T),O=n(342),x=r(O),C=n(343),_=r(C),k=n(344),j=r(k),P=n(1),E=r(P),S=n(57),F=r(S),N=n(345),U=r(N),L=n(347),A=r(L),H=n(69),Y=r(H),q=7,$=function(t,e){return!(!t||!t.querySelector)&&t.querySelectorAll(e)},e.default=new E.default({name:"MdDatepickerDialog",components:{MdPopover:F.default,MdArrowRightIcon:U.default,MdArrowLeftIcon:A.default,MdDialog:Y.default},props:{mdDate:Date,mdDisabledDates:[Array,Function],mdImmediately:{type:Boolean,default:!1}},data:function(){return{currentDate:null,selectedDate:null,showDialog:!1,monthAction:null,currentView:"day",contentStyles:{},availableYears:null}},computed:{firstDayOfAWeek:function(){var t=+this.locale.firstDayOfAWeek;return Number.isNaN(t)||!Number.isFinite(t)?0:(t=Math.floor(t)%q,t+=t<0?q:0,t)},locale:function(){return this.$material.locale},popperSettings:function(){return{placement:"bottom-start",modifiers:{keepTogether:{enabled:!0},flip:{enabled:!1}}}},calendarClasses:function(){return"next"===this.monthAction?"md-next":"md-previous"},firstDayOfMonth:function(){return(0,s.default)(this.currentDate).getDay()},prefixEmptyDays:function(){var t=this.firstDayOfMonth-this.firstDayOfAWeek;return t+=t<0?q:0,t},daysInMonth:function(){return(0,p.default)(this.currentDate)},currentDay:function(){return this.selectedDate?(0,d.default)(this.selectedDate):(0,d.default)(this.currentDate)},currentMonth:function(){return(0,v.default)(this.currentDate)},currentMonthName:function(){return this.locale.months[this.currentMonth]},currentYear:function(){return(0,w.default)(this.currentDate)},selectedYear:function(){return this.selectedDate?(0,w.default)(this.selectedDate):(0,w.default)(this.currentDate)},shortDayName:function(){return this.selectedDate?this.locale.shortDays[(0,h.default)(this.selectedDate)]:this.locale.shortDays[(0,h.default)(this.currentDate)]},shortMonthName:function(){return this.selectedDate?this.locale.shortMonths[(0,v.default)(this.selectedDate)]:this.locale.shortMonths[(0,v.default)(this.currentDate)]}},watch:{mdDate:function(){this.currentDate=this.mdDate||new Date,this.selectedDate=this.mdDate},currentDate:function(t,e){var n=this;this.$nextTick().then((function(){e&&n.setContentStyles()}))},currentView:function(){var t=this;this.$nextTick().then((function(){if("year"===t.currentView){var e=$(t.$el,".md-datepicker-year-button.md-datepicker-selected");e.length&&e[0].scrollIntoView({behavior:"instant",block:"center",inline:"center"})}}))}},methods:{setContentStyles:function(){var t,e=$(this.$el,".md-datepicker-month");e.length&&(t=e[e.length-1],this.contentStyles={height:t.offsetHeight+10+"px"})},setAvailableYears:function(){for(var t=this.locale,e=t.startYear,n=t.endYear,r=e,a=[];r<=n;)a.push(r++);this.availableYears=a},handleDisabledDateByArray:function(t){return this.mdDisabledDates.some((function(e){return(0,D.default)(e,t)}))},isDisabled:function(t){if(this.mdDisabledDates){var e=(0,x.default)(this.currentDate,t);if(Array.isArray(this.mdDisabledDates))return this.handleDisabledDateByArray(e);if("function"==typeof this.mdDisabledDates)return this.mdDisabledDates(e)}},isSelectedDay:function(t){return(0,M.default)(this.selectedDate,(0,x.default)(this.currentDate,t))},isToday:function(t){return(0,D.default)(new Date,(0,x.default)(this.currentDate,t))},previousMonth:function(){this.monthAction="previous",this.currentDate=(0,c.default)(this.currentDate,1)},nextMonth:function(){this.monthAction="next",this.currentDate=(0,i.default)(this.currentDate,1)},switchMonth:function(t){this.currentDate=(0,_.default)(this.currentDate,t),this.currentView="day"},switchYear:function(t){this.currentDate=(0,j.default)(this.currentDate,t),this.currentView="month"},selectDate:function(t){this.currentDate=(0,x.default)(this.currentDate,t),this.selectedDate=this.currentDate,this.mdImmediately&&(this.$emit("update:mdDate",this.selectedDate),this.closeDialog())},closeDialog:function(){this.$emit("md-closed")},onClose:function(){this.closeDialog()},onCancel:function(){this.closeDialog()},onConfirm:function(){this.$emit("update:mdDate",this.selectedDate),this.closeDialog()},resetDate:function(){this.currentDate=this.mdDate||new Date,this.selectedDate=this.mdDate,this.currentView="day"}},created:function(){this.setAvailableYears(),this.resetDate()}})},153:function(t,e,n){"use strict";function r(t,e){var n,r,u,c,l;return Object(s.a)(2,arguments),n=Object(i.a)(t),r=Object(a.a)(e),u=n.getMonth()+r,c=new Date(0),c.setFullYear(n.getFullYear(),u,1),c.setHours(0,0,0,0),l=Object(o.default)(c),n.setMonth(u,Math.min(l,n.getDate())),n}var a,i,o,s;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(18),i=n(10),o=n(97),s=n(8)},154:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(14),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdArrowRightIcon",components:{MdIcon:a.default}}},155:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(14),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdArrowLeftIcon",components:{MdIcon:a.default}}},156:function(t,e){},157:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-portal",[n("transition",{attrs:{name:"md-dialog"}},[t.mdActive?n("div",t._g({staticClass:"md-dialog",class:[t.dialogClasses,t.$mdActiveTheme],on:{keydown:function(e){return!e.type.indexOf("key")&&t._k(e.keyCode,"esc",27,e.key,["Esc","Escape"])?null:t.onEsc(e)}}},t.$listeners),[n("md-focus-trap",[n("div",{staticClass:"md-dialog-container"},[t._t("default"),t._v(" "),n("keep-alive",[t.mdBackdrop?n("md-overlay",{class:t.mdBackdropClass,attrs:{"md-fixed":"","md-active":t.mdActive},on:{click:t.onClick}}):t._e()],1)],2)])],1):t._e()])],1)},a=[],i={render:r,staticRenderFns:a};e.a=i},158:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(14),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdDateIcon",components:{MdIcon:a.default}}},16:function(t,e){function n(){throw Error("setTimeout has not been defined")}function r(){throw Error("clearTimeout has not been defined")}function a(t){if(l===setTimeout)return setTimeout(t,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(t,0);try{return l(t,0)}catch(e){try{return l.call(null,t,0)}catch(e){return l.call(this,t,0)}}}function i(t){if(d===clearTimeout)return clearTimeout(t);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(t);try{return d(t)}catch(e){try{return d.call(null,t)}catch(e){return d.call(this,t)}}}function o(){h&&m&&(h=!1,m.length?f=m.concat(f):p=-1,f.length&&s())}function s(){var t,e;if(!h){for(t=a(o),h=!0,e=f.length;e;){for(m=f,f=[];++p<e;)m&&m[p].run();p=-1,e=f.length}m=null,h=!1,i(t)}}function u(t,e){this.fun=t,this.array=e}function c(){}var l,d,f,h,m,p,g=t.exports={};!(function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(t){d=r}})(),f=[],h=!1,p=-1,g.nextTick=function(t){var e,n=Array(arguments.length-1);if(arguments.length>1)for(e=1;e<arguments.length;e++)n[e-1]=arguments[e];f.push(new u(t,n)),1!==f.length||h||a(s)},u.prototype.run=function(){this.fun.apply(null,this.array)},g.title="browser",g.browser=!0,g.env={},g.argv=[],g.version="",g.versions={},g.on=c,g.addListener=c,g.once=c,g.off=c,g.removeListener=c,g.removeAllListeners=c,g.emit=c,g.prependListener=c,g.prependOnceListener=c,g.listeners=function(t){return[]},g.binding=function(t){throw Error("process.binding is not supported")},g.cwd=function(){return"/"},g.chdir=function(t){throw Error("process.chdir is not supported")},g.umask=function(){return 0}},18:function(t,e,n){"use strict";function r(t){if(null===t||!0===t||!1===t)return NaN;var e=+t;return isNaN(e)?e:e<0?Math.ceil(e):Math.floor(e)}e.a=r},2:function(e,n){e.exports=t},21:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s;Object.defineProperty(e,"__esModule",{value:!0}),a=n(1),i=r(a),o=n(35),s=r(o),e.default=new i.default({name:"MdIcon",components:{MdSvgLoader:s.default},props:{mdSrc:String}})},22:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r={};e.default={name:"MdSVGLoader",props:{mdSrc:{type:String,required:!0}},data:function(){return{html:null,error:null}},watch:{mdSrc:function(){this.html=null,this.loadSVG()}},methods:{isSVG:function(t){return"string"==typeof t&&t.indexOf("svg")>=0},setHtml:function(t){var e=this;r[this.mdSrc].then((function(t){return e.html=t,e.$nextTick()})).then((function(){return e.$emit("md-loaded")}))},unexpectedError:function(t){this.error="Something bad happened trying to fetch "+this.mdSrc+".",t(this.error)},loadSVG:function(){var t=this;r.hasOwnProperty(this.mdSrc)?this.setHtml():r[this.mdSrc]=new Promise(function(e,n){var r=new window.XMLHttpRequest;r.open("GET",t.mdSrc,!0),r.onload=function(){var a=r.getResponseHeader("content-type");200===r.status?t.isSVG(a)?(e(r.response),t.setHtml()):(t.error="The file "+t.mdSrc+" is not a valid SVG.",n(t.error)):r.status>=400&&r.status<500?(t.error="The file "+t.mdSrc+" do not exists.",n(t.error)):t.unexpectedError(n)},r.onerror=function(){return t.unexpectedError(n)},r.onabort=function(){return t.unexpectedError(n)},r.send()})}},mounted:function(){this.loadSVG()}}},28:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s;Object.defineProperty(e,"__esModule",{value:!0}),a=n(2),i=r(a),o=n(11),s=r(o),e.default={name:"MdPortal",abstract:!0,props:{mdAttachToParent:Boolean,mdTarget:{type:null,validator:function(t){return!!(HTMLElement&&t&&t instanceof HTMLElement)||(i.default.util.warn("The md-target-el prop is invalid. You should pass a valid HTMLElement.",this),!1)}}},data:function(){return{leaveTimeout:null,originalParentEl:null}},computed:{transitionName:function(){var t,e,n=this._vnode.componentOptions.children[0];if(n){if(t=n.data.transition)return t.name;if(e=n.componentOptions.propsData.name)return e}return"v"},leaveClass:function(){return this.transitionName+"-leave"},leaveActiveClass:function(){return this.transitionName+"-leave-active"},leaveToClass:function(){return this.transitionName+"-leave-to"}},watch:{mdTarget:function(t,e){this.changeParentEl(t),e&&this.$forceUpdate()}},methods:{getTransitionDuration:function(t){var e=window.getComputedStyle(t).transitionDuration,n=parseFloat(e,10),r=e.match(/m?s/);return r&&(r=r[0]),"s"===r?1e3*n:"ms"===r?n:0},killGhostElement:function(t){t.parentNode&&(this.changeParentEl(this.originalParentEl),this.$options._parentElm=this.originalParentEl,t.parentNode.removeChild(t))},initDestroy:function(t){var e=this,n=this.$el;t&&this.$el.nodeType===Node.COMMENT_NODE&&(n=this.$vnode.elm),n.classList.add(this.leaveClass),n.classList.add(this.leaveActiveClass),this.$nextTick().then((function(){n.classList.add(e.leaveToClass),clearTimeout(e.leaveTimeout),e.leaveTimeout=setTimeout((function(){e.destroyElement(n)}),e.getTransitionDuration(n))}))},destroyElement:function(t){var e=this;(0,s.default)((function(){t.classList.remove(e.leaveClass),t.classList.remove(e.leaveActiveClass),t.classList.remove(e.leaveToClass),e.$emit("md-destroy"),e.killGhostElement(t)}))},changeParentEl:function(t){t&&t.appendChild(this.$el)}},mounted:function(){this.originalParentEl||(this.originalParentEl=this.$el.parentNode,this.$emit("md-initial-parent",this.$el.parentNode)),this.mdAttachToParent&&this.$el.parentNode.parentNode?this.changeParentEl(this.$el.parentNode.parentNode):document&&this.changeParentEl(this.mdTarget||document.body)},beforeDestroy:function(){this.$el.classList?this.initDestroy():this.killGhostElement(this.$el)},render:function(t){var e=this.$slots.default;if(e&&e[0])return e[0]}}},3:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s,u;Object.defineProperty(e,"__esModule",{value:!0}),n(7),a=n(5),i=r(a),o=n(4),s=r(o),u=function(){var t=new i.default({ripple:!0,theming:{},locale:{startYear:1900,endYear:2099,dateFormat:"yyyy-MM-dd",days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shorterDays:["S","M","T","W","T","F","S"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"],shorterMonths:["J","F","M","A","M","Ju","Ju","A","Se","O","N","D"],firstDayOfAWeek:0},router:{linkActiveClass:"router-link-active"}});return Object.defineProperties(t.theming,{metaColors:{get:function(){return s.default.metaColors},set:function(t){s.default.metaColors=t}},theme:{get:function(){return s.default.theme},set:function(t){s.default.theme=t}},enabled:{get:function(){return s.default.enabled},set:function(t){s.default.enabled=t}}}),t},e.default=function(t){t.material||(t.material=u(),t.prototype.$material=t.material)}},326:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s;Object.defineProperty(e,"__esModule",{value:!0}),a=n(3),i=r(a),o=n(327),s=r(o),e.default=function(t){(0,i.default)(t),t.component(s.default.name,s.default)}},327:function(t,e,n){"use strict";function r(t){n(328)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(142),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(353),u=n(0),c=!1,l=r,d=null,f=null,h=u(i.a,s.a,c,l,d,f),e.default=h.exports},328:function(t,e){},329:function(t,e,n){"use strict";t.exports="undefined"!=typeof navigator&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent)},330:function(t,e,n){"use strict";function r(t,e){for(var n=t<0?"-":"",r=""+Math.abs(t);r.length<e;)r="0"+r;return n+r}function a(t){var e,n,r,a;return Object(g.a)(1,arguments),e=Object(h.a)(t),n=e.getTime(),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0),r=e.getTime(),a=n-r,Math.floor(a/v)+1}function i(t,e){var n,a=t>0?"-":"+",i=Math.abs(t),o=Math.floor(i/60),s=i%60;return 0===s?a+(o+""):(n=e||"",a+(o+"")+n+r(s,2))}function o(t,e){if(t%60==0){return(t>0?"-":"+")+r(Math.abs(t)/60,2)}return s(t,e)}function s(t,e){var n=e||"",a=t>0?"-":"+",i=Math.abs(t);return a+r(Math.floor(i/60),2)+n+r(i%60,2)}function u(t,e,n){var r,a,i,o,s,u,m,p,v,b,w,y,M;if(Object(g.a)(2,arguments),r=e+"",a=n||{},i=a.locale||d.a,o=i.options&&i.options.firstWeekContainsDate,s=null==o?1:Object(k.a)(o),!((u=null==a.firstWeekContainsDate?s:Object(k.a)(a.firstWeekContainsDate))>=1&&u<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");if(m=i.options&&i.options.weekStartsOn,p=null==m?0:Object(k.a)(m),!((v=null==a.weekStartsOn?p:Object(k.a)(a.weekStartsOn))>=0&&v<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!i.localize)throw new RangeError("locale must contain localize property");if(!i.formatLong)throw new RangeError("locale must contain formatLong property");if(b=Object(h.a)(t),!Object(l.default)(b))throw new RangeError("Invalid time value");return w=Object(C.a)(b),y=Object(f.a)(b,w),M={firstWeekContainsDate:u,weekStartsOn:v,locale:i,_originalDate:b},r.match(P).map((function(t){var e=t[0];return"p"===e||"P"===e?(0,x.a[e])(t,i.formatLong,M):t})).join("").match(j).map((function(t){var e,n;if("''"===t)return"'";if("'"===(e=t[0]))return c(t);if(n=O[e])return!a.useAdditionalWeekYearTokens&&Object(_.b)(t)&&Object(_.c)(t),!a.useAdditionalDayOfYearTokens&&Object(_.a)(t)&&Object(_.c)(t),n(y,t,i.localize,M);if(e.match(F))throw new RangeError("Format string contains an unescaped latin alphabet character `"+e+"`");return t})).join("")}function c(t){return t.match(E)[1].replace(S,"'")}var l,d,f,h,m,p,g,v,b,w,y,M,T,D,O,x,C,_,k,j,P,E,S,F;Object.defineProperty(e,"__esModule",{value:!0}),l=n(143),d=n(144),f=n(145),h=n(10),m={y:function(t,e){var n=t.getUTCFullYear(),a=n>0?n:1-n;return r("yy"===e?a%100:a,e.length)},M:function(t,e){var n=t.getUTCMonth();return"M"===e?n+1+"":r(n+1,2)},d:function(t,e){return r(t.getUTCDate(),e.length)},a:function(t,e){var n=t.getUTCHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":case"aaa":return n.toUpperCase();case"aaaaa":return n[0];case"aaaa":default:return"am"===n?"a.m.":"p.m."}},h:function(t,e){return r(t.getUTCHours()%12||12,e.length)},H:function(t,e){return r(t.getUTCHours(),e.length)},m:function(t,e){return r(t.getUTCMinutes(),e.length)},s:function(t,e){return r(t.getUTCSeconds(),e.length)},S:function(t,e){var n=e.length,a=t.getUTCMilliseconds();return r(Math.floor(a*Math.pow(10,n-3)),e.length)}},p=m,g=n(8),v=864e5,b=n(146),w=n(147),y=n(148),M=n(94),T={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},D={G:function(t,e,n){var r=t.getUTCFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(t,e,n){var r,a;return"yo"===e?(r=t.getUTCFullYear(),a=r>0?r:1-r,n.ordinalNumber(a,{unit:"year"})):p.y(t,e)},Y:function(t,e,n,a){var i,o=Object(M.a)(t,a),s=o>0?o:1-o;return"YY"===e?(i=s%100,r(i,2)):"Yo"===e?n.ordinalNumber(s,{unit:"year"}):r(s,e.length)},R:function(t,e){return r(Object(w.a)(t),e.length)},u:function(t,e){return r(t.getUTCFullYear(),e.length)},Q:function(t,e,n){var a=Math.ceil((t.getUTCMonth()+1)/3);switch(e){case"Q":return a+"";case"QQ":return r(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(t,e,n){var a=Math.ceil((t.getUTCMonth()+1)/3);switch(e){case"q":return a+"";case"qq":return r(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(t,e,n){var r=t.getUTCMonth();switch(e){case"M":case"MM":return p.M(t,e);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(t,e,n){var a=t.getUTCMonth();switch(e){case"L":return a+1+"";case"LL":return r(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(t,e,n,a){var i=Object(y.a)(t,a);return"wo"===e?n.ordinalNumber(i,{unit:"week"}):r(i,e.length)},I:function(t,e,n){var a=Object(b.a)(t);return"Io"===e?n.ordinalNumber(a,{unit:"week"}):r(a,e.length)},d:function(t,e,n){return"do"===e?n.ordinalNumber(t.getUTCDate(),{unit:"date"}):p.d(t,e)},D:function(t,e,n){var i=a(t);return"Do"===e?n.ordinalNumber(i,{unit:"dayOfYear"}):r(i,e.length)},E:function(t,e,n){var r=t.getUTCDay();switch(e){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(t,e,n,a){var i=t.getUTCDay(),o=(i-a.weekStartsOn+8)%7||7;switch(e){case"e":return o+"";case"ee":return r(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(i,{width:"short",context:"formatting"});case"eeee":default:return n.day(i,{width:"wide",context:"formatting"})}},c:function(t,e,n,a){var i=t.getUTCDay(),o=(i-a.weekStartsOn+8)%7||7;switch(e){case"c":return o+"";case"cc":return r(o,e.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(i,{width:"narrow",context:"standalone"});case"cccccc":return n.day(i,{width:"short",context:"standalone"});case"cccc":default:return n.day(i,{width:"wide",context:"standalone"})}},i:function(t,e,n){var a=t.getUTCDay(),i=0===a?7:a;switch(e){case"i":return i+"";case"ii":return r(i,e.length);case"io":return n.ordinalNumber(i,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});case"iiii":default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(t,e,n){var r=t.getUTCHours(),a=r/12>=1?"pm":"am";switch(e){case"a":case"aa":case"aaa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaaaa":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(t,e,n){var r,a=t.getUTCHours();switch(r=12===a?T.noon:0===a?T.midnight:a/12>=1?"pm":"am",e){case"b":case"bb":case"bbb":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbbbb":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(t,e,n){var r,a=t.getUTCHours();switch(r=a>=17?T.evening:a>=12?T.afternoon:a>=4?T.morning:T.night,e){case"B":case"BB":case"BBB":return n.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(r,{width:"wide",context:"formatting"})}},h:function(t,e,n){if("ho"===e){var r=t.getUTCHours()%12;return 0===r&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return p.h(t,e)},H:function(t,e,n){return"Ho"===e?n.ordinalNumber(t.getUTCHours(),{unit:"hour"}):p.H(t,e)},K:function(t,e,n){var a=t.getUTCHours()%12;return"Ko"===e?n.ordinalNumber(a,{unit:"hour"}):r(a,e.length)},k:function(t,e,n){var a=t.getUTCHours();return 0===a&&(a=24),"ko"===e?n.ordinalNumber(a,{unit:"hour"}):r(a,e.length)},m:function(t,e,n){return"mo"===e?n.ordinalNumber(t.getUTCMinutes(),{unit:"minute"}):p.m(t,e)},s:function(t,e,n){return"so"===e?n.ordinalNumber(t.getUTCSeconds(),{unit:"second"}):p.s(t,e)},S:function(t,e){return p.S(t,e)},X:function(t,e,n,r){var a=r._originalDate||t,i=a.getTimezoneOffset();if(0===i)return"Z";switch(e){case"X":return o(i);case"XXXX":case"XX":return s(i);case"XXXXX":case"XXX":default:return s(i,":")}},x:function(t,e,n,r){var a=r._originalDate||t,i=a.getTimezoneOffset();switch(e){case"x":return o(i);case"xxxx":case"xx":return s(i);case"xxxxx":case"xxx":default:return s(i,":")}},O:function(t,e,n,r){var a=r._originalDate||t,o=a.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+i(o,":");case"OOOO":default:return"GMT"+s(o,":")}},z:function(t,e,n,r){var a=r._originalDate||t,o=a.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+i(o,":");case"zzzz":default:return"GMT"+s(o,":")}},t:function(t,e,n,a){var i=a._originalDate||t;return r(Math.floor(i.getTime()/1e3),e.length)},T:function(t,e,n,a){return r((a._originalDate||t).getTime(),e.length)}},O=D,x=n(149),C=n(150),_=n(151),k=n(18),e.default=u,j=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,P=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,E=/^'([^]*?)'?$/,S=/''/g,F=/[a-zA-Z]/},331:function(t,e,n){"use strict";function r(t,e){if(null==t)throw new TypeError("assign requires that input parameter not be null or undefined");e=e||{};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}function a(t,e,n){var r,a,i,o,s,u,c,l,d,f,h;if(Object(_.a)(2,arguments),r=n||{},a=r.locale,i=a&&a.options&&a.options.weekStartsOn,o=null==i?0:Object(x.a)(i),!((s=null==r.weekStartsOn?o:Object(x.a)(r.weekStartsOn))>=0&&s<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");return u=Object(M.a)(t),c=Object(x.a)(e),l=u.getUTCDay(),d=c%7,f=(d+7)%7,h=(f<s?7:0)+c-l,u.setUTCDate(u.getUTCDate()+h),u}function i(t,e){var n,r,a,i,o,s,u;return Object(_.a)(2,arguments),n=Object(x.a)(e),n%7==0&&(n-=7),r=1,a=Object(M.a)(t),i=a.getUTCDay(),o=n%7,s=(o+7)%7,u=(s<r?7:0)+n-i,a.setUTCDate(a.getUTCDate()+u),a}function o(t,e){var n,r,a;return Object(_.a)(2,arguments),n=Object(M.a)(t),r=Object(x.a)(e),a=Object(k.a)(n)-r,n.setUTCDate(n.getUTCDate()-7*a),n}function s(t,e,n){var r,a,i;return Object(_.a)(2,arguments),r=Object(M.a)(t),a=Object(x.a)(e),i=Object(j.a)(r,n)-a,r.setUTCDate(r.getUTCDate()-7*i),r}function u(t,e,n){var r,a=e.match(t);return a?(r=parseInt(a[0],10),{value:n?n(r):r,rest:e.slice(a[0].length)}):null}function c(t,e){var n,r,a,i,o=e.match(t);return o?"Z"===o[0]?{value:0,rest:e.slice(1)}:(n="+"===o[1]?1:-1,r=o[2]?parseInt(o[2],10):0,a=o[3]?parseInt(o[3],10):0,i=o[5]?parseInt(o[5],10):0,{value:n*(r*S+a*F+i*N),rest:e.slice(o[0].length)}):null}function l(t,e){return u(U.anyDigitsSigned,t,e)}function d(t,e,n){switch(t){case 1:return u(U.singleDigit,e,n);case 2:return u(U.twoDigits,e,n);case 3:return u(U.threeDigits,e,n);case 4:return u(U.fourDigits,e,n);default:return u(RegExp("^\\d{1,"+t+"}"),e,n)}}function f(t,e,n){switch(t){case 1:return u(U.singleDigitSigned,e,n);case 2:return u(U.twoDigitsSigned,e,n);case 3:return u(U.threeDigitsSigned,e,n);case 4:return u(U.fourDigitsSigned,e,n);default:return u(RegExp("^-?\\d{1,"+t+"}"),e,n)}}function h(t){switch(t){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function m(t,e){var n,r,a,i,o=e>0,s=o?e:1-e;return s<=50?n=t||100:(r=s+50,a=100*Math.floor(r/100),i=t>=r%100,n=t+a-(i?100:0)),o?n:1-n}function p(t){return t%400==0||t%4==0&&t%100!=0}function g(t,e,n,a){var i,o,s,u,c,l,d,f,h,m,p,g,C,k,j,P,E,S,F,N,U,L,A,H,Y,W,R,z,Q;if(Object(_.a)(3,arguments),i=t+"",o=e+"",s=a||{},u=s.locale||w.a,!u.match)throw new RangeError("locale must contain match property");if(c=u.options&&u.options.firstWeekContainsDate,l=null==c?1:Object(x.a)(c),!((d=null==s.firstWeekContainsDate?l:Object(x.a)(s.firstWeekContainsDate))>=1&&d<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");if(f=u.options&&u.options.weekStartsOn,h=null==f?0:Object(x.a)(f),!((m=null==s.weekStartsOn?h:Object(x.a)(s.weekStartsOn))>=0&&m<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(""===o)return""===i?Object(M.a)(n):new Date(NaN);for(p={firstWeekContainsDate:d,weekStartsOn:m,locale:u},g=[{priority:$,set:v,index:0}],k=o.match(I).map((function(t){var e=t[0];return"p"===e||"P"===e?(0,T.a[e])(t,u.formatLong,p):t})).join("").match(B),j=[],C=0;C<k.length;C++)if(P=k[C],!s.useAdditionalWeekYearTokens&&Object(O.b)(P)&&Object(O.c)(P),!s.useAdditionalDayOfYearTokens&&Object(O.a)(P)&&Object(O.c)(P),E=P[0],S=q[E]){if(F=S.incompatibleTokens,Array.isArray(F)){for(N=void 0,U=0;U<j.length;U++)if(L=j[U].token,-1!==F.indexOf(L)||L===E){N=j[U];break}if(N)throw new RangeError("The format string mustn't contain `".concat(N.fullToken,"` and `").concat(P,"` at the same time"))}else if("*"===S.incompatibleTokens&&j.length)throw new RangeError("The format string mustn't contain `".concat(P,"` and any other token at the same time"));if(j.push({token:E,fullToken:P}),!(A=S.parse(i,P,u.match,p)))return new Date(NaN);g.push({priority:S.priority,set:S.set,validate:S.validate,value:A.value,index:g.length}),i=A.rest}else{if(E.match(G))throw new RangeError("Format string contains an unescaped latin alphabet character `"+E+"`");if("''"===P?P="'":"'"===E&&(P=b(P)),0!==i.indexOf(P))return new Date(NaN);i=i.slice(P.length)}if(i.length>0&&V.test(i))return new Date(NaN);if(H=g.map((function(t){return t.priority})).sort((function(t,e){return e-t})).filter((function(t,e,n){return n.indexOf(t)===e})).map((function(t){return g.filter((function(e){return e.priority===t})).reverse()})).map((function(t){return t[0]})),Y=Object(M.a)(n),isNaN(Y))return new Date(NaN);for(W=Object(y.a)(Y,Object(D.a)(Y)),R={},C=0;C<H.length;C++){if(z=H[C],z.validate&&!z.validate(W,z.value,p))return new Date(NaN);Q=z.set(W,R,z.value,p),Q[0]?(W=Q[0],r(R,Q[1])):W=Q}return W}function v(t,e){if(e.timestampIsSet)return t;var n=new Date(0);return n.setFullYear(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()),n.setHours(t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()),n}function b(t){return t.match(W)[1].replace(R,"'")}var w,y,M,T,D,O,x,C,_,k,j,P,E,S,F,N,U,L,A,H,Y,q,$,B,I,W,R,V,G;Object.defineProperty(e,"__esModule",{value:!0}),w=n(144),y=n(145),M=n(10),T=n(149),D=n(150),O=n(151),x=n(18),C=n(94),_=n(8),k=n(146),j=n(148),P=n(65),E=n(66),S=36e5,F=6e4,N=1e3,U={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},L={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/},A=[31,28,31,30,31,30,31,31,30,31,30,31],H=[31,29,31,30,31,30,31,31,30,31,30,31],Y={G:{priority:140,parse:function(t,e,n,r){switch(e){case"G":case"GG":case"GGG":return n.era(t,{width:"abbreviated"})||n.era(t,{width:"narrow"});case"GGGGG":return n.era(t,{width:"narrow"});case"GGGG":default:return n.era(t,{width:"wide"})||n.era(t,{width:"abbreviated"})||n.era(t,{width:"narrow"})}},set:function(t,e,n,r){return e.era=n,t.setUTCFullYear(n,0,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["R","u","t","T"]},y:{priority:130,parse:function(t,e,n,r){var a=function(t){return{year:t,isTwoDigitYear:"yy"===e}};switch(e){case"y":return d(4,t,a);case"yo":return n.ordinalNumber(t,{unit:"year",valueCallback:a});default:return d(e.length,t,a)}},validate:function(t,e,n){return e.isTwoDigitYear||e.year>0},set:function(t,e,n,r){var a,i,o=t.getUTCFullYear();return n.isTwoDigitYear?(a=m(n.year,o),t.setUTCFullYear(a,0,1),t.setUTCHours(0,0,0,0),t):(i="era"in e&&1!==e.era?1-n.year:n.year,t.setUTCFullYear(i,0,1),t.setUTCHours(0,0,0,0),t)},incompatibleTokens:["Y","R","u","w","I","i","e","c","t","T"]},Y:{priority:130,parse:function(t,e,n,r){var a=function(t){return{year:t,isTwoDigitYear:"YY"===e}};switch(e){case"Y":return d(4,t,a);case"Yo":return n.ordinalNumber(t,{unit:"year",valueCallback:a});default:return d(e.length,t,a)}},validate:function(t,e,n){return e.isTwoDigitYear||e.year>0},set:function(t,e,n,r){var a,i,o=Object(C.a)(t,r);return n.isTwoDigitYear?(a=m(n.year,o),t.setUTCFullYear(a,0,r.firstWeekContainsDate),t.setUTCHours(0,0,0,0),Object(E.a)(t,r)):(i="era"in e&&1!==e.era?1-n.year:n.year,t.setUTCFullYear(i,0,r.firstWeekContainsDate),t.setUTCHours(0,0,0,0),Object(E.a)(t,r))},incompatibleTokens:["y","R","u","Q","q","M","L","I","d","D","i","t","T"]},R:{priority:130,parse:function(t,e,n,r){return"R"===e?f(4,t):f(e.length,t)},set:function(t,e,n,r){var a=new Date(0);return a.setUTCFullYear(n,0,4),a.setUTCHours(0,0,0,0),Object(P.a)(a)},incompatibleTokens:["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]},u:{priority:130,parse:function(t,e,n,r){return"u"===e?f(4,t):f(e.length,t)},set:function(t,e,n,r){return t.setUTCFullYear(n,0,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["G","y","Y","R","w","I","i","e","c","t","T"]},Q:{priority:120,parse:function(t,e,n,r){switch(e){case"Q":case"QQ":return d(e.length,t);case"Qo":return n.ordinalNumber(t,{unit:"quarter"});case"QQQ":return n.quarter(t,{width:"abbreviated",context:"formatting"})||n.quarter(t,{width:"narrow",context:"formatting"});case"QQQQQ":return n.quarter(t,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(t,{width:"wide",context:"formatting"})||n.quarter(t,{width:"abbreviated",context:"formatting"})||n.quarter(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,n){return e>=1&&e<=4},set:function(t,e,n,r){return t.setUTCMonth(3*(n-1),1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]},q:{priority:120,parse:function(t,e,n,r){switch(e){case"q":case"qq":return d(e.length,t);case"qo":return n.ordinalNumber(t,{unit:"quarter"});case"qqq":return n.quarter(t,{width:"abbreviated",context:"standalone"})||n.quarter(t,{width:"narrow",context:"standalone"});case"qqqqq":return n.quarter(t,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(t,{width:"wide",context:"standalone"})||n.quarter(t,{width:"abbreviated",context:"standalone"})||n.quarter(t,{width:"narrow",context:"standalone"})}},validate:function(t,e,n){return e>=1&&e<=4},set:function(t,e,n,r){return t.setUTCMonth(3*(n-1),1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]},M:{priority:110,parse:function(t,e,n,r){var a=function(t){return t-1};switch(e){case"M":return u(U.month,t,a);case"MM":return d(2,t,a);case"Mo":return n.ordinalNumber(t,{unit:"month",valueCallback:a});case"MMM":return n.month(t,{width:"abbreviated",context:"formatting"})||n.month(t,{width:"narrow",context:"formatting"});case"MMMMM":return n.month(t,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(t,{width:"wide",context:"formatting"})||n.month(t,{width:"abbreviated",context:"formatting"})||n.month(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,n){return e>=0&&e<=11},set:function(t,e,n,r){return t.setUTCMonth(n,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]},L:{priority:110,parse:function(t,e,n,r){var a=function(t){return t-1};switch(e){case"L":return u(U.month,t,a);case"LL":return d(2,t,a);case"Lo":return n.ordinalNumber(t,{unit:"month",valueCallback:a});case"LLL":return n.month(t,{width:"abbreviated",context:"standalone"})||n.month(t,{width:"narrow",context:"standalone"});case"LLLLL":return n.month(t,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(t,{width:"wide",context:"standalone"})||n.month(t,{width:"abbreviated",context:"standalone"})||n.month(t,{width:"narrow",context:"standalone"})}},validate:function(t,e,n){return e>=0&&e<=11},set:function(t,e,n,r){return t.setUTCMonth(n,1),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]},w:{priority:100,parse:function(t,e,n,r){switch(e){case"w":return u(U.week,t);case"wo":return n.ordinalNumber(t,{unit:"week"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=1&&e<=53},set:function(t,e,n,r){return Object(E.a)(s(t,n,r),r)},incompatibleTokens:["y","R","u","q","Q","M","L","I","d","D","i","t","T"]},I:{priority:100,parse:function(t,e,n,r){switch(e){case"I":return u(U.week,t);case"Io":return n.ordinalNumber(t,{unit:"week"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=1&&e<=53},set:function(t,e,n,r){return Object(P.a)(o(t,n,r),r)},incompatibleTokens:["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]},d:{priority:90,parse:function(t,e,n,r){switch(e){case"d":return u(U.date,t);case"do":return n.ordinalNumber(t,{unit:"date"});default:return d(e.length,t)}},validate:function(t,e,n){var r=t.getUTCFullYear(),a=p(r),i=t.getUTCMonth();return a?e>=1&&e<=H[i]:e>=1&&e<=A[i]},set:function(t,e,n,r){return t.setUTCDate(n),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","w","I","D","i","e","c","t","T"]},D:{priority:90,parse:function(t,e,n,r){switch(e){case"D":case"DD":return u(U.dayOfYear,t);case"Do":return n.ordinalNumber(t,{unit:"date"});default:return d(e.length,t)}},validate:function(t,e,n){return p(t.getUTCFullYear())?e>=1&&e<=366:e>=1&&e<=365},set:function(t,e,n,r){return t.setUTCMonth(0,n),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]},E:{priority:90,parse:function(t,e,n,r){switch(e){case"E":case"EE":case"EEE":return n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"EEEEE":return n.day(t,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"EEEE":default:return n.day(t,{width:"wide",context:"formatting"})||n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,n){return e>=0&&e<=6},set:function(t,e,n,r){return t=a(t,n,r),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["D","i","e","c","t","T"]},e:{priority:90,parse:function(t,e,n,r){var a=function(t){var e=7*Math.floor((t-1)/7);return(t+r.weekStartsOn+6)%7+e};switch(e){case"e":case"ee":return d(e.length,t,a);case"eo":return n.ordinalNumber(t,{unit:"day",valueCallback:a});case"eee":return n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"eeeee":return n.day(t,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"});case"eeee":default:return n.day(t,{width:"wide",context:"formatting"})||n.day(t,{width:"abbreviated",context:"formatting"})||n.day(t,{width:"short",context:"formatting"})||n.day(t,{width:"narrow",context:"formatting"})}},validate:function(t,e,n){return e>=0&&e<=6},set:function(t,e,n,r){return t=a(t,n,r),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]},c:{priority:90,parse:function(t,e,n,r){var a=function(t){var e=7*Math.floor((t-1)/7);return(t+r.weekStartsOn+6)%7+e};switch(e){case"c":case"cc":return d(e.length,t,a);case"co":return n.ordinalNumber(t,{unit:"day",valueCallback:a});case"ccc":return n.day(t,{width:"abbreviated",context:"standalone"})||n.day(t,{width:"short",context:"standalone"})||n.day(t,{width:"narrow",context:"standalone"});case"ccccc":return n.day(t,{width:"narrow",context:"standalone"});case"cccccc":return n.day(t,{width:"short",context:"standalone"})||n.day(t,{width:"narrow",context:"standalone"});case"cccc":default:return n.day(t,{width:"wide",context:"standalone"})||n.day(t,{width:"abbreviated",context:"standalone"})||n.day(t,{width:"short",context:"standalone"})||n.day(t,{width:"narrow",context:"standalone"})}},validate:function(t,e,n){return e>=0&&e<=6},set:function(t,e,n,r){return t=a(t,n,r),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]},i:{priority:90,parse:function(t,e,n,r){var a=function(t){return 0===t?7:t};switch(e){case"i":case"ii":return d(e.length,t);case"io":return n.ordinalNumber(t,{unit:"day"});case"iii":return n.day(t,{width:"abbreviated",context:"formatting",valueCallback:a})||n.day(t,{width:"short",context:"formatting",valueCallback:a})||n.day(t,{width:"narrow",context:"formatting",valueCallback:a});case"iiiii":return n.day(t,{width:"narrow",context:"formatting",valueCallback:a});case"iiiiii":return n.day(t,{width:"short",context:"formatting",valueCallback:a})||n.day(t,{width:"narrow",context:"formatting",valueCallback:a});case"iiii":default:return n.day(t,{width:"wide",context:"formatting",valueCallback:a})||n.day(t,{width:"abbreviated",context:"formatting",valueCallback:a})||n.day(t,{width:"short",context:"formatting",valueCallback:a})||n.day(t,{width:"narrow",context:"formatting",valueCallback:a})}},validate:function(t,e,n){return e>=1&&e<=7},set:function(t,e,n,r){return t=i(t,n,r),t.setUTCHours(0,0,0,0),t},incompatibleTokens:["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]},a:{priority:80,parse:function(t,e,n,r){switch(e){case"a":case"aa":case"aaa":return n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaaa":return n.dayPeriod(t,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(t,{width:"wide",context:"formatting"})||n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"})}},set:function(t,e,n,r){return t.setUTCHours(h(n),0,0,0),t},incompatibleTokens:["b","B","H","K","k","t","T"]},b:{priority:80,parse:function(t,e,n,r){switch(e){case"b":case"bb":case"bbb":return n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbbb":return n.dayPeriod(t,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(t,{width:"wide",context:"formatting"})||n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"})}},set:function(t,e,n,r){return t.setUTCHours(h(n),0,0,0),t},incompatibleTokens:["a","B","H","K","k","t","T"]},B:{priority:80,parse:function(t,e,n,r){switch(e){case"B":case"BB":case"BBB":return n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBBB":return n.dayPeriod(t,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(t,{width:"wide",context:"formatting"})||n.dayPeriod(t,{width:"abbreviated",context:"formatting"})||n.dayPeriod(t,{width:"narrow",context:"formatting"})}},set:function(t,e,n,r){return t.setUTCHours(h(n),0,0,0),t},incompatibleTokens:["a","b","t","T"]},h:{priority:70,parse:function(t,e,n,r){switch(e){case"h":return u(U.hour12h,t);case"ho":return n.ordinalNumber(t,{unit:"hour"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=1&&e<=12},set:function(t,e,n,r){var a=t.getUTCHours()>=12;return a&&n<12?t.setUTCHours(n+12,0,0,0):a||12!==n?t.setUTCHours(n,0,0,0):t.setUTCHours(0,0,0,0),t},incompatibleTokens:["H","K","k","t","T"]},H:{priority:70,parse:function(t,e,n,r){switch(e){case"H":return u(U.hour23h,t);case"Ho":return n.ordinalNumber(t,{unit:"hour"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=0&&e<=23},set:function(t,e,n,r){return t.setUTCHours(n,0,0,0),t},incompatibleTokens:["a","b","h","K","k","t","T"]},K:{priority:70,parse:function(t,e,n,r){switch(e){case"K":return u(U.hour11h,t);case"Ko":return n.ordinalNumber(t,{unit:"hour"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=0&&e<=11},set:function(t,e,n,r){return t.getUTCHours()>=12&&n<12?t.setUTCHours(n+12,0,0,0):t.setUTCHours(n,0,0,0),t},incompatibleTokens:["a","b","h","H","k","t","T"]},k:{priority:70,parse:function(t,e,n,r){switch(e){case"k":return u(U.hour24h,t);case"ko":return n.ordinalNumber(t,{unit:"hour"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=1&&e<=24},set:function(t,e,n,r){var a=n<=24?n%24:n;return t.setUTCHours(a,0,0,0),t},incompatibleTokens:["a","b","h","H","K","t","T"]},m:{priority:60,parse:function(t,e,n,r){switch(e){case"m":return u(U.minute,t);case"mo":return n.ordinalNumber(t,{unit:"minute"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=0&&e<=59},set:function(t,e,n,r){return t.setUTCMinutes(n,0,0),t},incompatibleTokens:["t","T"]},s:{priority:50,parse:function(t,e,n,r){switch(e){case"s":return u(U.second,t);case"so":return n.ordinalNumber(t,{unit:"second"});default:return d(e.length,t)}},validate:function(t,e,n){return e>=0&&e<=59},set:function(t,e,n,r){return t.setUTCSeconds(n,0),t},incompatibleTokens:["t","T"]},S:{priority:30,parse:function(t,e,n,r){var a=function(t){return Math.floor(t*Math.pow(10,3-e.length))};return d(e.length,t,a)},set:function(t,e,n,r){return t.setUTCMilliseconds(n),t},incompatibleTokens:["t","T"]},X:{priority:10,parse:function(t,e,n,r){switch(e){case"X":return c(L.basicOptionalMinutes,t);case"XX":return c(L.basic,t);case"XXXX":return c(L.basicOptionalSeconds,t);case"XXXXX":return c(L.extendedOptionalSeconds,t);case"XXX":default:return c(L.extended,t)}},set:function(t,e,n,r){return e.timestampIsSet?t:new Date(t.getTime()-n)},incompatibleTokens:["t","T","x"]},x:{priority:10,parse:function(t,e,n,r){switch(e){case"x":return c(L.basicOptionalMinutes,t);case"xx":return c(L.basic,t);case"xxxx":return c(L.basicOptionalSeconds,t);case"xxxxx":return c(L.extendedOptionalSeconds,t);case"xxx":default:return c(L.extended,t)}},set:function(t,e,n,r){return e.timestampIsSet?t:new Date(t.getTime()-n)},incompatibleTokens:["t","T","X"]},t:{priority:40,parse:function(t,e,n,r){return l(t)},set:function(t,e,n,r){return[new Date(1e3*n),{timestampIsSet:!0}]},incompatibleTokens:"*"},T:{priority:20,parse:function(t,e,n,r){return l(t)},set:function(t,e,n,r){return[new Date(n),{timestampIsSet:!0}]},incompatibleTokens:"*"}},q=Y,e.default=g,$=10,B=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,I=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,W=/^'([^]*?)'?$/,R=/''/g,V=/\S/,G=/[a-zA-Z]/},332:function(t,e,n){"use strict";function r(t){n(333)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(152),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(349),u=n(0),c=!1,l=r,d=null,f=null,h=u(i.a,s.a,c,l,d,f),e.default=h.exports},333:function(t,e){},334:function(t,e,n){"use strict";function r(t){Object(i.a)(1,arguments);var e=Object(a.a)(t);return e.setDate(1),e.setHours(0,0,0,0),e}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)},335:function(t,e,n){"use strict";function r(t,e){Object(o.a)(2,arguments);var n=Object(a.a)(e);return Object(i.default)(t,-n)}var a,i,o;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(18),i=n(153),o=n(8)},336:function(t,e,n){"use strict";function r(t){var e;return Object(i.a)(1,arguments),e=Object(a.a)(t),e.getDate()}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)},337:function(t,e,n){"use strict";function r(t){var e;return Object(i.a)(1,arguments),e=Object(a.a)(t),e.getDay()}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)},338:function(t,e,n){"use strict";function r(t){var e;return Object(i.a)(1,arguments),e=Object(a.a)(t),e.getMonth()}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)},339:function(t,e,n){"use strict";function r(t){var e;return Object(i.a)(1,arguments),e=Object(a.a)(t),e.getFullYear()}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)},34:function(t,e){},340:function(t,e,n){"use strict";function r(t,e){var n,r;return Object(i.a)(2,arguments),n=Object(a.a)(t),r=Object(a.a)(e),n.getTime()===r.getTime()}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)},341:function(t,e,n){"use strict";function r(t){Object(o.a)(1,arguments);var e=Object(i.a)(t);return e.setHours(0,0,0,0),e}function a(t,e){var n,a;return Object(o.a)(2,arguments),n=r(t),a=r(e),n.getTime()===a.getTime()}var i,o;Object.defineProperty(e,"__esModule",{value:!0}),i=n(10),o=n(8),e.default=a},342:function(t,e,n){"use strict";function r(t,e){var n,r;return Object(o.a)(2,arguments),n=Object(i.a)(t),r=Object(a.a)(e),n.setDate(r),n}var a,i,o;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(18),i=n(10),o=n(8)},343:function(t,e,n){"use strict";function r(t,e){var n,r,u,c,l,d;return Object(s.a)(2,arguments),n=Object(i.a)(t),r=Object(a.a)(e),u=n.getFullYear(),c=n.getDate(),l=new Date(0),l.setFullYear(u,r,15),l.setHours(0,0,0,0),d=Object(o.default)(l),n.setMonth(r,Math.min(c,d)),n}var a,i,o,s;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(18),i=n(10),o=n(97),s=n(8)},344:function(t,e,n){"use strict";function r(t,e){var n,r;return Object(o.a)(2,arguments),n=Object(i.a)(t),r=Object(a.a)(e),isNaN(n)?new Date(NaN):(n.setFullYear(r),n)}var a,i,o;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(18),i=n(10),o=n(8)},345:function(t,e,n){"use strict";var r,a,i,o,s,u,c,l,d,f;Object.defineProperty(e,"__esModule",{value:!0}),r=n(154),a=n.n(r);for(i in r)"default"!==i&&(function(t){n.d(e,t,(function(){return r[t]}))})(i);o=n(346),s=n(0),u=!1,c=null,l=null,d=null,f=s(a.a,o.a,u,c,l,d),e.default=f.exports},346:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(0)},a=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-icon",{staticClass:"md-icon-image"},[n("svg",{attrs:{height:"24",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg"}},[n("path",{attrs:{d:"M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"}}),t._v(" "),n("path",{attrs:{d:"M0-.25h24v24H0z",fill:"none"}})])])}],i={render:r,staticRenderFns:a};e.a=i},347:function(t,e,n){"use strict";var r,a,i,o,s,u,c,l,d,f;Object.defineProperty(e,"__esModule",{value:!0}),r=n(155),a=n.n(r);for(i in r)"default"!==i&&(function(t){n.d(e,t,(function(){return r[t]}))})(i);o=n(348),s=n(0),u=!1,c=null,l=null,d=null,f=s(a.a,o.a,u,c,l,d),e.default=f.exports},348:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(0)},a=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-icon",{staticClass:"md-icon-image"},[n("svg",{attrs:{height:"24",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg"}},[n("path",{attrs:{d:"M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"}}),t._v(" "),n("path",{attrs:{d:"M0-.5h24v24H0z",fill:"none"}})])])}],i={render:r,staticRenderFns:a};e.a=i},349:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-popover",{attrs:{"md-settings":t.popperSettings,"md-active":""}},[n("transition",{attrs:{name:"md-datepicker-dialog",appear:""},on:{enter:t.setContentStyles,"after-leave":t.resetDate}},[n("div",{staticClass:"md-datepicker-dialog",class:[t.$mdActiveTheme]},[n("div",{staticClass:"md-datepicker-header"},[n("span",{staticClass:"md-datepicker-year-select",class:{"md-selected":"year"===t.currentView},on:{click:function(e){t.currentView="year"}}},[t._v(t._s(t.selectedYear))]),t._v(" "),n("div",{staticClass:"md-datepicker-date-select",class:{"md-selected":"year"!==t.currentView},on:{click:function(e){t.currentView="day"}}},[n("strong",{staticClass:"md-datepicker-dayname"},[t._v(t._s(t.shortDayName)+", ")]),t._v(" "),n("strong",{staticClass:"md-datepicker-monthname"},[t._v(t._s(t.shortMonthName))]),t._v(" "),n("strong",{staticClass:"md-datepicker-day"},[t._v(t._s(t.currentDay))])])]),t._v(" "),n("div",{staticClass:"md-datepicker-body"},[n("transition",{attrs:{name:"md-datepicker-body-header"}},["day"===t.currentView?n("div",{staticClass:"md-datepicker-body-header"},[n("md-button",{staticClass:"md-dense md-icon-button",on:{click:t.previousMonth}},[n("md-arrow-left-icon")],1),t._v(" "),n("md-button",{staticClass:"md-dense md-icon-button",on:{click:t.nextMonth}},[n("md-arrow-right-icon")],1)],1):t._e()]),t._v(" "),n("div",{staticClass:"md-datepicker-body-content",style:t.contentStyles},[n("transition",{attrs:{name:"md-datepicker-view"}},["day"===t.currentView?n("transition-group",{staticClass:"md-datepicker-panel md-datepicker-calendar",class:t.calendarClasses,attrs:{tag:"div",name:"md-datepicker-month"}},t._l([t.currentDate],(function(e){return n("div",{key:e.getMonth(),staticClass:"md-datepicker-panel md-datepicker-month"},[n("md-button",{staticClass:"md-dense md-datepicker-month-trigger",on:{click:function(e){t.currentView="month"}}},[t._v(t._s(t.currentMonthName)+" "+t._s(t.currentYear))]),t._v(" "),n("div",{staticClass:"md-datepicker-week"},[t._l(t.locale.shorterDays,(function(e,r){return r>=t.firstDayOfAWeek?n("span",{key:r},[t._v(t._s(e))]):t._e()})),t._v(" "),t._l(t.locale.shorterDays,(function(e,r){return r<t.firstDayOfAWeek?n("span",{key:r},[t._v(t._s(e))]):t._e()}))],2),t._v(" "),n("div",{staticClass:"md-datepicker-days"},[t._l(t.prefixEmptyDays,(function(t){return n("span",{key:"day-empty-"+t,staticClass:"md-datepicker-empty"})})),t._v(" "),t._l(t.daysInMonth,(function(e){return n("div",{key:"day-"+e,staticClass:"md-datepicker-day"},[n("span",{staticClass:"md-datepicker-day-button",class:{"md-datepicker-selected":t.isSelectedDay(e),"md-datepicker-today":t.isToday(e),"md-datepicker-disabled":t.isDisabled(e)},on:{click:function(n){return t.selectDate(e)}}},[t._v(t._s(e))])])}))],2)],1)})),0):"month"===t.currentView?n("div",{staticClass:"md-datepicker-panel md-datepicker-month-selector"},[n("md-button",{staticClass:"md-datepicker-year-trigger",on:{click:function(e){t.currentView="year"}}},[t._v(t._s(t.currentYear))]),t._v(" "),t._l(t.locale.months,(function(e,r){return n("span",{key:e,staticClass:"md-datepicker-month-button",class:{"md-datepicker-selected":t.currentMonthName===e},on:{click:function(e){return t.switchMonth(r)}}},[t._v(t._s(e))])}))],2):"year"===t.currentView?n("keep-alive",[n("md-content",{staticClass:"md-datepicker-panel md-datepicker-year-selector md-scrollbar"},t._l(t.availableYears,(function(e){return n("span",{key:e,staticClass:"md-datepicker-year-button",class:{"md-datepicker-selected":t.currentYear===e},on:{click:function(n){return t.switchYear(e)}}},[t._v(t._s(e))])})),0)],1):t._e()],1)],1),t._v(" "),n("md-dialog-actions",{staticClass:"md-datepicker-body-footer"},[n("md-button",{staticClass:"md-primary",on:{click:t.onCancel}},[t._v("Cancel")]),t._v(" "),t.mdImmediately?t._e():n("md-button",{staticClass:"md-primary",on:{click:t.onConfirm}},[t._v("Ok")])],1)],1)])])],1)},a=[],i={render:r,staticRenderFns:a};e.a=i},35:function(t,e,n){"use strict";function r(t){n(36)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(22),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(37),u=n(0),c=!1,l=r,d=null,f=null,h=u(i.a,s.a,c,l,d,f),e.default=h.exports},350:function(t,e,n){"use strict";var r,a,i,o,s,u,c,l,d,f;Object.defineProperty(e,"__esModule",{value:!0}),r=n(158),a=n.n(r);for(i in r)"default"!==i&&(function(t){n.d(e,t,(function(){return r[t]}))})(i);o=n(351),s=n(0),u=!1,c=null,l=null,d=null,f=s(a.a,o.a,u,c,l,d),e.default=f.exports},351:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(0)},a=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-icon",{staticClass:"md-icon-image"},[n("svg",{attrs:{height:"24",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg"}},[n("path",{attrs:{d:"M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"}}),t._v(" "),n("path",{attrs:{d:"M0 0h24v24H0z",fill:"none"}})])])}],i={render:r,staticRenderFns:a};e.a=i},352:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){var n=void 0;return function(){var r=this,a=arguments,i=function(){return t.apply(r,a)};clearTimeout(n),n=setTimeout(i,e)}}},353:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-field",{class:["md-datepicker",{"md-native":!this.mdOverrideNative}],attrs:{"md-clearable":""}},[n("md-date-icon",{staticClass:"md-date-icon",nativeOn:{click:function(e){return t.toggleDialog(e)}}}),t._v(" "),n("md-input",{ref:"input",attrs:{type:t.type,pattern:t.pattern},nativeOn:{focus:function(e){return t.onFocus(e)}},model:{value:t.inputDate,callback:function(e){t.inputDate=e},expression:"inputDate"}}),t._v(" "),t._t("default"),t._v(" "),n("keep-alive",[t.showDialog?n("md-datepicker-dialog",{attrs:{"md-date":t.localDate,"md-disabled-dates":t.mdDisabledDates,mdImmediately:t.mdImmediately},on:{"update:mdDate":function(e){t.localDate=e},"update:md-date":function(e){t.localDate=e},"md-closed":t.toggleDialog}}):t._e()],1),t._v(" "),n("md-overlay",{staticClass:"md-datepicker-overlay",attrs:{"md-fixed":"","md-active":t.showDialog},on:{click:t.toggleDialog}})],2)},a=[],i={render:r,staticRenderFns:a};e.a=i},36:function(t,e){},37:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;return(t._self._c||e)("i",{staticClass:"md-svg-loader",domProps:{innerHTML:t._s(t.html)}})},a=[],i={render:r,staticRenderFns:a};e.a=i},38:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.mdSrc?n("md-svg-loader",{staticClass:"md-icon md-icon-image",class:[t.$mdActiveTheme],attrs:{"md-src":t.mdSrc},on:{"md-loaded":function(e){return t.$emit("md-loaded")}}}):n("i",{staticClass:"md-icon md-icon-font",class:[t.$mdActiveTheme]},[t._t("default")],2)},a=[],i={render:r,staticRenderFns:a};e.a=i},4:function(t,e,n){"use strict";var r,a,i,o,s;Object.defineProperty(e,"__esModule",{value:!0}),r=n(2),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),i=null,o=null,s=null,e.default=new a.default({data:function(){return{prefix:"md-theme-",theme:"default",enabled:!0,metaColors:!1}},computed:{themeTarget:function(){return!this.$isServer&&document.documentElement},fullThemeName:function(){return this.getThemeName()}},watch:{enabled:{immediate:!0,handler:function(){var t=this.fullThemeName,e=this.themeTarget,n=this.enabled;e&&(n?(e.classList.add(t),this.metaColors&&this.setHtmlMetaColors(t)):(e.classList.remove(t),this.metaColors&&this.setHtmlMetaColors()))}},theme:function(t,e){var n=this.getThemeName,r=this.themeTarget;t=n(t),r.classList.remove(n(e)),r.classList.add(t),this.metaColors&&this.setHtmlMetaColors(t)},metaColors:function(t){t?this.setHtmlMetaColors(this.fullThemeName):this.setHtmlMetaColors()}},methods:{getAncestorTheme:function(t){var e,n=this;return t?(e=t.mdTheme,(function t(r){if(r){var a=r.mdTheme,i=r.$parent;return a&&a!==e?a:t(i)}return n.theme})(t.$parent)):null},getThemeName:function(t){var e=t||this.theme;return this.prefix+e},setMicrosoftColors:function(t){i&&i.setAttribute("content",t)},setThemeColors:function(t){o&&o.setAttribute("content",t)},setMaskColors:function(t){s&&s.setAttribute("color",t)},setHtmlMetaColors:function(t){var e,n="#fff";t&&(e=window.getComputedStyle(document.documentElement),n=e.getPropertyValue("--"+t+"-primary")),n&&(this.setMicrosoftColors(n),this.setThemeColors(n),this.setMaskColors(n))}},mounted:function(){var t=this;i=document.querySelector('[name="msapplication-TileColor"]'),o=document.querySelector('[name="theme-color"]'),s=document.querySelector('[rel="mask-icon"]'),this.enabled&&this.metaColors&&window.addEventListener("load",(function(){t.setHtmlMetaColors(t.fullThemeName)}))}})},41:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s,u,c,l;Object.defineProperty(e,"__esModule",{value:!0}),a=Object.assign||function(t){var e,n,r;for(e=1;e<arguments.length;e++){n=arguments[e];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},i=n(68),o=r(i),s=n(6),u=r(s),c=n(28),l=r(c),e.default={name:"MdPopover",abstract:!0,components:{MdPortal:l.default},props:{mdActive:Boolean,mdSettings:{type:Object,default:function(){return{}}}},data:function(){return{popperInstance:null,originalParentEl:null,shouldRender:!1,shouldActivate:!1}},computed:{popoverClasses:function(){return this.shouldActivate?"md-active":this.shouldRender?"md-rendering":void 0}},watch:{mdActive:{immediate:!0,handler:function(t){this.shouldRender=t,t?this.bindPopper():this.shouldActivate=!1}},mdSettings:function(){this.popperInstance&&this.createPopper()}},methods:{getPopperOptions:function(){var t=this;return{placement:"bottom",modifiers:{preventOverflow:{boundariesElement:"viewport",padding:16},computeStyle:{gpuAcceleration:!1}},onCreate:function(){t.shouldActivate=!0,t.$emit("md-active")}}},setOriginalParent:function(t){this.originalParentEl||(this.originalParentEl=t)},killPopper:function(){this.popperInstance&&(this.popperInstance.destroy(),this.popperInstance=null)},bindPopper:function(){var t=this;this.$nextTick().then((function(){t.originalParentEl&&t.createPopper()}))},createPopper:function(){if(this.mdSettings){var t=(0,u.default)(this.getPopperOptions(),this.mdSettings);this.$el.nodeType!==Node.COMMENT_NODE&&(this.popperInstance=new o.default(this.originalParentEl,this.$el,t))}},resetPopper:function(){this.popperInstance&&(this.killPopper(),this.createPopper())}},beforeDestroy:function(){this.killPopper()},mounted:function(){this.resetPopper()},render:function(t){return t(l.default,{props:a({},this.$attrs),on:a({},this.$listeners,{"md-initial-parent":this.setOriginalParent,"md-destroy":this.killPopper})},this.$slots.default)}}},43:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=Object.assign||function(t){var e,n,r;for(e=1;e<arguments.length;e++){n=arguments[e];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t};e.default={props:{value:{},placeholder:String,name:String,maxlength:[String,Number],readonly:Boolean,required:Boolean,disabled:Boolean,mdCounter:[String,Number]},data:function(){return{localValue:this.value,textareaHeight:!1}},computed:{model:{get:function(){return this.localValue},set:function(t){var e=this;"inputevent"!==(""+t.constructor).match(/function (\w*)/)[1].toLowerCase()&&this.$nextTick((function(){e.localValue=t}))}},clear:function(){return this.MdField.clear},attributes:function(){return r({},this.$attrs,{type:this.type,id:this.id,name:this.name,disabled:this.disabled,required:this.required,placeholder:this.placeholder,readonly:this.readonly,maxlength:this.maxlength})}},watch:{model:function(){this.setFieldValue()},clear:function(t){t&&this.clearField()},placeholder:function(){this.setPlaceholder()},disabled:function(){this.setDisabled()},required:function(){this.setRequired()},maxlength:function(){this.setMaxlength()},mdCounter:function(){this.setMaxlength()},localValue:function(t){this.$emit("input",t)},value:function(t){this.localValue=t}},methods:{clearField:function(){this.$el.value="",this.model="",this.setFieldValue()},setLabelFor:function(){var t,e;this.$el.parentNode&&(t=this.$el.parentNode.querySelector("label"))&&(!(e=t.getAttribute("for"))||e.indexOf("md-")>=0)&&t.setAttribute("for",this.id)},setFieldValue:function(){this.MdField.value=this.model},setPlaceholder:function(){this.MdField.placeholder=!!this.placeholder},setDisabled:function(){this.MdField.disabled=!!this.disabled},setRequired:function(){this.MdField.required=!!this.required},setMaxlength:function(){this.mdCounter?this.MdField.counter=parseInt(this.mdCounter,10):this.MdField.maxlength=parseInt(this.maxlength,10)},onFocus:function(){this.MdField.focused=!0},onBlur:function(){this.MdField.focused=!1}},created:function(){this.setFieldValue(),this.setPlaceholder(),this.setDisabled(),this.setRequired(),this.setMaxlength()},mounted:function(){this.setLabelFor()}}},5:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){var e={};return a.default.util.defineReactive(e,"reactive",t),e.reactive},r=n(2),a=(function(t){return t&&t.__esModule?t:{default:t}})(r)},50:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s,u,c,l,d;Object.defineProperty(e,"__esModule",{value:!0}),a=n(1),i=r(a),o=n(64),s=r(o),u=n(88),c=r(u),l=n(90),d=r(l),e.default=new i.default({name:"MdField",components:{MdClearIcon:s.default,MdPasswordOffIcon:c.default,MdPasswordOnIcon:d.default},props:{mdInline:Boolean,mdClearable:Boolean,mdCounter:{type:Boolean,default:!0},mdTogglePassword:{type:Boolean,default:!0}},data:function(){return{showPassword:!1,MdField:{value:null,focused:!1,highlighted:!1,disabled:!1,required:!1,placeholder:!1,textarea:!1,autogrow:!1,maxlength:null,counter:null,password:null,togglePassword:!1,clear:!1,file:!1}}},provide:function(){return{MdField:this.MdField}},computed:{stringValue:function(){return(this.MdField.value||0===this.MdField.value)&&""+this.MdField.value},hasCounter:function(){return this.mdCounter&&(this.MdField.maxlength||this.MdField.counter)},hasPasswordToggle:function(){return this.mdTogglePassword&&this.MdField.password},hasValue:function(){return this.stringValue&&this.stringValue.length>0},valueLength:function(){return this.stringValue?this.stringValue.length:0},fieldClasses:function(){return{"md-inline":this.mdInline,"md-clearable":this.mdClearable,"md-focused":this.MdField.focused,"md-highlight":this.MdField.highlighted,"md-disabled":this.MdField.disabled,"md-required":this.MdField.required,"md-has-value":this.hasValue,"md-has-placeholder":this.MdField.placeholder,"md-has-textarea":this.MdField.textarea,"md-has-password":this.MdField.password,"md-has-file":this.MdField.file,"md-has-select":this.MdField.select,"md-autogrow":this.MdField.autogrow}}},methods:{clearInput:function(){var t=this;this.MdField.clear=!0,this.$emit("md-clear"),this.$nextTick().then((function(){t.MdField.clear=!1}))},togglePassword:function(){this.MdField.togglePassword=!this.MdField.togglePassword},onBlur:function(){this.MdField.highlighted=!1}}})},51:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(14),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdClearIcon",components:{MdIcon:a.default}}},52:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(14),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdPasswordOffIcon",components:{MdIcon:a.default}}},527:function(t,e,n){t.exports=n(326)},53:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(14),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdPasswordOnIcon",components:{MdIcon:a.default}}},54:function(t,e,n){"use strict";var r,a,i,o,s,u,c,l,d,f;Object.defineProperty(e,"__esModule",{value:!0}),r=n(55),a=n.n(r);for(i in r)"default"!==i&&(function(t){n.d(e,t,(function(){return r[t]}))})(i);o=n(93),s=n(0),u=!1,c=null,l=null,d=null,f=s(a.a,o.a,u,c,l,d),e.default=f.exports},55:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s,u,c,l;Object.defineProperty(e,"__esModule",{value:!0}),a=Object.assign||function(t){var e,n,r;for(e=1;e<arguments.length;e++){n=arguments[e];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},i=n(1),o=r(i),s=n(12),u=r(s),c=n(43),l=r(c),e.default=new o.default({name:"MdInput",mixins:[l.default],inject:["MdField"],props:{id:{type:String,default:function(){return"md-input-"+(0,u.default)()}},type:{type:String,default:"text"}},computed:{toggleType:function(){return this.MdField.togglePassword},isPassword:function(){return"password"===this.type},listeners:function(){var t=a({},this.$listeners);return delete t.input,t}},watch:{type:function(t){this.setPassword(this.isPassword)},toggleType:function(t){t?this.setTypeText():this.setTypePassword()}},methods:{setPassword:function(t){this.MdField.password=t,this.MdField.togglePassword=!1},setTypePassword:function(){this.$el.type="password"},setTypeText:function(){this.$el.type="text"}},created:function(){this.setPassword(this.isPassword)},beforeDestroy:function(){this.setPassword(!1)}})},56:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(28),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdOverlay",components:{MdPortal:a.default},props:{mdActive:Boolean,mdAttachToParent:Boolean,mdFixed:Boolean},computed:{overlayClasses:function(){return{"md-fixed":this.mdFixed}}}}},57:function(t,e,n){"use strict";function r(t){n(67)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(41),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(0),u=null,c=!1,l=r,d=null,f=null,h=s(i.a,u,c,l,d,f),e.default=h.exports},59:function(t,e,n){"use strict";function r(t){n(95)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(56),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(96),u=n(0),c=!1,l=r,d=null,f=null,h=u(i.a,s.a,c,l,d,f),e.default=h.exports},6:function(t,e,n){!(function(e,n){t.exports=n()})(0,(function(){"use strict";function t(t){return!!t&&"object"==typeof t}function e(t){var e=Object.prototype.toString.call(t);return"[object RegExp]"===e||"[object Date]"===e||n(t)}function n(t){return t.$$typeof===h}function r(t){return Array.isArray(t)?[]:{}}function a(t,e){return!1!==e.clone&&e.isMergeableObject(t)?l(r(t),t,e):t}function i(t,e,n){return t.concat(e).map((function(t){return a(t,n)}))}function o(t,e){if(!e.customMerge)return l;var n=e.customMerge(t);return"function"==typeof n?n:l}function s(t){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(t).filter((function(e){return t.propertyIsEnumerable(e)})):[]}function u(t){return Object.keys(t).concat(s(t))}function c(t,e,n){var r={};return n.isMergeableObject(t)&&u(t).forEach((function(e){r[e]=a(t[e],n)})),u(e).forEach((function(i){n.isMergeableObject(e[i])&&t[i]?r[i]=o(i,n)(t[i],e[i],n):r[i]=a(e[i],n)})),r}function l(t,e,n){var r,o,s;return n=n||{},n.arrayMerge=n.arrayMerge||i,n.isMergeableObject=n.isMergeableObject||d,r=Array.isArray(e),o=Array.isArray(t),s=r===o,s?r?n.arrayMerge(t,e,n):c(t,e,n):a(e,n)}var d=function(n){return t(n)&&!e(n)},f="function"==typeof Symbol&&Symbol.for,h=f?Symbol.for("react.element"):60103;return l.all=function(t,e){if(!Array.isArray(t))throw Error("first argument should be an array");return t.reduce((function(t,n){return l(t,n,e)}),{})},l}))},60:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(2),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default={name:"MdFocusTrap",abstract:!0,methods:{setFocus:function(){var t=this;window.setTimeout((function(){t.$el.tagName&&(t.$el.setAttribute("tabindex","-1"),t.$el.focus())}),20)}},mounted:function(){this.setFocus()},render:function(){try{var t=this.$slots.default;if(!t)return null;if(t.length>1)throw Error();return t[0]}catch(t){a.default.util.warn("MdFocusTrap can only render one, and exactly one child component.",this)}return null}}},63:function(t,e,n){"use strict";function r(t){n(86)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(50),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(92),u=n(0),c=!1,l=r,d=null,f=null,h=u(i.a,s.a,c,l,d,f),e.default=h.exports},64:function(t,e,n){"use strict";var r,a,i,o,s,u,c,l,d,f;Object.defineProperty(e,"__esModule",{value:!0}),r=n(51),a=n.n(r);for(i in r)"default"!==i&&(function(t){n.d(e,t,(function(){return r[t]}))})(i);o=n(87),s=n(0),u=!1,c=null,l=null,d=null,f=s(a.a,o.a,u,c,l,d),e.default=f.exports},65:function(t,e,n){"use strict";function r(t){var e,n,r,o;return Object(i.a)(1,arguments),e=1,n=Object(a.a)(t),r=n.getUTCDay(),o=(r<e?7:0)+r-e,n.setUTCDate(n.getUTCDate()-o),n.setUTCHours(0,0,0,0),n}var a,i;e.a=r,a=n(10),i=n(8)},66:function(t,e,n){"use strict";function r(t,e){var n,r,s,u,c,l,d,f;if(Object(o.a)(1,arguments),n=e||{},r=n.locale,s=r&&r.options&&r.options.weekStartsOn,u=null==s?0:Object(a.a)(s),!((c=null==n.weekStartsOn?u:Object(a.a)(n.weekStartsOn))>=0&&c<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");return l=Object(i.a)(t),d=l.getUTCDay(),f=(d<c?7:0)+d-c,l.setUTCDate(l.getUTCDate()-f),l.setUTCHours(0,0,0,0),l}var a,i,o;e.a=r,a=n(18),i=n(10),o=n(8)},67:function(t,e){},68:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(t){function n(t){var e=!1;return function(){e||(e=!0,window.Promise.resolve().then((function(){e=!1,t()})))}}function r(t){var e=!1;return function(){e||(e=!0,setTimeout((function(){e=!1,t()}),ft))}}function a(t){var e={};return t&&"[object Function]"===e.toString.call(t)}function i(t,e){var n,r;return 1!==t.nodeType?[]:(n=t.ownerDocument.defaultView,r=n.getComputedStyle(t,null),e?r[e]:r)}function o(t){return"HTML"===t.nodeName?t:t.parentNode||t.host}function s(t){if(!t)return document.body;switch(t.nodeName){case"HTML":case"BODY":return t.ownerDocument.body;case"#document":return t.body}var e=i(t),n=e.overflow,r=e.overflowX;return/(auto|scroll|overlay)/.test(n+e.overflowY+r)?t:s(o(t))}function u(t){return t&&t.referenceNode?t.referenceNode:t}function c(t){return 11===t?pt:10===t?gt:pt||gt}function l(t){var e,n,r;if(!t)return document.documentElement;for(e=c(10)?document.body:null,n=t.offsetParent||null;n===e&&t.nextElementSibling;)n=(t=t.nextElementSibling).offsetParent;return r=n&&n.nodeName,r&&"BODY"!==r&&"HTML"!==r?-1!==["TH","TD","TABLE"].indexOf(n.nodeName)&&"static"===i(n,"position")?l(n):n:t?t.ownerDocument.documentElement:document.documentElement}function d(t){var e=t.nodeName;return"BODY"!==e&&("HTML"===e||l(t.firstElementChild)===t)}function f(t){return null!==t.parentNode?f(t.parentNode):t}function h(t,e){var n,r,a,i,o,s;return t&&t.nodeType&&e&&e.nodeType?(n=t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING,r=n?t:e,a=n?e:t,i=document.createRange(),i.setStart(r,0),i.setEnd(a,0),o=i.commonAncestorContainer,t!==o&&e!==o||r.contains(a)?d(o)?o:l(o):(s=f(t),s.host?h(s.host,e):h(t,f(e).host))):document.documentElement}function m(t){var e,n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"top",a="top"===r?"scrollTop":"scrollLeft",i=t.nodeName;return"BODY"===i||"HTML"===i?(e=t.ownerDocument.documentElement,n=t.ownerDocument.scrollingElement||e,n[a]):t[a]}function p(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=m(e,"top"),a=m(e,"left"),i=n?-1:1;return t.top+=r*i,t.bottom+=r*i,t.left+=a*i,t.right+=a*i,t}function g(t,e){var n="x"===e?"Left":"Top",r="Left"===n?"Right":"Bottom";return parseFloat(t["border"+n+"Width"])+parseFloat(t["border"+r+"Width"])}function v(t,e,n,r){return Math.max(e["offset"+t],e["scroll"+t],n["client"+t],n["offset"+t],n["scroll"+t],c(10)?parseInt(n["offset"+t])+parseInt(r["margin"+("Height"===t?"Top":"Left")])+parseInt(r["margin"+("Height"===t?"Bottom":"Right")]):0)}function b(t){var e=t.body,n=t.documentElement,r=c(10)&&getComputedStyle(n);return{height:v("Height",e,n,r),width:v("Width",e,n,r)}}function w(t){return yt({},t,{right:t.left+t.width,bottom:t.top+t.height})}function y(t){var e,n,r,a,o,s,u,l,d,f={};try{c(10)?(f=t.getBoundingClientRect(),e=m(t,"top"),n=m(t,"left"),f.top+=e,f.left+=n,f.bottom+=e,f.right+=n):f=t.getBoundingClientRect()}catch(t){}return r={left:f.left,top:f.top,width:f.right-f.left,height:f.bottom-f.top},a="HTML"===t.nodeName?b(t.ownerDocument):{},o=a.width||t.clientWidth||r.width,s=a.height||t.clientHeight||r.height,u=t.offsetWidth-o,l=t.offsetHeight-s,(u||l)&&(d=i(t),u-=g(d,"x"),l-=g(d,"y"),r.width-=u,r.height-=l),w(r)}function M(t,e){var n,r,a,o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],u=c(10),l="HTML"===e.nodeName,d=y(t),f=y(e),h=s(t),m=i(e),g=parseFloat(m.borderTopWidth),v=parseFloat(m.borderLeftWidth);return o&&l&&(f.top=Math.max(f.top,0),f.left=Math.max(f.left,0)),n=w({top:d.top-f.top-g,left:d.left-f.left-v,width:d.width,height:d.height}),n.marginTop=0,n.marginLeft=0,!u&&l&&(r=parseFloat(m.marginTop),a=parseFloat(m.marginLeft),n.top-=g-r,n.bottom-=g-r,n.left-=v-a,n.right-=v-a,n.marginTop=r,n.marginLeft=a),(u&&!o?e.contains(h):e===h&&"BODY"!==h.nodeName)&&(n=p(n,e)),n}function T(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=t.ownerDocument.documentElement,r=M(t,n),a=Math.max(n.clientWidth,window.innerWidth||0),i=Math.max(n.clientHeight,window.innerHeight||0),o=e?0:m(n),s=e?0:m(n,"left");return w({top:o-r.top+r.marginTop,left:s-r.left+r.marginLeft,width:a,height:i})}function D(t){var e,n=t.nodeName;return"BODY"!==n&&"HTML"!==n&&("fixed"===i(t,"position")||!!(e=o(t))&&D(e))}function O(t){if(!t||!t.parentElement||c())return document.documentElement;for(var e=t.parentElement;e&&"none"===i(e,"transform");)e=e.parentElement;return e||document.documentElement}function x(t,e,n,r){var a,i,c,l,d,f,m=arguments.length>4&&void 0!==arguments[4]&&arguments[4],p={top:0,left:0},g=m?O(t):h(t,u(e));return"viewport"===r?p=T(g,m):(a=void 0,"scrollParent"===r?(a=s(o(e)),"BODY"===a.nodeName&&(a=t.ownerDocument.documentElement)):a="window"===r?t.ownerDocument.documentElement:r,i=M(a,g,m),"HTML"!==a.nodeName||D(g)?p=i:(c=b(t.ownerDocument),l=c.height,d=c.width,p.top+=i.top-i.marginTop,p.bottom=l+i.top,p.left+=i.left-i.marginLeft,p.right=d+i.left)),n=n||0,f="number"==typeof n,p.left+=f?n:n.left||0,p.top+=f?n:n.top||0,p.right-=f?n:n.right||0,p.bottom-=f?n:n.bottom||0,p}function C(t){return t.width*t.height}function _(t,e,n,r,a){var i,o,s,u,c,l,d=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;return-1===t.indexOf("auto")?t:(i=x(n,r,d,a),o={top:{width:i.width,height:e.top-i.top},right:{width:i.right-e.right,height:i.height},bottom:{width:i.width,height:i.bottom-e.bottom},left:{width:e.left-i.left,height:i.height}},s=Object.keys(o).map((function(t){return yt({key:t},o[t],{area:C(o[t])})})).sort((function(t,e){return e.area-t.area})),u=s.filter((function(t){var e=t.width,r=t.height;return e>=n.clientWidth&&r>=n.clientHeight})),c=u.length>0?u[0].key:s[0].key,l=t.split("-")[1],c+(l?"-"+l:""))}function k(t,e,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return M(n,r?O(e):h(e,u(n)),r)}function j(t){var e=t.ownerDocument.defaultView,n=e.getComputedStyle(t),r=parseFloat(n.marginTop||0)+parseFloat(n.marginBottom||0),a=parseFloat(n.marginLeft||0)+parseFloat(n.marginRight||0);return{width:t.offsetWidth+a,height:t.offsetHeight+r}}function P(t){var e={left:"right",right:"left",bottom:"top",top:"bottom"};return t.replace(/left|right|bottom|top/g,(function(t){return e[t]}))}function E(t,e,n){var r,a,i,o,s,u,c;return n=n.split("-")[0],r=j(t),a={width:r.width,height:r.height},i=-1!==["right","left"].indexOf(n),o=i?"top":"left",s=i?"left":"top",u=i?"height":"width",c=i?"width":"height",a[o]=e[o]+e[u]/2-r[u]/2,a[s]=n===s?e[s]-r[c]:e[P(s)],a}function S(t,e){return Array.prototype.find?t.find(e):t.filter(e)[0]}function F(t,e,n){if(Array.prototype.findIndex)return t.findIndex((function(t){return t[e]===n}));var r=S(t,(function(t){return t[e]===n}));return t.indexOf(r)}function N(t,e,n){return(void 0===n?t:t.slice(0,F(t,"name",n))).forEach((function(t){t.function&&console.warn("`modifier.function` is deprecated, use `modifier.fn`!");var n=t.function||t.fn;t.enabled&&a(n)&&(e.offsets.popper=w(e.offsets.popper),e.offsets.reference=w(e.offsets.reference),e=n(e,t))})),e}function U(){if(!this.state.isDestroyed){var t={instance:this,styles:{},arrowStyles:{},attributes:{},flipped:!1,offsets:{}};t.offsets.reference=k(this.state,this.popper,this.reference,this.options.positionFixed),t.placement=_(this.options.placement,t.offsets.reference,this.popper,this.reference,this.options.modifiers.flip.boundariesElement,this.options.modifiers.flip.padding),t.originalPlacement=t.placement,t.positionFixed=this.options.positionFixed,t.offsets.popper=E(this.popper,t.offsets.reference,t.placement),t.offsets.popper.position=this.options.positionFixed?"fixed":"absolute",t=N(this.modifiers,t),this.state.isCreated?this.options.onUpdate(t):(this.state.isCreated=!0,this.options.onCreate(t))}}function L(t,e){return t.some((function(t){var n=t.name;return t.enabled&&n===e}))}function A(t){var e,n,r,a=[!1,"ms","Webkit","Moz","O"],i=t.charAt(0).toUpperCase()+t.slice(1);for(e=0;e<a.length;e++)if(n=a[e],r=n?""+n+i:t,void 0!==document.body.style[r])return r;return null}function H(){return this.state.isDestroyed=!0,L(this.modifiers,"applyStyle")&&(this.popper.removeAttribute("x-placement"),this.popper.style.position="",this.popper.style.top="",this.popper.style.left="",this.popper.style.right="",this.popper.style.bottom="",this.popper.style.willChange="",this.popper.style[A("transform")]=""),this.disableEventListeners(),this.options.removeOnDestroy&&this.popper.parentNode.removeChild(this.popper),this}function Y(t){var e=t.ownerDocument;return e?e.defaultView:window}function q(t,e,n,r){var a="BODY"===t.nodeName,i=a?t.ownerDocument.defaultView:t;i.addEventListener(e,n,{passive:!0}),a||q(s(i.parentNode),e,n,r),r.push(i)}function $(t,e,n,r){n.updateBound=r,Y(t).addEventListener("resize",n.updateBound,{passive:!0});var a=s(t);return q(a,"scroll",n.updateBound,n.scrollParents),n.scrollElement=a,n.eventsEnabled=!0,n}function B(){this.state.eventsEnabled||(this.state=$(this.reference,this.options,this.state,this.scheduleUpdate))}function I(t,e){return Y(t).removeEventListener("resize",e.updateBound),e.scrollParents.forEach((function(t){t.removeEventListener("scroll",e.updateBound)})),e.updateBound=null,e.scrollParents=[],e.scrollElement=null,e.eventsEnabled=!1,e}function W(){this.state.eventsEnabled&&(cancelAnimationFrame(this.scheduleUpdate),this.state=I(this.reference,this.state))}function R(t){return""!==t&&!isNaN(parseFloat(t))&&isFinite(t)}function V(t,e){Object.keys(e).forEach((function(n){var r="";-1!==["width","height","top","right","bottom","left"].indexOf(n)&&R(e[n])&&(r="px"),t.style[n]=e[n]+r}))}function G(t,e){Object.keys(e).forEach((function(n){!1!==e[n]?t.setAttribute(n,e[n]):t.removeAttribute(n)}))}function z(t){return V(t.instance.popper,t.styles),G(t.instance.popper,t.attributes),t.arrowElement&&Object.keys(t.arrowStyles).length&&V(t.arrowElement,t.arrowStyles),t}function Q(t,e,n,r,a){var i=k(a,e,t,n.positionFixed),o=_(n.placement,i,e,t,n.modifiers.flip.boundariesElement,n.modifiers.flip.padding);return e.setAttribute("x-placement",o),V(e,{position:n.positionFixed?"fixed":"absolute"}),n}function X(t,e){var n=t.offsets,r=n.popper,a=n.reference,i=Math.round,o=Math.floor,s=function(t){return t},u=i(a.width),c=i(r.width),l=-1!==["left","right"].indexOf(t.placement),d=-1!==t.placement.indexOf("-"),f=u%2==c%2,h=u%2==1&&c%2==1,m=e?l||d||f?i:o:s,p=e?i:s;return{left:m(h&&!d&&e?r.left-1:r.left),top:p(r.top),bottom:p(r.bottom),right:m(r.right)}}function J(t,e){var n,r,a,i,o,s,u,c,d,f,h,m,p,g=e.x,v=e.y,b=t.offsets.popper,w=S(t.instance.modifiers,(function(t){return"applyStyle"===t.name})).gpuAcceleration;return void 0!==w&&console.warn("WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!"),n=void 0!==w?w:e.gpuAcceleration,r=l(t.instance.popper),a=y(r),i={position:b.position},o=X(t,window.devicePixelRatio<2||!Mt),s="bottom"===g?"top":"bottom",u="right"===v?"left":"right",c=A("transform"),d=void 0,f=void 0,f="bottom"===s?"HTML"===r.nodeName?-r.clientHeight+o.bottom:-a.height+o.bottom:o.top,d="right"===u?"HTML"===r.nodeName?-r.clientWidth+o.right:-a.width+o.right:o.left,n&&c?(i[c]="translate3d("+d+"px, "+f+"px, 0)",i[s]=0,i[u]=0,i.willChange="transform"):(h="bottom"===s?-1:1,m="right"===u?-1:1,i[s]=f*h,i[u]=d*m,i.willChange=s+", "+u),p={"x-placement":t.placement},t.attributes=yt({},p,t.attributes),t.styles=yt({},i,t.styles),t.arrowStyles=yt({},t.offsets.arrow,t.arrowStyles),t}function K(t,e,n){var r,a,i=S(t,(function(t){return t.name===e})),o=!!i&&t.some((function(t){return t.name===n&&t.enabled&&t.order<i.order}));return o||(r="`"+e+"`",a="`"+n+"`",console.warn(a+" modifier is required by "+r+" modifier in order to work, be sure to include it before "+r+"!")),o}function Z(t,e){var n,r,a,o,s,u,c,l,d,f,h,m,p,g,v,b,y,M;if(!K(t.instance.modifiers,"arrow","keepTogether"))return t;if("string"==typeof(r=e.element)){if(!(r=t.instance.popper.querySelector(r)))return t}else if(!t.instance.popper.contains(r))return console.warn("WARNING: `arrow.element` must be child of its popper element!"),t;return a=t.placement.split("-")[0],o=t.offsets,s=o.popper,u=o.reference,c=-1!==["left","right"].indexOf(a),l=c?"height":"width",d=c?"Top":"Left",f=d.toLowerCase(),h=c?"left":"top",m=c?"bottom":"right",p=j(r)[l],u[m]-p<s[f]&&(t.offsets.popper[f]-=s[f]-(u[m]-p)),u[f]+p>s[m]&&(t.offsets.popper[f]+=u[f]+p-s[m]),t.offsets.popper=w(t.offsets.popper),g=u[f]+u[l]/2-p/2,v=i(t.instance.popper),b=parseFloat(v["margin"+d]),y=parseFloat(v["border"+d+"Width"]),M=g-t.offsets.popper[f]-b-y,M=Math.max(Math.min(s[l]-p,M),0),t.arrowElement=r,t.offsets.arrow=(n={},wt(n,f,Math.round(M)),wt(n,h,""),n),t}function tt(t){return"end"===t?"start":"start"===t?"end":t}function et(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Dt.indexOf(t),r=Dt.slice(n+1).concat(Dt.slice(0,n));return e?r.reverse():r}function nt(t,e){var n,r,a,i,o;if(L(t.instance.modifiers,"inner"))return t;if(t.flipped&&t.placement===t.originalPlacement)return t;switch(n=x(t.instance.popper,t.instance.reference,e.padding,e.boundariesElement,t.positionFixed),r=t.placement.split("-")[0],a=P(r),i=t.placement.split("-")[1]||"",o=[],e.behavior){case Ot.FLIP:o=[r,a];break;case Ot.CLOCKWISE:o=et(r);break;case Ot.COUNTERCLOCKWISE:o=et(r,!0);break;default:o=e.behavior}return o.forEach((function(s,u){var c,l,d,f,h,m,p,g,v,b,w,y,M;if(r!==s||o.length===u+1)return t;r=t.placement.split("-")[0],a=P(r),c=t.offsets.popper,l=t.offsets.reference,d=Math.floor,f="left"===r&&d(c.right)>d(l.left)||"right"===r&&d(c.left)<d(l.right)||"top"===r&&d(c.bottom)>d(l.top)||"bottom"===r&&d(c.top)<d(l.bottom),h=d(c.left)<d(n.left),m=d(c.right)>d(n.right),p=d(c.top)<d(n.top),g=d(c.bottom)>d(n.bottom),v="left"===r&&h||"right"===r&&m||"top"===r&&p||"bottom"===r&&g,b=-1!==["top","bottom"].indexOf(r),w=!!e.flipVariations&&(b&&"start"===i&&h||b&&"end"===i&&m||!b&&"start"===i&&p||!b&&"end"===i&&g),y=!!e.flipVariationsByContent&&(b&&"start"===i&&m||b&&"end"===i&&h||!b&&"start"===i&&g||!b&&"end"===i&&p),M=w||y,(f||v||M)&&(t.flipped=!0,(f||v)&&(r=o[u+1]),M&&(i=tt(i)),t.placement=r+(i?"-"+i:""),t.offsets.popper=yt({},t.offsets.popper,E(t.instance.popper,t.offsets.reference,t.placement)),t=N(t.instance.modifiers,t,"flip"))})),t}function rt(t){var e=t.offsets,n=e.popper,r=e.reference,a=t.placement.split("-")[0],i=Math.floor,o=-1!==["top","bottom"].indexOf(a),s=o?"right":"bottom",u=o?"left":"top",c=o?"width":"height";return n[s]<i(r[u])&&(t.offsets.popper[u]=i(r[u])-n[c]),n[u]>i(r[s])&&(t.offsets.popper[u]=i(r[s])),t}function at(t,e,n,r){var a,i,o=t.match(/((?:\-|\+)?\d*\.?\d*)(.*)/),s=+o[1],u=o[2];if(!s)return t;if(0===u.indexOf("%")){switch(a=void 0,u){case"%p":a=n;break;case"%":case"%r":default:a=r}return i=w(a),i[e]/100*s}return"vh"===u||"vw"===u?(void 0,("vh"===u?Math.max(document.documentElement.clientHeight,window.innerHeight||0):Math.max(document.documentElement.clientWidth,window.innerWidth||0))/100*s):s}function it(t,e,n,r){var a,i,o=[0,0],s=-1!==["right","left"].indexOf(r),u=t.split(/(\+|\-)/).map((function(t){return t.trim()})),c=u.indexOf(S(u,(function(t){return-1!==t.search(/,|\s/)})));return u[c]&&-1===u[c].indexOf(",")&&console.warn("Offsets separated by white space(s) are deprecated, use a comma (,) instead."),a=/\s*,\s*|\s+/,i=-1!==c?[u.slice(0,c).concat([u[c].split(a)[0]]),[u[c].split(a)[1]].concat(u.slice(c+1))]:[u],i=i.map((function(t,r){var a=(1===r?!s:s)?"height":"width",i=!1;return t.reduce((function(t,e){return""===t[t.length-1]&&-1!==["+","-"].indexOf(e)?(t[t.length-1]=e,i=!0,t):i?(t[t.length-1]+=e,i=!1,t):t.concat(e)}),[]).map((function(t){return at(t,a,e,n)}))})),i.forEach((function(t,e){t.forEach((function(n,r){R(n)&&(o[e]+=n*("-"===t[r-1]?-1:1))}))})),o}function ot(t,e){var n=e.offset,r=t.placement,a=t.offsets,i=a.popper,o=a.reference,s=r.split("-")[0],u=void 0;return u=R(+n)?[+n,0]:it(n,i,o,s),"left"===s?(i.top+=u[0],i.left-=u[1]):"right"===s?(i.top+=u[0],i.left+=u[1]):"top"===s?(i.left+=u[0],i.top-=u[1]):"bottom"===s&&(i.left+=u[0],i.top+=u[1]),t.popper=i,t}function st(t,e){var n,r,a,i,o,s,u,c,d,f=e.boundariesElement||l(t.instance.popper);return t.instance.reference===f&&(f=l(f)),n=A("transform"),r=t.instance.popper.style,a=r.top,i=r.left,o=r[n],r.top="",r.left="",r[n]="",s=x(t.instance.popper,t.instance.reference,e.padding,f,t.positionFixed),r.top=a,r.left=i,r[n]=o,e.boundaries=s,u=e.priority,c=t.offsets.popper,d={primary:function(t){var n=c[t];return c[t]<s[t]&&!e.escapeWithReference&&(n=Math.max(c[t],s[t])),wt({},t,n)},secondary:function(t){var n="right"===t?"left":"top",r=c[n];return c[t]>s[t]&&!e.escapeWithReference&&(r=Math.min(c[n],s[t]-("right"===t?c.width:c.height))),wt({},n,r)}},u.forEach((function(t){var e=-1!==["left","top"].indexOf(t)?"primary":"secondary";c=yt({},c,d[e](t))})),t.offsets.popper=c,t}function ut(t){var e,n,r,a,i,o,s,u=t.placement,c=u.split("-")[0],l=u.split("-")[1];return l&&(e=t.offsets,n=e.reference,r=e.popper,a=-1!==["bottom","top"].indexOf(c),i=a?"left":"top",o=a?"width":"height",s={start:wt({},i,n[i]),end:wt({},i,n[i]+n[o]-r[o])},t.offsets.popper=yt({},r,s[l])),t}function ct(t){var e,n;if(!K(t.instance.modifiers,"hide","preventOverflow"))return t;if(e=t.offsets.reference,n=S(t.instance.modifiers,(function(t){return"preventOverflow"===t.name})).boundaries,e.bottom<n.top||e.left>n.right||e.top>n.bottom||e.right<n.left){if(!0===t.hide)return t;t.hide=!0,t.attributes["x-out-of-boundaries"]=""}else{if(!1===t.hide)return t;t.hide=!1,t.attributes["x-out-of-boundaries"]=!1}return t}function lt(t){var e=t.placement,n=e.split("-")[0],r=t.offsets,a=r.popper,i=r.reference,o=-1!==["left","right"].indexOf(n),s=-1===["top","left"].indexOf(n);return a[o?"left":"top"]=i[n]-(s?a[o?"width":"height"]:0),t.placement=P(e),t.offsets.popper=w(a),t}var dt="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof navigator,ft=(function(){var t,e=["Edge","Trident","Firefox"];for(t=0;t<e.length;t+=1)if(dt&&navigator.userAgent.indexOf(e[t])>=0)return 1;return 0})(),ht=dt&&window.Promise,mt=ht?n:r,pt=dt&&!(!window.MSInputMethodContext||!document.documentMode),gt=dt&&/MSIE 10/.test(navigator.userAgent),vt=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},bt=(function(){function t(t,e){var n,r;for(n=0;n<e.length;n++)r=e[n],r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}})(),wt=function(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t},yt=Object.assign||function(t){var e,n,r;for(e=1;e<arguments.length;e++){n=arguments[e];for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Mt=dt&&/Firefox/i.test(navigator.userAgent),Tt=["auto-start","auto","auto-end","top-start","top","top-end","right-start","right","right-end","bottom-end","bottom","bottom-start","left-end","left","left-start"],Dt=Tt.slice(3),Ot={FLIP:"flip",CLOCKWISE:"clockwise",COUNTERCLOCKWISE:"counterclockwise"},xt={shift:{order:100,enabled:!0,fn:ut},offset:{order:200,enabled:!0,fn:ot,offset:0},preventOverflow:{order:300,enabled:!0,fn:st,priority:["left","right","top","bottom"],padding:5,boundariesElement:"scrollParent"},keepTogether:{order:400,enabled:!0,fn:rt},arrow:{order:500,enabled:!0,fn:Z,element:"[x-arrow]"},flip:{order:600,enabled:!0,fn:nt,behavior:"flip",padding:5,boundariesElement:"viewport",flipVariations:!1,flipVariationsByContent:!1},inner:{order:700,enabled:!1,fn:lt},hide:{order:800,enabled:!0,fn:ct},computeStyle:{order:850,enabled:!0,fn:J,gpuAcceleration:!0,x:"bottom",y:"right"},applyStyle:{order:900,enabled:!0,fn:z,onLoad:Q,gpuAcceleration:void 0}},Ct={placement:"bottom",positionFixed:!1,eventsEnabled:!0,removeOnDestroy:!1,onCreate:function(){},onUpdate:function(){},modifiers:xt},_t=(function(){function t(e,n){var r,i=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};vt(this,t),this.scheduleUpdate=function(){return requestAnimationFrame(i.update)},this.update=mt(this.update.bind(this)),this.options=yt({},t.Defaults,o),this.state={isDestroyed:!1,isCreated:!1,scrollParents:[]},this.reference=e&&e.jquery?e[0]:e,this.popper=n&&n.jquery?n[0]:n,this.options.modifiers={},Object.keys(yt({},t.Defaults.modifiers,o.modifiers)).forEach((function(e){i.options.modifiers[e]=yt({},t.Defaults.modifiers[e]||{},o.modifiers?o.modifiers[e]:{})})),this.modifiers=Object.keys(this.options.modifiers).map((function(t){return yt({name:t},i.options.modifiers[t])})).sort((function(t,e){return t.order-e.order})),this.modifiers.forEach((function(t){t.enabled&&a(t.onLoad)&&t.onLoad(i.reference,i.popper,i.options,t,i.state)})),this.update(),r=this.options.eventsEnabled,r&&this.enableEventListeners(),this.state.eventsEnabled=r}return bt(t,[{key:"update",value:function(){return U.call(this)}},{key:"destroy",value:function(){return H.call(this)}},{key:"enableEventListeners",value:function(){return B.call(this)}},{key:"disableEventListeners",value:function(){return W.call(this)}}]),t})();_t.Utils=("undefined"!=typeof window?window:t).PopperUtils,_t.placements=Tt,_t.Defaults=Ct,e.default=_t}.call(e,n(13))},69:function(t,e,n){"use strict";function r(t){n(156)}var a,i,o,s,u,c,l,d,f,h;Object.defineProperty(e,"__esModule",{value:!0}),a=n(71),i=n.n(a);for(o in a)"default"!==o&&(function(t){n.d(e,t,(function(){return a[t]}))})(o);s=n(157),u=n(0),c=!1,l=r,d=null,f=null,h=u(i.a,s.a,c,l,d,f),e.default=h.exports},7:function(t,e){},71:function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}var a,i,o,s,u,c,l,d;Object.defineProperty(e,"__esModule",{value:!0}),a=n(1),i=r(a),o=n(28),s=r(o),u=n(59),c=r(u),l=n(60),d=r(l),e.default=new i.default({name:"MdDialog",components:{MdPortal:s.default,MdOverlay:c.default,MdFocusTrap:d.default},props:{mdActive:Boolean,mdBackdrop:{type:Boolean,default:!0},mdBackdropClass:{type:String,default:"md-dialog-overlay"},mdCloseOnEsc:{type:Boolean,default:!0},mdClickOutsideToClose:{type:Boolean,default:!0},mdFullscreen:{type:Boolean,default:!0},mdAnimateFromSource:Boolean},computed:{dialogClasses:function(){return{"md-dialog-fullscreen":this.mdFullscreen}}},watch:{mdActive:function(t){var e=this;this.$nextTick().then((function(){t?e.$emit("md-opened"):e.$emit("md-closed")}))}},methods:{closeDialog:function(){this.$emit("update:mdActive",!1)},onClick:function(){this.mdClickOutsideToClose&&this.closeDialog(),this.$emit("md-clicked-outside")},onEsc:function(){this.mdCloseOnEsc&&this.closeDialog()}}})},8:function(t,e,n){"use strict";function r(t,e){if(e.length<t)throw new TypeError(t+" argument"+t>1?"s":" required, but only "+e.length+" present")}e.a=r},86:function(t,e){},87:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(1)},a=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("svg",{attrs:{height:"24",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg"}},[n("path",{attrs:{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}}),t._v(" "),n("path",{attrs:{d:"M0 0h24v24H0z",fill:"none"}})])},function(){var t=this,e=t.$createElement;return(t._self._c||e)("md-icon",{staticClass:"md-icon-image"},[t._m(0)])}],i={render:r,staticRenderFns:a};e.a=i},88:function(t,e,n){"use strict";var r,a,i,o,s,u,c,l,d,f;Object.defineProperty(e,"__esModule",{value:!0}),r=n(52),a=n.n(r);for(i in r)"default"!==i&&(function(t){n.d(e,t,(function(){return r[t]}))})(i);o=n(89),s=n(0),u=!1,c=null,l=null,d=null,f=s(a.a,o.a,u,c,l,d),e.default=f.exports},89:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(0)},a=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-icon",{staticClass:"md-icon-image"},[n("svg",{attrs:{height:"24",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg"}},[n("path",{attrs:{d:"M0 0h24v24H0zm0 0h24v24H0zm0 0h24v24H0zm0 0h24v24H0z",fill:"none"}}),t._v(" "),n("path",{attrs:{d:"M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"}})])])}],i={render:r,staticRenderFns:a};e.a=i},9:function(t,e,n){"use strict";var r,a;Object.defineProperty(e,"__esModule",{value:!0}),r=n(2),a=(function(t){return t&&t.__esModule?t:{default:t}})(r),e.default=function(t,e){return{validator:function(n){return!!e.includes(n)||(a.default.util.warn("The "+t+" prop is invalid. Given value: "+n+". Available options: "+e.join(", ")+".",void 0),!1)}}}},90:function(t,e,n){"use strict";var r,a,i,o,s,u,c,l,d,f;Object.defineProperty(e,"__esModule",{value:!0}),r=n(53),a=n.n(r);for(i in r)"default"!==i&&(function(t){n.d(e,t,(function(){return r[t]}))})(i);o=n(91),s=n(0),u=!1,c=null,l=null,d=null,f=s(a.a,o.a,u,c,l,d),e.default=f.exports},91:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(0)},a=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-icon",{staticClass:"md-icon-image"},[n("svg",{attrs:{height:"24",viewBox:"0 0 24 24",width:"24",xmlns:"http://www.w3.org/2000/svg"}},[n("path",{attrs:{d:"M0 0h24v24H0z",fill:"none"}}),t._v(" "),n("path",{attrs:{d:"M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"}})])])}],i={render:r,staticRenderFns:a};e.a=i},92:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"md-field",class:[t.$mdActiveTheme,t.fieldClasses],on:{blur:t.onBlur}},[t._t("default"),t._v(" "),t.hasCounter?n("span",{staticClass:"md-count"},[t._v(t._s(t.valueLength)+" / "+t._s(t.MdField.maxlength||t.MdField.counter))]):t._e(),t._v(" "),n("transition",{attrs:{name:"md-input-action",appear:""}},[t.hasValue&&t.mdClearable?n("md-button",{staticClass:"md-icon-button md-dense md-input-action md-clear",attrs:{tabindex:"-1",disabled:t.MdField.disabled},on:{click:t.clearInput}},[n("md-clear-icon")],1):t._e()],1),t._v(" "),n("transition",{attrs:{name:"md-input-action",appear:""}},[t.hasPasswordToggle?n("md-button",{staticClass:"md-icon-button md-dense md-input-action md-toggle-password",attrs:{tabindex:"-1"},on:{click:t.togglePassword}},[n(t.MdField.togglePassword?"md-password-on-icon":"md-password-off-icon")],1):t._e()],1)],2)},a=[],i={render:r,staticRenderFns:a};e.a=i},93:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return"checkbox"===t.attributes.type?n("input",t._g(t._b({directives:[{name:"model",rawName:"v-model",value:t.model,expression:"model"}],staticClass:"md-input",attrs:{type:"checkbox"},domProps:{checked:Array.isArray(t.model)?t._i(t.model,null)>-1:t.model},on:{focus:t.onFocus,blur:t.onBlur,change:function(e){var n,r,a=t.model,i=e.target,o=!!i.checked;Array.isArray(a)?(n=null,r=t._i(a,n),i.checked?r<0&&(t.model=a.concat([n])):r>-1&&(t.model=a.slice(0,r).concat(a.slice(r+1)))):t.model=o}}},"input",t.attributes,!1),t.listeners)):"radio"===t.attributes.type?n("input",t._g(t._b({directives:[{name:"model",rawName:"v-model",value:t.model,expression:"model"}],staticClass:"md-input",attrs:{type:"radio"},domProps:{checked:t._q(t.model,null)},on:{focus:t.onFocus,blur:t.onBlur,change:function(e){t.model=null}}},"input",t.attributes,!1),t.listeners)):n("input",t._g(t._b({directives:[{name:"model",rawName:"v-model",value:t.model,expression:"model"}],staticClass:"md-input",attrs:{type:t.attributes.type},domProps:{value:t.model},on:{focus:t.onFocus,blur:t.onBlur,input:function(e){e.target.composing||(t.model=e.target.value)}}},"input",t.attributes,!1),t.listeners))},a=[],i={render:r,staticRenderFns:a};e.a=i},94:function(t,e,n){"use strict";function r(t,e){var n,r,u,c,l,d,f,h,m,p,g;if(Object(s.a)(1,arguments),n=Object(i.a)(t,e),r=n.getUTCFullYear(),u=e||{},c=u.locale,l=c&&c.options&&c.options.firstWeekContainsDate,d=null==l?1:Object(a.a)(l),!((f=null==u.firstWeekContainsDate?d:Object(a.a)(u.firstWeekContainsDate))>=1&&f<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");return h=new Date(0),h.setUTCFullYear(r+1,0,f),h.setUTCHours(0,0,0,0),m=Object(o.a)(h,e),p=new Date(0),p.setUTCFullYear(r,0,f),p.setUTCHours(0,0,0,0),g=Object(o.a)(p,e),n.getTime()>=m.getTime()?r+1:n.getTime()>=g.getTime()?r:r-1}var a,i,o,s;e.a=r,a=n(18),i=n(10),o=n(66),s=n(8)},95:function(t,e){},96:function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("md-portal",{attrs:{"md-attach-to-parent":t.mdAttachToParent}},[n("transition",{attrs:{name:"md-overlay"}},[t.mdActive?n("div",t._g({staticClass:"md-overlay",class:t.overlayClasses},t.$listeners)):t._e()])],1)},a=[],i={render:r,staticRenderFns:a};e.a=i},97:function(t,e,n){"use strict";function r(t){var e,n,r,o;return Object(i.a)(1,arguments),e=Object(a.a)(t),n=e.getFullYear(),r=e.getMonth(),o=new Date(0),o.setFullYear(n,r+1,0),o.setHours(0,0,0,0),o.getDate()}var a,i;Object.defineProperty(e,"__esModule",{value:!0}),e.default=r,a=n(10),i=n(8)}})}));
20,110.166667
120,551
0.690546
fcfbfad4fc6a75c28fd0a9691671445186774dbd
8,238
js
JavaScript
mapbender/src/Mapbender/CoreBundle/Resources/public/mapbender.element.overview.js
agrorural/geoportal
26c87776c7c0aa85c13c7477d0a7ce0260cba2de
[ "MIT" ]
null
null
null
mapbender/src/Mapbender/CoreBundle/Resources/public/mapbender.element.overview.js
agrorural/geoportal
26c87776c7c0aa85c13c7477d0a7ce0260cba2de
[ "MIT" ]
null
null
null
mapbender/src/Mapbender/CoreBundle/Resources/public/mapbender.element.overview.js
agrorural/geoportal
26c87776c7c0aa85c13c7477d0a7ce0260cba2de
[ "MIT" ]
null
null
null
(function($){ $.widget("mapbender.mbOverview", { options: { layerset: [] }, overview: null, layersOrigExtents: {}, mapOrigExtents: {}, startproj: null, /** * Creates the overview */ _create: function(){ if(!Mapbender.checkTarget("mbOverview", this.options.target)){ return; } var self = this; Mapbender.elementRegistry.onElementReady(this.options.target, $.proxy(self._setup, self)); }, /** * Initializes the overview */ _setup: function() { var widget = this; var options = widget.options; var mbMap = $('#' + options.target).data('mapbenderMbMap'); var model = mbMap.model; var element = $(widget.element); var mapMaxExtent = model.mapMaxExtent; var projection = mapMaxExtent.projection; var maxExtent = mapMaxExtent.extent; var overviewLayers = []; var layerSet = Mapbender.configuration.layersets[options.layerset]; var overviewContainer = $('.overviewContainer', widget.element).get(0); widget.mapOrigExtents = { max: { projection: projection, extent: maxExtent } }; widget.startproj = projection; element.addClass(options.anchor); $.each(layerSet.reverse(), function(idx, item) { $.each(item, function(idx2, layerDef) { if(layerDef.type !== "wms") { return; } var wmsLayer = widget.createWmsLayer(layerDef, { isBaseLayer: idx === 0 }); overviewLayers.push(wmsLayer); widget._addOrigLayerExtent(layerDef); }); }); if(!overviewLayers.length){ Mapbender.info(Mapbender.trans("mb.core.overview.nolayer")); return; } var overviewOptions = { layers: overviewLayers, div: overviewContainer, size: new OpenLayers.Size(options.width, options.height), //maximized: widget.options.maximized, mapOptions: { maxExtent: maxExtent, projection: projection, theme: null } }; if(options.fixed){ $.extend(overviewOptions, { minRatio: 1, maxRatio: 1000000000 // ,autoPan: false }); } widget.overview = new OpenLayers.Control.OverviewMap(overviewOptions); mbMap.map.olMap.addControl(widget.overview); $(document).bind('mbmapsrschanged', $.proxy(widget._changeSrs, widget)); element.find('.toggleOverview').bind('click', $.proxy(widget._openClose, widget)); if(!options.maximized){ element.addClass("closed"); } widget._ready(); }, /** * Create WMS layer by definition * @param layerDefinition * @param options * @returns {*} */ createWmsLayer: function(layerDefinition, options) { var ls = ""; var layerConfiguration = layerDefinition.configuration; var layerOptions = layerConfiguration.options; var layers = Mapbender.source[layerDefinition.type].getLayersList(layerDefinition, layerConfiguration.children[0], true); var url = layerOptions.url; for (var i = 0; i < layers.layers.length; i++) { ls += layers.layers[i].options.name !== "" ? "," + layers.layers[i].options.name : ""; } // Add proxy if needed if(layerOptions.proxy) { url = OpenLayers.ProxyHost + encodeURIComponent(url); } return new OpenLayers.Layer.WMS(layerDefinition.title, url, { version: layerOptions.version, layers: ls.substring(1), format: layerOptions.format, transparent: layerOptions.transparent }, $.extend({ opacity: layerOptions.opacity, singleTile: true }, options)); }, /** * Opens/closes the overview element */ _openClose: function(event){ var self = this; $(this.element).toggleClass('closed'); window.setTimeout(function(){ if(!$(self.element).hasClass('closed')){ self.overview.ovmap.updateSize(); } }, 300); }, /** * Transforms an extent into 'projection' projection. */ _transformExtent: function(extentObj, projection){ if(extentObj.extent != null){ if(extentObj.projection.projCode == projection.projCode){ return extentObj.extent.clone(); }else{ var newextent = extentObj.extent.clone(); newextent.transform(extentObj.projection, projection); return newextent; } }else{ return null; } }, /** * Cahnges the overview srs */ _changeSrs: function(event, srs) { var widget = this; var overview = widget.overview; var ovMap = overview.ovmap; var oldProj = ovMap.projection; var center = ovMap.getCenter().transform(oldProj, srs.projection); ovMap.projection = srs.projection; ovMap.displayProjection = srs.projection; ovMap.units = srs.projection.proj.units; ovMap.maxExtent = widget._transformExtent(widget.mapOrigExtents.max, srs.projection); $.each(ovMap.layers, function(idx, layer) { layer.projection = srs.projection; layer.units = srs.projection.proj.units; if(!widget.layersOrigExtents[layer.id]) { widget._addOrigLayerExtent(layer); } if(layer.maxExtent && layer.maxExtent != widget.overview.ovmap.maxExtent) { layer.maxExtent = widget._transformExtent(widget.layersOrigExtents[layer.id].max, srs.projection); } layer.initResolutions(); }); overview.update(); ovMap.setCenter(center, ovMap.getZoom(), false, true); }, /** * Adds a layer's original extent into the widget layersOrigExtent. */ _addOrigLayerExtent: function(layer) { var widget = this; var extents = widget.layersOrigExtents; if(layer.olLayer) { layer = layer.olLayer; } if(!extents[layer.id]) { extents[layer.id] = { max: { projection: widget.startproj, extent: layer.maxExtent ? layer.maxExtent.clone() : null } }; } }, /** * Puts callback on ready * @param {function} callback Function this runs after widget is ready */ ready: function(callback){ if(this.readyState === true){ callback(); }else{ this.readyCallbacks.push(callback); } }, /** * Runs if widget is ready */ _ready: function() { var widget = this; widget._trigger('ready'); for (var callback in widget.readyCallbacks) { callback(); delete(widget.readyCallbacks[callback]); } widget.readyState = true; } }); })(jQuery);
33.487805
133
0.488711
fcfc06703f6332de655ebb2b112c7d8f74dec21e
13,299
js
JavaScript
test/finance.unit.js
dangus21/blaver
76a48f78ab822a738614205a24ee53ef808f85af
[ "MIT-feh", "MIT" ]
109
2022-01-07T04:30:51.000Z
2022-02-24T19:29:16.000Z
test/finance.unit.js
dangus21/blaver
76a48f78ab822a738614205a24ee53ef808f85af
[ "MIT-feh", "MIT" ]
12
2022-01-07T20:31:54.000Z
2022-01-14T22:50:08.000Z
test/finance.unit.js
dangus21/blaver
76a48f78ab822a738614205a24ee53ef808f85af
[ "MIT-feh", "MIT" ]
9
2022-01-07T11:47:56.000Z
2022-01-15T12:57:51.000Z
if (typeof module !== 'undefined') { var assert = require('assert'); var sinon = require('sinon'); var blaver = require('../index'); } blaver.seed(1234); describe('finance.js', function () { describe('account( length )', function () { it('should supply a default length if no length is passed', function () { var account = blaver.finance.account(); var expected = 8; var actual = account.length; assert.strictEqual(actual, expected, 'The expected default account length is ' + expected + ' but it was ' + actual); }); it('should supply a length if a length is passed', function () { var expected = 9; var account = blaver.finance.account(expected); var actual = account.length; assert.strictEqual(actual, expected, 'The expected default account length is ' + expected + ' but it was ' + actual); }); it('should supply a default length if a zero is passed', function () { var expected = 8; var account = blaver.finance.account(0); var actual = account.length; assert.strictEqual(actual, expected, 'The expected default account length is ' + expected + ' but it was ' + actual); }); }); describe('accountName()', function () { it("should return an account name", function () { var actual = blaver.finance.accountName(); assert.ok(actual); }); }); describe('routingNumber()', function () { it("should return a routing number", function () { var actual = blaver.finance.routingNumber(); assert.ok(actual); }); }); describe('mask( length, parens, ellipsis )', function () { it("should set a default length", function () { var expected = 4; //default account mask length var mask = blaver.finance.mask(null, false, false); var actual = mask.length; assert.strictEqual(actual, expected, 'The expected default mask length is ' + expected + ' but it was ' + actual); }); it("should set a specified length", function () { var expected = blaver.datatype.number(20); expected = (expected == 0 || !expected || typeof expected == 'undefined') ? 4 : expected; var mask = blaver.finance.mask(expected, false, false); var actual = mask.length; //picks 4 if the random number generator picks 0 assert.strictEqual(actual, expected, 'The expected default mask length is ' + expected + ' but it was ' + actual); }); it("should set a default length of 4 for a zero value", function () { var expected = 4; blaver.finance.mask(0, false, false); var actual = 4; //picks 4 if the random number generator picks 0 assert.strictEqual(actual, expected, 'The expected default mask length is ' + expected + ' but it was ' + actual); }); it("should by default include parentheses around a partial account number", function () { var expected = true; var mask = blaver.finance.mask(null, null, false); var regexp = new RegExp(/(\(\d{4}?\))/); var actual = regexp.test(mask); assert.strictEqual(actual, expected, 'The expected match for parentheses is ' + expected + ' but it was ' + actual); }); it("should by default include an ellipsis", function () { var expected = true; var mask = blaver.finance.mask(null, false, null); var regexp = new RegExp(/(\.\.\.\d{4})/); var actual = regexp.test(mask); assert.strictEqual(actual, expected, 'The expected match for parentheses is ' + expected + ' but it was ' + actual); }); it("should work when random variables are passed into the arguments", function () { var length = blaver.datatype.number(20); var ellipsis = (length % 2 === 0) ? true : false; var parens = !ellipsis; var mask = blaver.finance.mask(length, ellipsis, parens); assert.ok(mask); }); }); describe('amount(min, max, dec, symbol)', function () { it("should use the default amounts when not passing arguments", function () { var amount = blaver.finance.amount(); assert.ok(amount); assert.strictEqual((amount > 0), true, "the amount should be greater than 0"); assert.strictEqual((amount < 1001), true, "the amount should be greater than 0"); }); it("should use the default decimal location when not passing arguments", function () { var amount = blaver.finance.amount(); var decimal = '.'; var expected = amount.length - 3; var amount = blaver.finance.amount(100, 100, 1); assert.ok(amount); assert.strictEqual(amount , '100.0', "the amount should be equal 100.0"); }); //TODO: add support for more currency and decimal options it("should not include a currency symbol by default", function () { var amount = blaver.finance.amount(); var regexp = new RegExp(/[0-9.]/); var expected = true; var actual = regexp.test(amount); assert.strictEqual(actual, expected, 'The expected match should not include a currency symbol'); }); it("it should handle negative amounts", function () { var amount = blaver.finance.amount(-200, -1); assert.ok(amount); assert.strictEqual((amount < 0), true, "the amount should be greater than 0"); assert.strictEqual((amount > -201), true, "the amount should be greater than 0"); }); it("it should handle argument dec", function () { var amount = blaver.finance.amount(100, 100, 1); assert.ok(amount); assert.strictEqual(amount , "100.0", "the amount should be equal 100.0"); }); it("it should handle argument dec = 0", function () { var amount = blaver.finance.amount(100, 100, 0); assert.ok(amount); assert.strictEqual(amount , '100', "the amount should be equal 100"); }); it("it should return a string", function() { var amount = blaver.finance.amount(100, 100, 0); var typeOfAmount = typeof amount; assert.ok(amount); assert.strictEqual(typeOfAmount , "string", "the amount type should be number"); }); [false, undefined].forEach(function (autoFormat){ it(`should return unformatted if autoformat is ${autoFormat}`, function() { const number = 6000; const amount = blaver.finance.amount(number, number, 0, undefined, autoFormat); assert.strictEqual(amount, number.toString()); }); }); it("should return the number formatted on the current locale", function() { const number = 6000, decimalPlaces = 2; const expected = number.toLocaleString(undefined, {minimumFractionDigits: decimalPlaces}); const amount = blaver.finance.amount(number, number, decimalPlaces, undefined, true); assert.strictEqual(amount, expected); }); }); describe('transactionType()', function () { it("should return a random transaction type", function () { var transactionType = blaver.finance.transactionType(); assert.ok(transactionType); }); }); describe("currencyCode()", function () { it("returns a random currency code with a format", function () { var currencyCode = blaver.finance.currencyCode(); assert.ok(currencyCode.match(/^[A-Z]{3}$/)); }); }); describe("bitcoinAddress()", function(){ it("returns a random bitcoin address", function(){ var bitcoinAddress = blaver.finance.bitcoinAddress(); /** * Note: Although the total length of a Bitcoin address can be 25-33 characters, regex quantifiers only check the preceding token * Therefore we take one from the total length of the address not including the first character ([13]) */ assert.ok(bitcoinAddress.match(/^[A-Z0-9.]{27,34}$/)); }); }); describe("litecoinAddress()", function(){ it("returns a random litecoin address", function(){ var litecoinAddress = blaver.finance.litecoinAddress(); assert.ok(litecoinAddress.match(/^[LM3][1-9a-km-zA-HJ-NP-Z]{25,32}$/)); }); }); describe("ethereumAddress()", function(){ it("returns a random ethereum address", function(){ var ethereumAddress = blaver.finance.ethereumAddress(); assert.ok(ethereumAddress.match(/^(0x)[0-9a-f]{40}$/)); }); }); describe("creditCardNumber()", function(){ var luhnFormula = require("./support/luhnCheck.js"); it("returns a random credit card number", function(){ var number = blaver.finance.creditCardNumber(); number = number.replace(/\D/g,""); // remove formating console.log("version:", process.version, number, number.length); assert.ok(number.length >= 13 && number.length <= 20); assert.ok(number.match(/^[0-9]{13,20}$/)); assert.ok(luhnFormula(number)); }); it("returns a valid credit card number", function(){ assert.ok(luhnFormula(blaver.finance.creditCardNumber(""))); assert.ok(luhnFormula(blaver.finance.creditCardNumber())); assert.ok(luhnFormula(blaver.finance.creditCardNumber())); assert.ok(luhnFormula(blaver.finance.creditCardNumber("visa"))); assert.ok(luhnFormula(blaver.finance.creditCardNumber("mastercard"))); assert.ok(luhnFormula(blaver.finance.creditCardNumber("discover"))); assert.ok(luhnFormula(blaver.finance.creditCardNumber())); assert.ok(luhnFormula(blaver.finance.creditCardNumber())); }); it("returns a correct credit card number when issuer provided", function(){ //TODO: implement checks for each format with regexp var visa = blaver.finance.creditCardNumber("visa"); assert.ok(visa.match(/^4(([0-9]){12}|([0-9]){3}(\-([0-9]){4}){3})$/)); assert.ok(luhnFormula(visa)); var mastercard = blaver.finance.creditCardNumber("mastercard"); assert.ok(mastercard.match(/^(5[1-5]\d{2}|6771)(\-\d{4}){3}$/)); assert.ok(luhnFormula(mastercard)); var discover = blaver.finance.creditCardNumber("discover"); assert.ok(luhnFormula(discover)); var american_express = blaver.finance.creditCardNumber("american_express"); assert.ok(luhnFormula(american_express)); var diners_club = blaver.finance.creditCardNumber("diners_club"); assert.ok(luhnFormula(diners_club)); var jcb = blaver.finance.creditCardNumber("jcb"); assert.ok(luhnFormula(jcb)); var switchC = blaver.finance.creditCardNumber("mastercard"); assert.ok(luhnFormula(switchC)); var solo = blaver.finance.creditCardNumber("solo"); assert.ok(luhnFormula(solo)); var maestro = blaver.finance.creditCardNumber("maestro"); assert.ok(luhnFormula(maestro)); var laser = blaver.finance.creditCardNumber("laser"); assert.ok(luhnFormula(laser)); var instapayment = blaver.finance.creditCardNumber("instapayment"); assert.ok(luhnFormula(instapayment)); }); it("returns custom formated strings",function(){ var number = blaver.finance.creditCardNumber("###-###-##L"); assert.ok(number.match(/^\d{3}\-\d{3}\-\d{3}$/)); assert.ok(luhnFormula(number)); number =blaver.finance.creditCardNumber("234[5-9]#{999}L"); assert.ok(number.match(/^234[5-9]\d{1000}$/)); assert.ok(luhnFormula(number)); }); }); describe("creditCardCVV()", function(){ it("returns a random credit card CVV", function(){ var cvv = blaver.finance.creditCardCVV(); assert.ok(cvv.length === 3); assert.ok(cvv.match(/^[0-9]{3}$/)); }); }); describe("iban()", function () { var ibanLib = require('../lib/iban'); it("returns a random yet formally correct IBAN number", function () { var iban = blaver.finance.iban(); var bban = iban.substring(4) + iban.substring(0, 4); assert.strictEqual(ibanLib.mod97(ibanLib.toDigitString(bban)), 1, "the result should be equal to 1"); }); it("returns a specific and formally correct IBAN number", function () { var iban = blaver.finance.iban(false, "DE"); var bban = iban.substring(4) + iban.substring(0, 4); var countryCode = iban.substring(0, 2); assert.equal(countryCode, "DE"); assert.equal(ibanLib.mod97(ibanLib.toDigitString(bban)), 1, "the result should be equal to 1"); }); it("throws an error if the passed country code is not supported", function () { assert.throws(function() { blaver.finance.iban(false, 'AA');}, /Country code AA not supported/); }); }); describe("bic()", function () { var ibanLib = require('../lib/iban'); it("returns a random yet formally correct BIC number", function () { var bic = blaver.finance.bic(); var expr = new RegExp("^[A-Z]{4}(" + ibanLib.iso3166.join("|") + ")[A-Z2-9][A-NP-Z0-9]([A-Z0-9]{3})?$", "i"); assert.ok(bic.match(expr)); }); }); describe("transactionDescription()", function() { beforeEach(function () { sinon.spy(blaver.helpers, 'createTransaction'); }); afterEach(function () { blaver.helpers.createTransaction.restore(); }); it("returns a random transaction description", function() { var transactionDescription = blaver.finance.transactionDescription(); assert.ok(transactionDescription); assert.ok(blaver.helpers.createTransaction.calledOnce); }); }); });
32.279126
140
0.63704
fcfc1916c6793417a15613cce51ba719810a670c
54
js
JavaScript
test/helpers/EVMRevert.js
jbogacz/react-dapp-boilerplate
41e64e3c5e1bb58ae0ad62dd2e9d2965a9d33d21
[ "MIT" ]
null
null
null
test/helpers/EVMRevert.js
jbogacz/react-dapp-boilerplate
41e64e3c5e1bb58ae0ad62dd2e9d2965a9d33d21
[ "MIT" ]
null
null
null
test/helpers/EVMRevert.js
jbogacz/react-dapp-boilerplate
41e64e3c5e1bb58ae0ad62dd2e9d2965a9d33d21
[ "MIT" ]
null
null
null
// export default 'revert'; module.exports = 'revert';
27
27
0.703704
fcfc42958fafb67ca61efb6a7ef9d5c69b6c9ecf
3,567
js
JavaScript
src/containers/partials/header.js
maidsafe/dev_website
8ee68506449df27161db4501d3a60c02b27cea6c
[ "MIT", "BSD-3-Clause" ]
9
2018-04-25T14:38:30.000Z
2020-05-05T02:09:07.000Z
src/containers/partials/header.js
maidsafe/dev_website
8ee68506449df27161db4501d3a60c02b27cea6c
[ "MIT", "BSD-3-Clause" ]
48
2018-04-26T12:11:56.000Z
2019-11-27T13:48:19.000Z
src/containers/partials/header.js
maidsafe/dev_website
8ee68506449df27161db4501d3a60c02b27cea6c
[ "MIT", "BSD-3-Clause" ]
26
2018-04-25T16:41:07.000Z
2020-05-05T14:18:40.000Z
import React from 'react' import { withSiteData } from 'react-static' import { Link, withRouter } from 'react-router-dom' // import classNames from 'classnames'; import CONST from '../../constants'; class Header extends React.Component { constructor() { super(); this.state = { showMenu: false, appDevNav: false, docsNav: false, dappsNav: false, coreTechNav: false, discoverNav: false, }; this.routes = { APP_DEV: '/start_developing', DOCS: '/docs', DAPPS: '/dapps', CORE_TECH: '/core_technology', DISCOVER: '/discover', PLATFORM_NODEJS: '/platform/nodejs', PLATFORM_RUST: '/platform/rust', PLATFORM_WEB: '/platform/web', PLATFORM_DOTNET: '/platform/dotnet', PLATFORM_XAMARIN: '/platform/xamarin', }; } componentDidMount() { this.setNavActive(); } componentDidUpdate(prevProp) { if (prevProp.location.pathname !== this.props.location.pathname) { this.setNavActive(); } } hideMenu() { if (!this.state.showMenu) { return; } this.setState({ showMenu: false }); } isNavMatch(target) { let route = ''; if (!target) { return; } if (typeof window !== 'undefined') { route = window.location.pathname; } if (typeof target === 'string') { return (route.search(target) !== -1); } return (target.filter((nav) => (route.search(nav) !== -1)).length !== 0); } setNavActive() { this.setState({ appDevNav: this.isNavMatch([this.routes.APP_DEV, this.routes.PLATFORM_NODEJS, this.routes.PLATFORM_WEB]), docsNav: this.isNavMatch(this.routes.DOCS), dappsNav: this.isNavMatch(this.routes.DAPPS), coreTechNav: this.isNavMatch(this.routes.CORE_TECH), discoverNav: this.isNavMatch(this.routes.DISCOVER), }); this.hideMenu(); } render() { const navMenuClasses = classNames({ active: this.state.showMenu }); const headerClasses = classNames({ 'header-fixed': this.props.isScrolling }); return ( <header className={headerClasses}> <div className="brand-logo"> <Link to="/" onClick={() => { this.hideMenu() }}> <span className="images"></span> </Link> </div> <div className="mob-menu" onClick={(e) => { this.setState({ showMenu: !this.state.showMenu }); }}></div> <nav className={navMenuClasses}> <Link className={classNames({ selected: this.state.appDevNav })} to="/start_developing" onClick={() => { this.hideMenu() }}>Start Developing</Link> <Link className={classNames({ selected: this.state.docsNav })} to="/docs" onClick={() => { this.hideMenu() }}>Docs</Link> <Link className={classNames({ selected: this.state.dappsNav })} to="/dapps" onClick={() => { this.hideMenu() }}>DApps</Link> <Link className={classNames({ selected: this.state.coreTechNav })} to="/core_technology" onClick={() => { this.hideMenu() }}>Core Technology</Link> <Link className={classNames({ selected: this.state.discoverNav })} to="/discover" onClick={() => { this.hideMenu() }}>Discover</Link> <a className="external community" href={CONST.externalLinks.general.devForum} target="_blank" rel="noreferrer">Dev Forum</a> </nav> </header> ); } } const HeaderCompWithRoute = withRouter(Header); export default HeaderCompWithRoute;
30.228814
134
0.594057
fcfc7bbdb47fabae6b33a4f8824a2419c6f04e61
742
js
JavaScript
src/views/findPurchase/table/column.js
slilp/backoffice-web
3598f35535eae66066d30e697a32c1f53d11d904
[ "MIT" ]
1
2021-05-25T03:16:45.000Z
2021-05-25T03:16:45.000Z
src/views/findPurchase/table/column.js
slilp/backoffice-web
3598f35535eae66066d30e697a32c1f53d11d904
[ "MIT" ]
null
null
null
src/views/findPurchase/table/column.js
slilp/backoffice-web
3598f35535eae66066d30e697a32c1f53d11d904
[ "MIT" ]
null
null
null
import { Button } from "react-bootstrap"; export const columns = [ { title: "รหัสการสั่งซื้อ", dataIndex: "code", key: "code", width:10, render: (text) => <span>{text}</span>, }, { title: "ชื่อลูกค้า", dataIndex: "name", key: "name", width:10, render: (text) => <span>{text}</span> }, { title: "ยอดขาย", dataIndex: "revenue", key: "revenue", width:10, render: (text) => <span>{text}</span>, }, { title: "เเก้ไข", dataIndex: "edit", key: "edit", width:10, render: (value) => ( <Button variant="primary" onClick={()=> value.func(value.pid , value.customerInfo)} size="sm" className="font-kanit"> เลือก </Button> ), }, ];
20.054054
124
0.513477
fcfc833bf9ef45fb34d12bf8c4db7c96ada0b879
903
js
JavaScript
build/config.js
alexholliz/dumbDiscordBot
5af33881f84a5bf2120473171eb5083bd6c91bfe
[ "MIT" ]
null
null
null
build/config.js
alexholliz/dumbDiscordBot
5af33881f84a5bf2120473171eb5083bd6c91bfe
[ "MIT" ]
null
null
null
build/config.js
alexholliz/dumbDiscordBot
5af33881f84a5bf2120473171eb5083bd6c91bfe
[ "MIT" ]
null
null
null
// meh, just export the whole dang thing as an object... export default { config: { src: [ 'src/**/*.js', '!src/**/*.[sS]pec.js', '!src/**/{fixtures,templates}/**' ], backEndsrc: [ 'src/**/*.js', '!src/**/*.[sS]pec.js', ], backEndTemplates: [ 'src/**/*', '!src/**/*.js' ], templates: [ //'src/**/{fixtures,templates}/**', //'src/**/*.json', //'src/**/*.php', //'src/**/*.html', //'src/**/*.png', //'src/**/*.xml', //'src/**/*.sql', //'src/**/*.py', //'src/**/*.sh', //'src/**/*.jpg', //'src/**/*.jpeg', //'src/**/*.ico', //'src/**/*.jpeg', //'src/**/*.csv', //'src/**/*.conf', //'src/**/*.css', //'src/**/*.sass', //'src/**/templates/**/.*' ], destDir: "dist", test: [ 'src/**/*.[sS]pec.js' ] } };
20.522727
56
0.345515
fcfca05c5c986a57c6968571e739f0f90d6b9f8d
260
js
JavaScript
tutorialModel.js
Fcmam5/diagflow-webhook-learn2code-gAssistant
285ff7819c8b842162efad4e9eea5125ca9ecd5b
[ "MIT" ]
null
null
null
tutorialModel.js
Fcmam5/diagflow-webhook-learn2code-gAssistant
285ff7819c8b842162efad4e9eea5125ca9ecd5b
[ "MIT" ]
null
null
null
tutorialModel.js
Fcmam5/diagflow-webhook-learn2code-gAssistant
285ff7819c8b842162efad4e9eea5125ca9ecd5b
[ "MIT" ]
null
null
null
class Tutorial { constructor(title, link, programming_lang, nature, language) { this.title = title this.link = link this.programming_lang = programming_lang this.nature = nature this.language = language } } module.exports = Tutorial;
21.666667
64
0.7
fcfca921671b491a4c3b5e1a1c5e31fb75aa91ef
6,738
js
JavaScript
src/widgets/auth/assets/src/auth.js
skeeks-cms/cms-theme-unify-v2
0bd896c3826c607ac3895a8b15319aa3abfe3906
[ "BSD-3-Clause" ]
1
2019-05-07T12:30:56.000Z
2019-05-07T12:30:56.000Z
src/widgets/auth/assets/src/auth.js
skeeks-cms/cms-theme-unify-v2
0bd896c3826c607ac3895a8b15319aa3abfe3906
[ "BSD-3-Clause" ]
null
null
null
src/widgets/auth/assets/src/auth.js
skeeks-cms/cms-theme-unify-v2
0bd896c3826c607ac3895a8b15319aa3abfe3906
[ "BSD-3-Clause" ]
null
null
null
/** * @link https://cms.skeeks.com/ * @copyright Copyright (c) 2010 SkeekS * @license https://cms.skeeks.com/license/ * @author Semenov Alexander <semenov@skeeks.com> */ (function (sx, $, _) { sx.classes.Auth = sx.classes.Component.extend({ _onDomReady: function () { var self = this; //Событие видежта action self.getJWrapper().on("action", function (e, data) { self.runAction(data); }); //Триггер для вызова нужного action $(".sx-trigger-action", self.getJWrapper()).on("click", function () { var action = $(this).data("action"); self.getJWrapper().trigger("action", { 'action': action }); return false; }); //Отправка SMS кода $(".sx-phone-code-trigger", self.getJWrapper()).on("click", function () { var jWrapper = $(this).closest(".sx-auth-action"); var phone = $(".sx-phone", jWrapper).val(); var ajaxQuery = sx.ajax.preparePostQuery(self.get("url-generate-phone-code"), { 'phone' : phone }); var Blocker = new sx.classes.Blocker(jWrapper); var handler = new sx.classes.AjaxHandlerStandartRespose(ajaxQuery, { 'blocker' : Blocker, 'enableBlocker' : true, }); handler.on("success", function(e, data) { $("[data-action=auth-by-phone-sms-code] .sx-phone", self.getJWrapper()).val(phone); self.getJWrapper().trigger("action", { 'action': "auth-by-phone-sms-code", 'left-time': data.data['left-repeat'] }); /*if (data.data['left-repeat']) { self.set("leftPhone", data.data['left-repeat']); self.runPhoneLeftTime(); }*/ }); ajaxQuery.execute(); return false; }); //Отправка Email кода $(".sx-email-code-trigger", self.getJWrapper()).on("click", function () { var jWrapper = $(this).closest(".sx-auth-action"); var email = $(".sx-email", jWrapper).val(); var ajaxQuery = sx.ajax.preparePostQuery(self.get("url-generate-email-code"), { 'email' : email }); var Blocker = new sx.classes.Blocker(jWrapper); var handler = new sx.classes.AjaxHandlerStandartRespose(ajaxQuery, { 'blocker' : Blocker, 'enableBlocker' : true, }); handler.on("success", function(e, data) { $("[data-action=auth-by-email-code] .sx-email", self.getJWrapper()).val(email); self.getJWrapper().trigger("action", { 'action': "auth-by-email-code", 'left-time': data.data['left-repeat'], }); /*if (data.data['left-repeat']) { self.set("leftEmail", data.data['left-repeat']); self.runEmailLeftTime(); }*/ }); ajaxQuery.execute(); return false; }); //Действие по умолчанию self.getJWrapper().trigger("action", { 'action': this.get('action') }); $(".sx-phone", self.getJWrapper()).mask("+7 999 999-99-99"); }, stopEmailLeftTime() { var self = this; var waitJwrappper = $(".sx-email-trigger-wrapper"); $(".sx-email-code-wait", waitJwrappper).hide(); $(".sx-email-code-trigger", waitJwrappper).show(); clearInterval(this.emailTimer); this.emailTimer = null }, stopPhoneLeftTime() { var self = this; var waitJwrappper = $(".sx-phone-trigger-wrapper"); $(".sx-phone-code-wait", waitJwrappper).hide(); $(".sx-phone-code-trigger", waitJwrappper).show(); clearInterval(this.phoneTimer); this.phoneTimer = null }, runEmailLeftTime() { var self = this; var waitJwrappper = $(".sx-email-trigger-wrapper"); $(".sx-left-time", waitJwrappper).empty().append(self.get("leftEmail")); $(".sx-email-code-wait", waitJwrappper).show(); $(".sx-email-code-trigger", waitJwrappper).hide(); if (!this.emailTimer) { this.emailTimer = setInterval(function() { var leftTime = self.get("leftEmail") - 1; self.set("leftEmail", leftTime); if (leftTime <= 0) { self.stopEmailLeftTime(); } $(".sx-left-time", waitJwrappper).empty().append(self.get("leftEmail")); }, 1000); } }, runPhoneLeftTime() { var self = this; var waitJwrappper = $(".sx-phone-trigger-wrapper"); $(".sx-left-time", waitJwrappper).empty().append(self.get("leftPhone")); $(".sx-phone-code-wait", waitJwrappper).show(); $(".sx-phone-code-trigger", waitJwrappper).hide(); if (!this.phoneTimer) { this.phoneTimer = setInterval(function() { var leftTime = self.get("leftPhone") - 1; self.set("leftPhone", leftTime); if (leftTime <= 0) { self.stopPhoneLeftTime(); } $(".sx-left-time", waitJwrappper).empty().append(self.get("leftPhone")); }, 1000); } }, getJWrapper() { return $("#" + this.get('id')); }, runAction: function (data) { var self = this; var action = data.action; $(".sx-auth-action").hide(); $(".sx-auth-action[data-action=" + action + "]").show(); console.log(data); if (action == 'auth-by-email-code' && data['left-time']) { self.set("leftEmail", data['left-time']); self.runEmailLeftTime(); } if (action == 'auth-by-phone-sms-code' && data['left-time']) { self.set("leftPhone", data['left-time']); self.runPhoneLeftTime(); } } }); })(sx, sx.$, sx._);
32.239234
103
0.45889
fcfcf41db5b1f056d73eedf33ef1f2084bc0a114
82
js
JavaScript
src/store/getter/userGetter.js
wayshon/community-vue
c4c9adca20a06df131e6dad097591921dcc2b5be
[ "Apache-2.0" ]
null
null
null
src/store/getter/userGetter.js
wayshon/community-vue
c4c9adca20a06df131e6dad097591921dcc2b5be
[ "Apache-2.0" ]
null
null
null
src/store/getter/userGetter.js
wayshon/community-vue
c4c9adca20a06df131e6dad097591921dcc2b5be
[ "Apache-2.0" ]
null
null
null
/** * getter */ export const getHome = state => { return state.user.name }
10.25
33
0.585366
fcfdb747edf505345119c4cae4dbe879c29161ca
785
js
JavaScript
.storybook/webpack.config.js
vickymin/preact-datepicker
644bae6828b29304b376d75d78a5abef800c4736
[ "MIT" ]
null
null
null
.storybook/webpack.config.js
vickymin/preact-datepicker
644bae6828b29304b376d75d78a5abef800c4736
[ "MIT" ]
null
null
null
.storybook/webpack.config.js
vickymin/preact-datepicker
644bae6828b29304b376d75d78a5abef800c4736
[ "MIT" ]
null
null
null
const ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { module: { rules: [ { test: /\.(png|jpg|gif)$/, loader: 'url-loader', options: { limit: '25000', name: 'images/[name].[ext]', }, }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader', }), }, { test: /\.less$/, include: /src/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader?-minimize', 'postcss-loader', 'less-loader'], }), }, ], }, plugins: [ new ExtractTextPlugin({ filename: '[name].css', allChunks: true, }), ], resolve: { alias: { react: 'preact-compat', 'react-dom': 'preact-compat', }, }, };
17.840909
68
0.536306
fcfdc27ec5f8a7df103e2d3cc2bf8c3d6d4dccf0
757
js
JavaScript
src/app/router.js
Zequez/ggfilter-client
0d0d049b35b5ce0c081ad56ac2600caf6f0dc635
[ "MIT" ]
null
null
null
src/app/router.js
Zequez/ggfilter-client
0d0d049b35b5ce0c081ad56ac2600caf6f0dc635
[ "MIT" ]
null
null
null
src/app/router.js
Zequez/ggfilter-client
0d0d049b35b5ce0c081ad56ac2600caf6f0dc635
[ "MIT" ]
null
null
null
import Router5 from 'router5' import browserPlugin from 'router5/plugins/browser' export const routes = [ { name: 'root', path: '/' }, { name: 'filterPlain', path: '/f' }, { name: 'filterSid', path: '/f/:sid' }, { name: 'filterFull', path: '/f/:sid/:slug' }, { name: 'sysreq', path: '/sysreq' }, { name: 'aboutSysreq', path: '/sysreq/about' }, { name: 'logs', path: '/logs' }, { name: 'sources', path: '/sources' }, { name: 'feedback', path: '/feedback' }, { name: 'donations', path: '/donations' }, { name: 'oculusSandbox', path: '/oculus-sandbox' } ] const router = Router5(routes, {defaultRoute: 'root'}).usePlugin(browserPlugin()) export const paths = router.buildPath export const urls = router.buildUrl export default router
31.541667
81
0.630119
fcfe3bebb686e8b612721a58ff0fca70941932b8
887
js
JavaScript
src/components/Signin.js
andyL89/intervals-ear-trainer
39a7128a645f6c44fc8209943586ef3ee818b5ce
[ "MIT" ]
null
null
null
src/components/Signin.js
andyL89/intervals-ear-trainer
39a7128a645f6c44fc8209943586ef3ee818b5ce
[ "MIT" ]
null
null
null
src/components/Signin.js
andyL89/intervals-ear-trainer
39a7128a645f6c44fc8209943586ef3ee818b5ce
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import withFirebaseAuth from 'react-with-firebase-auth' import 'firebase/auth'; import firebase from 'firebase/app'; import firebaseApp from './../firebase'; import { Nav } from 'react-bootstrap'; import { Link } from 'react-router-dom'; class Signin extends Component { render() { const { user, signOut, signInWithGoogle, } = this.props; return ( <> { user ? <Nav.Link><Link onClick={signOut} to="/home" style={{color: '#ffffff', textDecoration: 'none'}}>Sign out</Link></Nav.Link> : <Nav.Link onClick={signInWithGoogle}>Sign in with Google</Nav.Link>} </> ) } } const firebaseAppAuth = firebaseApp.auth(); const providers = { googleProvider: new firebase.auth.GoogleAuthProvider(), }; export default withFirebaseAuth({ providers, firebaseAppAuth, })(Signin);
24.638889
132
0.656144
fcfe9219978d0919b5006d4d38657bc7b8c179d0
918
js
JavaScript
client/src/component/profilePage/Profile.js
arbourKyle/premiereReact
7cce03e15a86d296a8809dac3b86ee717a71f9da
[ "MIT" ]
2
2022-03-30T15:20:58.000Z
2022-03-30T21:28:24.000Z
client/src/component/profilePage/Profile.js
arbourKyle/premiereReact
7cce03e15a86d296a8809dac3b86ee717a71f9da
[ "MIT" ]
null
null
null
client/src/component/profilePage/Profile.js
arbourKyle/premiereReact
7cce03e15a86d296a8809dac3b86ee717a71f9da
[ "MIT" ]
null
null
null
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; import Products from "../Products"; import CreateProduct from "../createproduct"; import Card from "../productcards,navbar/Card"; import "../profilePage/profile.css" const Profile = () => { const { user, isAuthenticated, isLoading } = useAuth0(); if (isLoading) { return <div>Loading ...</div>; } return ( isAuthenticated && ( <div id="profilepage"> <br></br> <img src={user.picture} alt={user.name} /> <h2>Welcome {user.name}</h2> <p>Your registered e-mail: {user.email}</p> <Products /> <br></br> <br></br> <Card /> <h3 id="adminrole">Admin role detected:<br></br></h3> <CreateProduct /> <br></br> <br></br> <br></br> </div> ) ); }; export default Profile;
19.531915
61
0.526144
fcfec4283cb2ec7a000ee63d715c41109ade4b2e
807
js
JavaScript
admin/public/javascripts/components/Api/PostSvc.js
polarExpress/superDockerBlog
5fb0d2d693da0679d85f16176642bed23918e938
[ "MIT" ]
null
null
null
admin/public/javascripts/components/Api/PostSvc.js
polarExpress/superDockerBlog
5fb0d2d693da0679d85f16176642bed23918e938
[ "MIT" ]
null
null
null
admin/public/javascripts/components/Api/PostSvc.js
polarExpress/superDockerBlog
5fb0d2d693da0679d85f16176642bed23918e938
[ "MIT" ]
null
null
null
(function() { 'use strict'; var PostSvc = ['PostApiSvc' ,function(PostApiSvc) { //POST specific post this.post = function(post) { var postPromise = PostApiSvc.submitPost(post); return postPromise; }; //PUT specific post this.update = function(post, postId) { var postPromise = PostApiSvc.updatePost(post, postId); return postPromise; }; this.delete = function(postId) { var postPromise = PostApiSvc.deletePost(postId); return postPromise; }; this.get = function(postId) { var postPromise; if (typeof postId == 'undefined') { postPromise = PostApiSvc.getAllPosts(); } else { postPromise = PostApiSvc.getPostById(postId); } return postPromise; }; }]; angular .module('Api') .service('PostSvc', PostSvc); })();
19.214286
60
0.640644
fcfed7c79384c822829e3d2f923b28f3897cb368
2,929
js
JavaScript
scripts/helpers/aside_archives.js
theWorkFsz/hexo-theme-butterfly
d62ec1b86656be7abf4b8f18f44e873621876814
[ "MIT" ]
1
2020-05-27T02:36:07.000Z
2020-05-27T02:36:07.000Z
scripts/helpers/aside_archives.js
theWorkFsz/hexo-theme-butterfly
d62ec1b86656be7abf4b8f18f44e873621876814
[ "MIT" ]
4
2021-03-01T21:15:15.000Z
2022-02-26T01:55:56.000Z
scripts/helpers/aside_archives.js
theWorkFsz/hexo-theme-butterfly
d62ec1b86656be7abf4b8f18f44e873621876814
[ "MIT" ]
null
null
null
/** * Butterfly * for aside archives */ 'use strict' hexo.extend.helper.register('aside_archives', function (options = {}) { const { config } = this const archiveDir = config.archive_dir const { timezone } = config const lang = toMomentLocale(this.page.lang || this.page.language || config.language) let { format } = options const type = options.type || 'monthly' const { transform } = options const showCount = Object.prototype.hasOwnProperty.call(options, 'show_count') ? options.show_count : true const order = options.order || -1 const compareFunc = type === 'monthly' ? (yearA, monthA, yearB, monthB) => yearA === yearB && monthA === monthB : (yearA, monthA, yearB, monthB) => yearA === yearB const limit = options.limit const moreButton = this._p('aside.more_button') let result = '' if (!format) { format = type === 'monthly' ? 'MMMM YYYY' : 'YYYY' } const posts = this.site.posts.sort('date', order) if (!posts.length) return result const data = [] let length = 0 posts.forEach(post => { // Clone the date object to avoid pollution let date = post.date.clone() if (timezone) date = date.tz(timezone) const year = date.year() const month = date.month() + 1 const lastData = data[length - 1] if (!lastData || !compareFunc(lastData.year, lastData.month, year, month)) { if (lang) date = date.locale(lang) const name = date.format(format) length = data.push({ name, year, month, count: 1 }) } else { lastData.count++ } }) const link = item => { let url = `${archiveDir}/${item.year}/` if (type === 'monthly') { if (item.month < 10) url += '0' url += `${item.month}/` } return this.url_for(url) } result += '<ul class="archive-list">' const len = data.length const Judge = limit === 0 ? len : Math.min(len, limit) for (let i = 0; i < Judge; i++) { const item = data[i] result += '<li class="archive-list-item">' result += `<a class="archive-list-link" href="${link(item)}">` result += '<span class="archive-list-date">' result += transform ? transform(item.name) : item.name result += '</span>' if (showCount) { result += `<span class="archive-list-count">${item.count}</span>` } result += '</a>' result += '</li>' } if (len > Judge) { result += '<li class="archive-list-item is-center">' result += `<a class="archive-list-link-more" href="${this.url_for(archiveDir)}">${moreButton}</a></li>` } result += '</ul>' return result }) var toMomentLocale = function (lang) { if (lang === undefined) { return undefined } // moment.locale('') equals moment.locale('en') // moment.locale(null) equals moment.locale('en') if (!lang || lang === 'en' || lang === 'default') { return 'en' } return lang.toLowerCase().replace('_', '-') }
26.151786
107
0.592011
fcff0ce9f29b41de6614e413027f16dfae0ff133
5,003
js
JavaScript
src/drilldownMenu/docs/demo.js
thierry2015/angular-foundation-6
5399134af158bf670915e02778ab9c689cd52ff3
[ "MIT" ]
114
2016-03-03T14:59:26.000Z
2021-10-07T16:11:40.000Z
src/drilldownMenu/docs/demo.js
thierry2015/angular-foundation-6
5399134af158bf670915e02778ab9c689cd52ff3
[ "MIT" ]
85
2016-03-02T23:56:02.000Z
2019-09-05T22:51:15.000Z
src/drilldownMenu/docs/demo.js
thierry2015/angular-foundation-6
5399134af158bf670915e02778ab9c689cd52ff3
[ "MIT" ]
77
2016-04-06T12:07:05.000Z
2021-11-10T07:09:13.000Z
angular.module('foundationDemoApp') .controller('DrillDownDemoCtrl', function($scope, $element, $timeout, $log) { 'ngInject'; const vm = { ddmApi: null, shouldShow: false, haveShown: false, haveResized: false, alerts: [], showHideMenu: showHideMenu, showSubmenu1: showSubmenu1, hideSubmenu1: hideSubmenu1, closeAlert: closeAlert, }; $scope.vm = vm; /** * Initial alert used as part of the API Usage demo */ vm.alerts = [{ type: 'alert', msg: 'The menu below is hidden with css. Press the button to show it (using ng-show).', }]; /** * Event handlers for the menu events */ $scope.$on('resize.mm.foundation.drilldownMenu', onMenuResized); $scope.$on('open.mm.foundation.drilldownMenu', onSubmenuOpen); $scope.$on('hide.mm.foundation.drilldownMenu', onSubmenuClosed); /** * Sets the variable to show or hide the menu block */ function showHideMenu() { vm.shouldShow = !vm.shouldShow; if (!vm.haveShown) { closeAlert(0); addAlert( 'alert', 'The menu is now "shown", but because it was hidden initially it will start with ' + '"max-width: 0px" and doesn\'t appear! Press the resize button to trigger ' + 'a resize via the API' ); vm.haveShown = true; } } /** * Get the UL for submenu 1. * NOTE: You MUST use the UL for the submenu to show/hide, NOT the parent LI! * * @returns {angular.element} - The element for submenu 1 in the API section */ function getSubmenu1() { return angular.element($element[0].querySelector('ul#drilldown-api-submenu-1')); } /** * Function to use the API to open a specific menu item */ function showSubmenu1() { // // Find the item // var element = getSubmenu1(); // // Use the API to open it // vm.ddmApi.show(element); } /** * Function to use the API to close a specific menu item */ function hideSubmenu1() { // // Find the item // var element = getSubmenu1(); // // Use the API to open it // vm.ddmApi.hide(element); } /** * Handler for the resized event from the menu * * @param {Object} event - Angular `event` object (see $rootScope.$on) * @param {angular.element} menuElement - The root element of the menu */ function onMenuResized(event, menuElement) { if (menuElement.attr('id') !== 'drilldown-api-menu') { return; // One of the other menus } if (vm.haveShown && !vm.haveResized) { closeAlert(0); addAlert( 'success', 'Congratulations! The menu should now be visible!' ); addAlert( 'alert', 'The same 0-width problem will happen again if the menu is hidden then ' + 'resized (via the API or via a viewport size change). ' + 'You MUST trigger a resize via the API after showing it again if this happens.' ); vm.haveResized = true; } } /** * Example handler for the submenu open event * * @param {Object} event - Angular `event` object (see $rootScope.$on) * @param {angular.element} menuElement - The root element of the menu * @param {angular.element} submenuElement - The submenu element that has just opened */ function onSubmenuOpen(event, menuElement, submenuElement) { if (submenuElement.attr('id') === 'drilldown-api-submenu-1') { $log.log('Submenu 1 has been opened!'); } } /** * Example handler for the submenu close event * * @param {Object} event - Angular `event` object (see $rootScope.$on) * @param {angular.element} menuElement - The root element of the menu * @param {angular.element} submenuElement - The submenu element that has just closed */ function onSubmenuClosed(event, menuElement, submenuElement) { if (submenuElement.attr('id') === 'drilldown-api-submenu-1') { $log.log('Submenu 1 has been closed!'); } } /** * Closes the specific alert * * @param {number} index - The index of the alert to close */ function closeAlert(index) { vm.alerts.splice(index, 1); } /** * Adds a new alert programmatically. * Used of the explanations of the drilldown menu API and functionality. * * @param {string} type - the type of alert * @param {string} msg - the alert message */ function addAlert(type, msg) { vm.alerts.push({ type: type, msg: msg }); } });
30.321212
100
0.553668
1e00209efd87aa9c4b3b7e4845d35105ee4bfa89
1,438
js
JavaScript
server/webpack.prod.config.js
Shenenkaka/react-mobile-calendar
1099e09552ae63926bf6c9f7653b256956925815
[ "MIT" ]
2
2021-02-01T03:24:10.000Z
2022-01-12T15:16:24.000Z
server/webpack.prod.config.js
Shenenkaka/react-mobile-calendar
1099e09552ae63926bf6c9f7653b256956925815
[ "MIT" ]
null
null
null
server/webpack.prod.config.js
Shenenkaka/react-mobile-calendar
1099e09552ae63926bf6c9f7653b256956925815
[ "MIT" ]
null
null
null
const path = require('path') module.exports = { mode: 'production', entry: './playground/index.js', output: { filename: 'main.js', path: path.resolve(path.resolve(), './public/dist') }, module: { rules: [ { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: [ [ '@babel/preset-env', { targets: { esmodules: true, } } ], '@babel/preset-react' ] } } }, { test: /\.less$/, use: [ { loader: 'style-loader', // creates style nodes from JS strings }, { loader: 'css-loader', // translates CSS into CommonJS }, { loader: 'less-loader', // compiles Less to CSS }, ], }, ] } }
29.346939
86
0.273296
1e006570fb8f6e166a3f63f7a69407c609673a6b
2,870
js
JavaScript
tests/unit/data-test.js
shibulijack-fd/ember-decorators-polyfill
626c3ad30b47772aaedb75bc25649d26ed0c5e94
[ "MIT" ]
19
2019-04-05T00:37:14.000Z
2019-12-17T21:53:52.000Z
tests/unit/data-test.js
shibulijack-fd/ember-decorators-polyfill
626c3ad30b47772aaedb75bc25649d26ed0c5e94
[ "MIT" ]
18
2019-04-05T23:54:15.000Z
2020-01-22T18:24:35.000Z
tests/unit/data-test.js
ember-polyfills/ember-decorators-polyfill
c5df3369f7dc900f5e20fe50222f7a0e38ff2f66
[ "MIT" ]
7
2019-04-07T08:10:20.000Z
2020-01-05T21:51:26.000Z
import { module, test } from 'qunit'; import DS from 'ember-data'; import { getContext } from '@ember/test-helpers'; import { setupApplicationTest } from 'ember-qunit'; import { get as emberGet } from '@ember/object'; import { run } from '@ember/runloop'; import { gte } from 'ember-compatibility-helpers'; function get(obj, key) { if (gte('3.1.0')) { return obj[key]; } else { return emberGet(obj, key); } } function getService(name) { return getContext().owner.lookup(`service:${name}`); } function register(registeredName, object) { getContext().owner.register(registeredName, object); } function stubAdapter() { let store = getService('store'); run(() => store.createRecord('post', { name: name1 })); run(() => store.createRecord('post', { name: name2 })); } let name1 = 'Rails is omakase'; let name2 = 'The Parley Letter'; let expectedNames = [name1, name2].join(); module('ember-data', function(hooks) { setupApplicationTest(hooks); test('attr', async function(assert) { let Post = DS.Model.extend({ name: DS.attr() }); register(`model:post`, Post); stubAdapter(); let store = getService('store'); let posts = await store.peekAll('post'); let names = posts .toArray() .map(post => get(post, 'name')) .join(); assert.equal(names, expectedNames, 'The correct records are in the array'); }); test('@attr', async function(assert) { let Post = class extends DS.Model { @DS.attr() name; }; register(`model:post`, Post); stubAdapter(); let store = getService('store'); let posts = await store.peekAll('post'); let names = posts .toArray() .map(post => get(post, 'name')) .join(); assert.equal(names, expectedNames, 'The correct records are in the array'); }); test('@attr can be used without parens', async function(assert) { let Post = class extends DS.Model { @DS.attr name; }; register(`model:post`, Post); stubAdapter(); let store = getService('store'); let posts = await store.peekAll('post'); let names = posts .toArray() .map(post => get(post, 'name')) .join(); assert.equal(names, expectedNames, 'The correct records are in the array'); }); if (gte('ember-data', '3.11.0')) { test('@attr works with module imports without parens', async function(assert) { let { default: Model, attr } = window.require('@ember-data/model'); let Post = class extends Model { @attr name; }; register(`model:post`, Post); stubAdapter(); let store = getService('store'); let posts = await store.peekAll('post'); let names = posts .toArray() .map(post => get(post, 'name')) .join(); assert.equal(names, expectedNames, 'The correct records are in the array'); }); } });
25.855856
83
0.612544
1e00d7bf5fdd4d38512167ec520a56365e2a377a
893
js
JavaScript
src/components/ranking-panel/index.js
Lninn/fcc-image-search
9f68d42de5aa5709c5ae36c2c2ec1a8137eb34ea
[ "MIT" ]
null
null
null
src/components/ranking-panel/index.js
Lninn/fcc-image-search
9f68d42de5aa5709c5ae36c2c2ec1a8137eb34ea
[ "MIT" ]
2
2022-02-13T20:11:53.000Z
2022-02-27T10:12:00.000Z
src/components/ranking-panel/index.js
Lninn/cnode-clone
9f68d42de5aa5709c5ae36c2c2ec1a8137eb34ea
[ "MIT" ]
null
null
null
import React from "react"; import { Panel } from "@components"; import { Link } from "react-router-dom"; import { queryRankingScore } from "@services"; function Index() { const [data, setData] = React.useState([]); React.useEffect(() => { async function query() { try { const res = await queryRankingScore(); setData(res); } catch (error) { console.error(error); } } query(); }, []); const header = ( <> 积分榜 <Link to="/user">TOP 100 &gt;&gt;&gt;</Link> </> ); return ( <Panel className="ranking-panel" header={header}> <ol> {data.map((user) => { return ( <li key={user.id}> <span>{user.score}</span> <Link to="/user">{user.name}</Link> </li> ); })} </ol> </Panel> ); } export default Index;
19.413043
53
0.489362
1e016eb671a37c50322a67d3a83851a122275b45
881
js
JavaScript
commands/queue.js
higordiasz/Mey
12b25b3277f4b5e49c9a46a0a33abf6344391419
[ "MIT" ]
1
2021-06-22T03:14:58.000Z
2021-06-22T03:14:58.000Z
commands_old/queue.js
higordiasz/Mey
12b25b3277f4b5e49c9a46a0a33abf6344391419
[ "MIT" ]
null
null
null
commands_old/queue.js
higordiasz/Mey
12b25b3277f4b5e49c9a46a0a33abf6344391419
[ "MIT" ]
1
2021-06-21T19:16:17.000Z
2021-06-21T19:16:17.000Z
const { MessageEmbed, splitMessage, escapeMarkdown } = require("discord.js"); module.exports = { name: "queue", aliases: ["q"], description: "Show the music queue and now playing.", execute(message) { const queue = message.client.queue.get(message.guild.id); if (!queue) return message.reply("There is nothing playing.").catch(console.error); const description = queue.songs.map((song, index) => `${index + 1}. ${escapeMarkdown(song.title)}`); let queueEmbed = new MessageEmbed() .setTitle("Klarck Queue") .setDescription(description) .setColor("#ffffff"); const splitDescription = splitMessage(description, { maxLength: 2048, char: "\n", prepend: "", append: "" }); splitDescription.forEach(async (m) => { queueEmbed.setDescription(m); message.channel.send(queueEmbed); }); } };
28.419355
104
0.637911
1e019f78bc606eae71d6c55c524a37dbb03b1e3e
745
js
JavaScript
routes/server_rendered_views.js
IAmBrandonMcGregor/acorn
88ecc92feee27c07f2c241cb7497c619aa746d76
[ "MIT" ]
null
null
null
routes/server_rendered_views.js
IAmBrandonMcGregor/acorn
88ecc92feee27c07f2c241cb7497c619aa746d76
[ "MIT" ]
null
null
null
routes/server_rendered_views.js
IAmBrandonMcGregor/acorn
88ecc92feee27c07f2c241cb7497c619aa746d76
[ "MIT" ]
null
null
null
/* These routes are rooted to calls to /[view-route] */ // Cache references to other modules. var express = require('express'), router = express.Router(), path = require('path'), fs = require('fs'); // Serve the main index.html file. This is integral to bootstrapping our application. router.get('/', function (req, res, next) { // read the contents of the Baseline CSS file and render them into the index view. fs.readFile('static/styles/css/baseline.css', function (err, css) { // pass any error to the default error handler... if (err) return next(new Error(err)); // otherwise, render the css into the view and send it. res.render('index', { title: 'Acorn', baselineCSS: css }); }); }); module.exports = router;
25.689655
85
0.677852
1e01b4f54783139436cdd5e72d6c123bae4ea750
213
js
JavaScript
samples/concepts/iterator/generator.js
noomorph/showing-the-es6
a89e22c7bc2f3ae56b99e88adc446c6802a641c2
[ "Artistic-2.0" ]
null
null
null
samples/concepts/iterator/generator.js
noomorph/showing-the-es6
a89e22c7bc2f3ae56b99e88adc446c6802a641c2
[ "Artistic-2.0" ]
null
null
null
samples/concepts/iterator/generator.js
noomorph/showing-the-es6
a89e22c7bc2f3ae56b99e88adc446c6802a641c2
[ "Artistic-2.0" ]
null
null
null
function* gen123() { var i = 1; yield i; // -> 1 i += 1; yield i; // -> 2 } g = gen123(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { done: true }
17.75
38
0.446009
1e01c1bbfcf19efd695f46790193813727b33703
14,114
js
JavaScript
FilePicker/Scripts/app.js
isabella232/O365-TenantWide-File-Picker
9f8761334d6a41efe5d06dc978efc7a76ccf11be
[ "MIT" ]
4
2015-10-05T14:56:28.000Z
2019-07-03T14:33:44.000Z
FilePicker/Scripts/app.js
OfficeDev/O365-TenantWide-File-Picker
9f8761334d6a41efe5d06dc978efc7a76ccf11be
[ "MIT" ]
1
2019-11-28T08:01:41.000Z
2019-11-28T08:01:41.000Z
FilePicker/Scripts/app.js
isabella232/O365-TenantWide-File-Picker
9f8761334d6a41efe5d06dc978efc7a76ccf11be
[ "MIT" ]
2
2015-11-18T05:01:41.000Z
2020-11-17T19:13:35.000Z
(function () { var host = "https://localhost:44300"; angular.module("filePicker", []) .controller("searchCtrl", ["$scope", "$http", function ($scope, $http) { $scope.items = []; $scope.searchTerms = ""; $scope.waiting = true; $scope.active_view = "OneDrive"; $scope.breadcrumb = [{ name: "OneDrive", id: null, type: "root", path: null }]; //toggles between OneDrive view and Sites View $scope.toggleNav = function (item) { //ignore clicks on the active item if ($scope.active_view === item) return; //set the active_view and start waiting $scope.active_view = item; $scope.waiting = true; //check id this is OneDrive or Sites if (item === "OneDrive") { $scope.breadcrumb = [{ name: "OneDrive", id: null, type: "root", path: null }]; queryOneDrive(null); } else { $scope.breadcrumb = [{ name: "Sites", id: null, type: "root", path: null }]; querySites(); } }; //handles navigation back to an item in the breadcrumb $scope.breadnav = function (item, index) { //ignore clicks on current breadcrumb level if (index === $scope.breadcrumb.length - 1) return; //start waiting and determine if this is reset or middle breadcrumb $scope.waiting = true; if (index === 0) { //reset based on the activeview if ($scope.active_view === "OneDrive") queryOneDrive(null); else querySites(); } else { //navigate based on the activeview if ($scope.active_view === "OneDrive") queryOneDrive(item.id); else if (item.type !== "lib") querySite(item.path); else queryLib(item.path, null); } //update breadcrumb by removing ends while (index < $scope.breadcrumb.length - 1) $scope.breadcrumb.pop(); }; //handles the item clicked event $scope.clicked = function (item) { //for files we just toggle the selected flag if (item.type === "File") { item.selected = !item.selected; return; } //start waiting $scope.waiting = true; //handle click based on type if (item.type === "Site") { //this is a site/web $scope.breadcrumb.push({ name: item.name, id: item.id, type: item.type, path: item.path }); querySite(item.path); } else if (item.type === "lib") { //this is a library $scope.breadcrumb.push({ name: item.name, id: item.id, type: item.type, path: item.path }); queryLib(item.path, null); } else { //this is a folder $scope.breadcrumb.push({ name: item.name, id: item.id, type: item.type, path: item.path }); if ($scope.active_view === "OneDrive") queryOneDrive(item.id); else queryLib(item.path, item.id) } }; //queries OneDrive var queryOneDrive = function (id) { //build query based on id var query = ""; if (id === null) query = "/files"; else query = "/files/" + id + "/children"; //perform query $scope.items = []; $http.defaults.headers.common["Authorization"] = "Bearer " + auth_details.myToken; $http.defaults.headers.post["accept"] = "application/json;odata=verbose"; $http.get(auth_details.myEndpoint + query) .success(function (data) { $(data.value).each(function (i, e) { if (e.type === "Folder") $scope.items.push({ "name": e.name, "type": e.type, "id": e.id, extension: "folder", path: e.webUrl }); else if (e.type === "File") { //get the file extension var ext = e.name.substring(e.name.lastIndexOf(".") + 1).toLowerCase(); //only add media files if (ext === "png" || ext === "gif" || ext === "jpg" || ext === "jpeg" || ext === "mp4") { $scope.items.push({ "name": e.name, "type": e.type, "id": e.id, extension: ext, size: e.size, path: e.webUrl }); } } }); $scope.waiting = false; }) .error(function (err) { //TODO }); }; //queries a library var queryLib = function (path, id) { //build query based on id if (id === null) path += "/files"; else path += "/children"; //perform query $scope.items = []; $http.defaults.headers.common["Authorization"] = "Bearer " + auth_details.rootToken; $http.defaults.headers.post["accept"] = "application/json;odata=verbose"; $http.get(path) .success(function (data) { $(data.value).each(function (i, e) { if (e["odata.type"] === "MS.FileServices.Folder") $scope.items.push({ "name": e.Name, "type": "Folder", "id": e.Id, extension: "folder", path: e["odata.id"] }); else if (e["odata.type"] === "MS.FileServices.File") { //get the file extension var ext = e.Name.substring(e.Name.lastIndexOf(".") + 1).toLowerCase(); //only add media files if (ext === "png" || ext === "gif" || ext === "jpg" || ext === "jpeg" || ext === "mp4") { $scope.items.push({ "name": e.Name, "type": "File", "id": e.Id, extension: ext, size: e.Size, path: e.Url }); } } }); $scope.waiting = false; }) .error(function (err) { //TODO }); }; //queries all site collections the user has access to var querySites = function () { //perform sharepoint search to locate sites collections the user has access to $scope.items = []; $http.defaults.headers.common["Authorization"] = "Bearer " + auth_details.rootToken; $http.defaults.headers.post["accept"] = "application/json;odata=verbose"; $http.get(auth_details.rootEndpoint + "/search/query?querytext='contentclass:sts_site'&trimduplicates=true&rowlimit=100&SelectProperties='WebTemplate,Title,Path,SiteLogo'") .success(function (data) { $(data.PrimaryQueryResult.RelevantResults.Table.Rows).each(function (i, e) { $scope.items.push(parseRow(e)); }); $scope.waiting = false; }) .error(function (err) { //TODO }); }; //queries a site var querySite = function (path) { $scope.items = []; //first get webs $http.defaults.headers.common["Authorization"] = "Bearer " + auth_details.rootToken; $http.defaults.headers.post["accept"] = "application/json;odata=verbose"; $http.get(path + "/webs") .success(function (webdata) { $(webdata.value).each(function (i, e) { $scope.items.push({ "name": e.Title, "type": "Site", "id": e.Id, extension: "site", size: null, path: e["odata.id"] }); }); //now get lists $http.defaults.headers.common["Authorization"] = "Bearer " + auth_details.rootToken; $http.defaults.headers.post["accept"] = "application/json;odata=verbose"; $http.get(path + "/Lists") .success(function (data) { $(data.value).each(function (i, e) { if (!e.Hidden && e.BaseTemplate == 101) { $scope.items.push({ "name": e.Title, "type": "lib", "id": e.id, extension: "lib", size: null, path: e["odata.id"] }); } }); $scope.waiting = false; }) .error(function (err) { //TODO }); }) .error(function (err) { //TODO }); }; //parses a search result into a flat row var parseRow = function (row) { var item = { selected: false }; item.type = "Site"; item.extension = "site"; $(row.Cells).each(function (i, e) { if (e.Key === "Path") item.path = e.Value + "/_api/web"; if (e.Key === "Title") item.name = e.Value; }); return item; } //perform initial search queryOneDrive(null); //event for sending selections back to parent window $scope.ok = function () { var data = { action: "result", files: [] }; $($scope.items).each(function (i, e) { if (e.selected) { data.files.push(e); } }); window.opener.postMessage(JSON.stringify(data), host); window.close(); }; //event for canceling the picker and sending cancel action back to parent window $scope.cancel = function () { window.opener.postMessage(JSON.stringify({ action: "cancel", files: null }), host); window.close(); }; }]); $(document).ready(function () { //wire up angular to the page angular.bootstrap($("#container"), ["filePicker"]); }); })(); //these are all office fabric events var fabric = fabric || {}; fabric.Spinner = function (holderElement, spinnerType) { var _holderElement = holderElement; var _spinnerType = spinnerType || "eight"; var eightSize = 0.18; var sixteenSize = 0.1; var circleObjects = []; var animationSpeed = 80; var interval; var spinner; var numCircles; var offsetSize; /** * @function start - starts or restarts the animation sequence * @memberOf fabric.Spinner */ function start() { interval = setInterval(function () { var i = circleObjects.length; while (i--) { _fade(circleObjects[i]); } }, animationSpeed); } /** * @function stop - stops the animation sequence * @memberOf fabric.Spinner */ function stop() { clearInterval(interval); } //private methods function _init() { if (_spinnerType === "sixteen") { offsetSize = sixteenSize; numCircles = 16; } else { offsetSize = eightSize; numCircles = 8; } _createCirclesAndArrange(); _initializeOpacities(); start(); } function _initializeOpacities() { var i = numCircles, j; while (i--) { j = circleObjects.length; while (j--) { _fade(circleObjects[j]); } } } function _fade(circleObject) { var opacity; if (circleObject.j < numCircles) { if (Math.floor(circleObject.j / (numCircles / 2))) { opacity = _getOpacity(circleObject.element) - 2 / numCircles; } else { opacity = _getOpacity(circleObject.element) + 2 / numCircles; } } else { circleObject.j = 0; opacity = 2 / numCircles; } _setOpacity(circleObject.element, opacity); circleObject.j++; } function _getOpacity(element) { return parseFloat(window.getComputedStyle(element).getPropertyValue("opacity")); } function _setOpacity(element, opacity) { element.style.opacity = opacity; } function _createCircle() { var circle = document.createElement('div'); var parentWidth = parseInt(window.getComputedStyle(spinner).getPropertyValue("width"), 10); circle.className = "ms-Spinner-circle"; circle.style.width = circle.style.height = parentWidth * offsetSize + "px"; return circle; } function _createCirclesAndArrange() { spinner = document.createElement("div"); spinner.className = "ms-Spinner"; _holderElement.appendChild(spinner); var width = spinner.clientWidth; var height = spinner.clientHeight; var angle = 0; var offset = width * offsetSize; var step = (2 * Math.PI) / numCircles; var i = numCircles; var circleObject; var radius = (width - offset) * 0.5; while (i--) { var circle = _createCircle(); var x = Math.round(width * 0.5 + radius * Math.cos(angle) - circle.clientWidth * 0.5) - offset * 0.5; var y = Math.round(height * 0.5 + radius * Math.sin(angle) - circle.clientHeight * 0.5) - offset * 0.5; spinner.appendChild(circle); circle.style.left = x + 'px'; circle.style.top = y + 'px'; angle += step; circleObject = { element: circle, j: i }; circleObjects.push(circleObject); } } _init(); return { start: start, stop: stop }; }; var spin16 = fabric.Spinner(jQuery("#spinner-16point")[0], "sixteen");
36.65974
184
0.48583
1e027570150db962d6392d939463eb6df4320e4b
82
js
JavaScript
test/chunking-form/samples/empty-module-no-treeshake/_expected/cjs/main2.js
jameshfisher/rollup
26d067557faba6ae6da1e130b98a12450f6328e2
[ "0BSD", "MIT" ]
23,201
2015-05-27T20:13:57.000Z
2022-03-31T18:07:42.000Z
test/chunking-form/samples/empty-module-no-treeshake/_expected/cjs/main2.js
jameshfisher/rollup
26d067557faba6ae6da1e130b98a12450f6328e2
[ "0BSD", "MIT" ]
3,981
2015-05-26T16:24:14.000Z
2022-03-31T09:52:35.000Z
test/chunking-form/samples/empty-module-no-treeshake/_expected/cjs/main2.js
jameshfisher/rollup
26d067557faba6ae6da1e130b98a12450f6328e2
[ "0BSD", "MIT" ]
1,557
2015-05-26T21:30:26.000Z
2022-03-31T03:58:14.000Z
'use strict'; require('./generated-emptyTransformed.js'); console.log('main2');
13.666667
43
0.707317
1e02bc18f1781e95fde1618803fd306de5800af9
2,832
js
JavaScript
src/examples/javascript/index.express.extended.js
coolgk/node-api
59a0822a89d56924e7171eac7c362bf8d052866f
[ "MIT" ]
1
2020-08-07T19:10:07.000Z
2020-08-07T19:10:07.000Z
src/examples/javascript/index.express.extended.js
coolgk/node-api
59a0822a89d56924e7171eac7c362bf8d052866f
[ "MIT" ]
5
2018-01-31T23:53:32.000Z
2021-05-06T21:26:29.000Z
src/examples/javascript/index.express.extended.js
coolgk/node-mvc
59a0822a89d56924e7171eac7c362bf8d052866f
[ "MIT" ]
null
null
null
'use strict'; /** * an extended example of using the @coolgk/mvc framework with session and form data handlers */ const express = require('express'); const { createClient } = require('redis'); const { Router } = require('@coolgk/mvc/router'); const { formData } = require('@coolgk/formdata'); const { Session } = require('@coolgk/session'); // import app configurations const { config } = require('./config'); const app = express(); // ...some middleware app.use(async (request, response, next) => { // initialise session // see @coolgk/session https://www.npmjs.com/package/@coolgk/session const session = new Session({ redisClient: createClient(config.redis), secret: config.secret, expiry: config.sessionMaxLife, request, response, cookie: { httpOnly: true, secure: config.secureCookie } }); // setup router const router = new Router({ rootDir: __dirname, // required url: request.originalUrl, // required method: request.method, // required // setup form data handler for 'application/json', 'application/x-www-form-urlencoded' and 'multipart/form-data' // see @coolgk/formdata https://www.npmjs.com/package/@coolgk/formdata formdata: formData(request, { dir: config.uploadDir }), // pass formdata in as a global dependency // pass session in as a global dependency session, config, // pass app config in as a global dependency ip: request.ip // pass ip address into router (controller methods) }); // router.route() returns the return value of the controller method if the return value is not falsy // otherwise it returns an object formatted by the "response" object (see the README file for @coolgk/mvc/response) // e.g. { code: 200, text: 'SUCCESS' }, { code: 200, json: {...} }, { code: 200, file: { name: ..., path: ... } } etc. // this example uses the injected response object for setting up http responese in a standard format const result = (await router.route()); // handle json, file or text responses const responseSent = result.json && (response.json(result.json) || 1) || result.file && (response.download(result.file.path, result.file.name || '') || 1) || result.code && (response.status(result.code).send(result.text) || 1); // json, file and text are the only valid responses from this simple app // log error for anything else if (!responseSent) { // your custom error logger console.error(result); // tslint:disable-line response.status(500).send('Internal Server Error'); } }); app.listen(3000); process.on('unhandledRejection', (error) => { // your custom error logger console.error(error); // tslint:disable-line });
36.779221
122
0.645833
1e0481e231512ec11dfc25720200f28055d23a37
3,086
js
JavaScript
js-apps/meep-frontend/src/js/components/dialogs/id-new-scenario-dialog.js
nikhildoifode/AdvantEDGE
2eb7bbc39154afe5e2210e5faf59535cf8fca191
[ "Apache-2.0" ]
null
null
null
js-apps/meep-frontend/src/js/components/dialogs/id-new-scenario-dialog.js
nikhildoifode/AdvantEDGE
2eb7bbc39154afe5e2210e5faf59535cf8fca191
[ "Apache-2.0" ]
null
null
null
js-apps/meep-frontend/src/js/components/dialogs/id-new-scenario-dialog.js
nikhildoifode/AdvantEDGE
2eb7bbc39154afe5e2210e5faf59535cf8fca191
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 InterDigital Communications, Inc * * 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. */ import React, { Component } from 'react'; import autoBind from 'react-autobind'; import { TextField, TextFieldHelperText } from '@rmwc/textfield'; import IDDialog from './id-dialog'; import { MEEP_DLG_NEW_SCENARIO, MEEP_DLG_NEW_SCENARIO_NAME } from '../../meep-constants'; class IDNewScenarioDialog extends Component { constructor(props) { super(props); autoBind(this); this.state = { scenarioName: '', err: null }; } changeScenarioName(name) { var err = null; if (name) { if (name.length > 20) { err = 'Maximum 20 characters'; } else if (!name.match(/^(([a-z0-9][-a-z0-9.]*)?[a-z0-9])+$/)) { err = 'Lowercase alphanumeric or \'-\''; } } this.setState({ scenarioName: name, err: err }); } /** * Callback function to receive the result of the getScenario operation. * @callback module:api/ScenarioConfigurationApi~getScenarioCallback * @param {String} error Error message, if any. * @param {module:model/Scenario} data The data returned by the service call. * @param {String} response The complete HTTP response. */ getScenarioNewCb(error /*, data, response*/) { if (error === null) { // TODO: consider showing an alert return; } // Validate scenario name if (this.state.scenarioName === '' || this.state.err !== null) { // TODO: consider showing an alert return; } // Clear scenario this.props.createScenario(this.state.scenarioName); } onSubmit() { this.props.api.getScenario( this.state.scenarioName, (error, data, response) => { this.getScenarioNewCb(error, data, response); } ); } render() { return ( <IDDialog title={this.props.title} open={this.props.open} onClose={this.props.onClose} onSubmit={this.onSubmit} cydata={MEEP_DLG_NEW_SCENARIO} > <TextField outlined style={{ width: '100%' }} label={'Scenario Name'} onChange={e => { this.changeScenarioName(e.target.value); }} value={this.state.scenarioName} invalid={this.state.err ? true : false} data-cy={MEEP_DLG_NEW_SCENARIO_NAME} /> <TextFieldHelperText validationMsg={true}> <span>{this.state.err}</span> </TextFieldHelperText> </IDDialog> ); } } export default IDNewScenarioDialog;
27.309735
79
0.626377
1e0484d967911cd6de3df6c4ec04cd2f1dfd5911
673,345
js
JavaScript
plugin/editor/smarteditor/js/smarteditor2.js
toptal3/MIXTAGE
2ccce1aa54fb7e885f6cc440b02f89d56537dc65
[ "MIT" ]
1
2020-07-20T13:12:06.000Z
2020-07-20T13:12:06.000Z
plugin/editor/smarteditor/js/smarteditor2.js
toptal3/MIXTAGE
2ccce1aa54fb7e885f6cc440b02f89d56537dc65
[ "MIT" ]
null
null
null
plugin/editor/smarteditor/js/smarteditor2.js
toptal3/MIXTAGE
2ccce1aa54fb7e885f6cc440b02f89d56537dc65
[ "MIT" ]
null
null
null
/** * SmartEditor2 NHN_Library:SE2.3.10.O11329:SmartEditor2.0-OpenSource * @version 11329 */ var nSE2Version = 11329;if(typeof window.nhn=='undefined') window.nhn = {}; /** * @fileOverview This file contains a function that takes care of various operations related to find and replace * @name N_FindReplace.js */ nhn.FindReplace = jindo.$Class({ sKeyword : "", window : null, document : null, bBrowserSupported : false, // true if End Of Contents is reached during last execution of find bEOC : false, $init : function(win){ this.sInlineContainer = "SPAN|B|U|I|S|STRIKE"; this.rxInlineContainer = new RegExp("^("+this.sInlineContainer+")$"); this.window = win; this.document = this.window.document; if(this.document.domain != this.document.location.hostname){ var oAgentInfo = jindo.$Agent(); var oNavigatorInfo = oAgentInfo.navigator(); if(oNavigatorInfo.firefox && oNavigatorInfo.version < 3){ this.bBrowserSupported = false; this.find = function(){return 3}; return; } } this.bBrowserSupported = true; }, /** * 해당노드의 다음 element를 찾는다. * 찾을 수 없거나 body 이면 body를 리턴 */ _findNextElement : function(elNode){ if(!elNode || elNode.tagName == "BODY"){ return null; } var elNext = elNode.nextSibling; if(elNext){ return (elNext.nodeType == 1 ? elNext : this._findNextElement(elNext)); }else{ return this._findNextElement(elNode.parentNode); } }, // 0: found // 1: not found // 2: keyword required // 3: browser not supported find : function(sKeyword, bCaseMatch, bBackwards, bWholeWord){ var bSearchResult, bFreshSearch; this.window.focus(); if(!sKeyword) return 2; // try find starting from current cursor position this.bEOC = false; bSearchResult = this.findNext(sKeyword, bCaseMatch, bBackwards, bWholeWord); if(bSearchResult) return 0; // end of the contents could have been reached so search again from the beginning this.bEOC = true; bSearchResult = this.findNew(sKeyword, bCaseMatch, bBackwards, bWholeWord); if(bSearchResult) return 0; return 1; }, findNew : function (sKeyword, bCaseMatch, bBackwards, bWholeWord){ this.findReset(); return this.findNext(sKeyword, bCaseMatch, bBackwards, bWholeWord); }, findNext : function(sKeyword, bCaseMatch, bBackwards, bWholeWord){ var bSearchResult; bCaseMatch = bCaseMatch || false; bWholeWord = bWholeWord || false; bBackwards = bBackwards || false; if(this.window.find){ var bWrapAround = false; return this.window.find(sKeyword, bCaseMatch, bBackwards, bWrapAround, bWholeWord); } // IE solution if(this.document.body.createTextRange){ try{ var iOption = 0; if(bBackwards) iOption += 1; if(bWholeWord) iOption += 2; if(bCaseMatch) iOption += 4; this.window.focus(); if(this.document.selection){ this._range = this.document.selection.createRangeCollection().item(0); this._range.collapse(false); }else{ // [SMARTEDITORSUS-1528] IE11인 경우 this._range = this.document.body.createTextRange(); var elNext = this._findNextElement(this.window.getSelection().focusNode); if(elNext){ this._range.moveToElementText(elNext); } } bSearchResult = this._range.findText(sKeyword, 1, iOption); this._range.select(); return bSearchResult; }catch(e){ return false; } } return false; }, findReset : function() { if (this.window.find){ this.window.getSelection().removeAllRanges(); return; } // IE solution if(this.document.body.createTextRange){ if(this.document.selection){ this._range = this.document.body.createTextRange(); this._range.collapse(true); this._range.select(); }else if(this.window.getSelection){ // [SMARTEDITORSUS-1528] IE11인 경우 var oSelection = this.window.getSelection(); oSelection.removeAllRanges(); oSelection.selectAllChildren(this.document.body); oSelection.collapseToStart(); } } }, // 0: replaced & next word found // 1: replaced & next word not found // 2: not replaced & next word found // 3: not replaced & next word not found // 4: sOriginalWord required replace : function(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord){ return this._replace(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord); }, /** * [SMARTEDITORSUS-1591] 크롬에서 replaceAll 시 selection 을 새로 만들면 첫번째 단어가 삭제되지 않고 남는 문제가 있어서 * selection 객체를 받아서 사용할 수 있도록 private 메서드 추가 * TODO: 근본적으로 HuskyRange 를 리팩토링할 필요가 있음 */ _replace : function(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord, oSelection){ if(!sOriginalWord) return 4; oSelection = oSelection || new nhn.HuskyRange(this.window); oSelection.setFromSelection(); bCaseMatch = bCaseMatch || false; var bMatch, selectedText = oSelection.toString(); if(bCaseMatch) bMatch = (selectedText == sOriginalWord); else bMatch = (selectedText.toLowerCase() == sOriginalWord.toLowerCase()); if(!bMatch) return this.find(sOriginalWord, bCaseMatch, bBackwards, bWholeWord)+2; if(typeof Replacement == "function"){ // the returned oSelection must contain the replacement oSelection = Replacement(oSelection); }else{ oSelection.pasteText(Replacement); } // force it to find the NEXT occurance of sOriginalWord oSelection.select(); return this.find(sOriginalWord, bCaseMatch, bBackwards, bWholeWord); }, // returns number of replaced words // -1 : if original word is not given replaceAll : function(sOriginalWord, Replacement, bCaseMatch, bWholeWord){ if(!sOriginalWord) return -1; var bBackwards = false; var iReplaceResult; var iResult = 0; var win = this.window; if(this.find(sOriginalWord, bCaseMatch, bBackwards, bWholeWord) !== 0){ return iResult; } var oSelection = new nhn.HuskyRange(this.window); oSelection.setFromSelection(); // 시작점의 북마크가 지워지면서 시작점을 지나서 replace가 되는 현상 방지용 // 첫 단어 앞쪽에 특수 문자 삽입 해서, replace와 함께 북마크가 사라지는 것 방지 oSelection.collapseToStart(); var oTmpNode = this.window.document.createElement("SPAN"); oTmpNode.innerHTML = unescape("%uFEFF"); oSelection.insertNode(oTmpNode); oSelection.select(); var sBookmark = oSelection.placeStringBookmark(); this.bEOC = false; while(!this.bEOC){ iReplaceResult = this._replace(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord, oSelection); if(iReplaceResult == 0 || iReplaceResult == 1){ iResult++; } } var startingPointReached = function(){ var oCurSelection = new nhn.HuskyRange(win); oCurSelection.setFromSelection(); oSelection.moveToBookmark(sBookmark); var pos = oSelection.compareBoundaryPoints(nhn.W3CDOMRange.START_TO_END, oCurSelection); if(pos == 1) return false; return true; }; iReplaceResult = 0; this.bEOC = false; while(!startingPointReached() && iReplaceResult == 0 && !this.bEOC){ iReplaceResult = this._replace(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord, oSelection); if(iReplaceResult == 0 || iReplaceResult == 1){ iResult++; } } oSelection.moveToBookmark(sBookmark); oSelection.deleteContents(); // [SMARTEDITORSUS-1591] 크롬에서 첫번째 단어가 삭제되지 않는 경우가 있으므로 select()메서드대신 deleteContents() 메서드를 호출한다. oSelection.removeStringBookmark(sBookmark); // setTimeout 없이 바로 지우면 IE8 브라우저가 빈번하게 죽어버림 setTimeout(function(){ oTmpNode.parentNode.removeChild(oTmpNode); }, 0); return iResult; }, _isBlankTextNode : function(oNode){ if(oNode.nodeType == 3 && oNode.nodeValue == ""){return true;} return false; }, _getNextNode : function(elNode, bDisconnected){ if(!elNode || elNode.tagName == "BODY"){ return {elNextNode: null, bDisconnected: false}; } if(elNode.nextSibling){ elNode = elNode.nextSibling; while(elNode.firstChild){ if(elNode.tagName && !this.rxInlineContainer.test(elNode.tagName)){ bDisconnected = true; } elNode = elNode.firstChild; } return {elNextNode: elNode, bDisconnected: bDisconnected}; } return this._getNextNode(nhn.DOMFix.parentNode(elNode), bDisconnected); }, _getNextTextNode : function(elNode, bDisconnected){ var htNextNode, elNode; while(true){ htNextNode = this._getNextNode(elNode, bDisconnected); elNode = htNextNode.elNextNode; bDisconnected = htNextNode.bDisconnected; if(elNode && elNode.nodeType != 3 && !this.rxInlineContainer.test(elNode.tagName)){ bDisconnected = true; } if(!elNode || (elNode.nodeType==3 && !this._isBlankTextNode(elNode))){ break; } } return {elNextText: elNode, bDisconnected: bDisconnected}; }, _getFirstTextNode : function(){ // 문서에서 제일 앞쪽에 위치한 아무 노드 찾기 var elFirstNode = this.document.body.firstChild; while(!!elFirstNode && elFirstNode.firstChild){ elFirstNode = elFirstNode.firstChild; } // 문서에 아무 노드도 없음 if(!elFirstNode){ return null; } // 처음 노드가 텍스트 노드가 아니거나 bogus 노드라면 다음 텍스트 노드를 찾음 if(elFirstNode.nodeType != 3 || this._isBlankTextNode(elFirstNode)){ var htTmp = this._getNextTextNode(elFirstNode, false); elFirstNode = htTmp.elNextText; } return elFirstNode; }, _addToTextMap : function(elNode, aTexts, aElTexts, nLen){ var nStartPos = aTexts[nLen].length; for(var i=0, nTo=elNode.nodeValue.length; i<nTo; i++){ aElTexts[nLen][nStartPos+i] = [elNode, i]; } aTexts[nLen] += elNode.nodeValue; }, _createTextMap : function(){ var aTexts = []; var aElTexts = []; var nLen=-1; var elNode = this._getFirstTextNode(); var htNextNode = {elNextText: elNode, bDisconnected: true}; while(elNode){ if(htNextNode.bDisconnected){ nLen++; aTexts[nLen] = ""; aElTexts[nLen] = []; } this._addToTextMap(htNextNode.elNextText, aTexts, aElTexts, nLen); htNextNode = this._getNextTextNode(elNode, false); elNode = htNextNode.elNextText; } return {aTexts: aTexts, aElTexts: aElTexts}; }, replaceAll_js : function(sOriginalWord, Replacement, bCaseMatch, bWholeWord){ try{ var t0 = new Date(); var htTmp = this._createTextMap(); var t1 = new Date(); var aTexts = htTmp.aTexts; var aElTexts = htTmp.aElTexts; // console.log(sOriginalWord); // console.log(aTexts); // console.log(aElTexts); var nMatchCnt = 0; var nOriginLen = sOriginalWord.length; // 단어 한개씩 비교 for(var i=0, niLen=aTexts.length; i<niLen; i++){ var sText = aTexts[i]; // 단어 안에 한글자씩 비교 //for(var j=0, njLen=sText.length - nOriginLen; j<njLen; j++){ for(var j=sText.length-nOriginLen; j>=0; j--){ var sTmp = sText.substring(j, j+nOriginLen); if(bWholeWord && (j > 0 && sText.charAt(j-1).match(/[a-zA-Z가-힣]/)) ){ continue; } if(sTmp == sOriginalWord){ nMatchCnt++; var oSelection = new nhn.HuskyRange(this.window); // 마지막 글자의 뒷부분 처리 var elContainer, nOffset; if(j+nOriginLen < aElTexts[i].length){ elContainer = aElTexts[i][j+nOriginLen][0]; nOffset = aElTexts[i][j+nOriginLen][1]; }else{ elContainer = aElTexts[i][j+nOriginLen-1][0]; nOffset = aElTexts[i][j+nOriginLen-1][1]+1; } oSelection.setEnd(elContainer, nOffset, true, true); oSelection.setStart(aElTexts[i][j][0], aElTexts[i][j][1], true); if(typeof Replacement == "function"){ // the returned oSelection must contain the replacement oSelection = Replacement(oSelection); }else{ oSelection.pasteText(Replacement); } j -= nOriginLen; } continue; } } /* var t2 = new Date(); console.log("OK"); console.log(sOriginalWord); console.log("MC:"+(t1-t0)); console.log("RP:"+(t2-t1)); */ return nMatchCnt; }catch(e){ /* console.log("ERROR"); console.log(sOriginalWord); console.log(new Date()-t0); */ return nMatchCnt; } } }); // "padding", "backgroundcolor", "border", "borderTop", "borderRight", "borderBottom", "borderLeft", "color", "textAlign", "fontWeight" nhn.husky.SE2M_TableTemplate = [ {}, /* // 0 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px dashed #666666", borderRight : "0", borderBottom : "0" }, aRowStyle : [ { padding : "3px 0 2px 0", border : "1px dashed #666666", borderTop : "0", borderLeft : "0" } ] }, // 1 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px solid #c7c7c7", borderRight : "0", borderBottom : "0" }, aRowStyle : [ { padding : "3px 0 2px 0", border : "1px solid #c7c7c7", borderTop : "0", borderLeft : "0" } ] }, // 2 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { border : "1px solid #c7c7c7" }, aRowStyle : [ { padding : "2px 0 1px 0", border : "1px solid #c7c7c7" } ] }, // 3 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { border : "1px double #c7c7c7" }, aRowStyle : [ { padding : "1px 0 0", border : "3px double #c7c7c7" } ] }, // 4 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { borderWidth : "2px 1px 1px 2px", borderStyle : "solid", borderColor : "#c7c7c7" }, aRowStyle : [ { padding : "2px 0 0", borderWidth : "1px 2px 2px 1px", borderStyle : "solid", borderColor : "#c7c7c7" } ] }, // 5 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { borderWidth : "1px 2px 2px 1px", borderStyle : "solid", borderColor : "#c7c7c7" }, aRowStyle : [ { padding : "1px 0 0", borderWidth : "2px 1px 1px 2px", borderStyle : "solid", borderColor : "#c7c7c7" } ] }, */ // Black theme ====================================================== // 6 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" } ] }, // 7 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" }, { padding : "3px 4px 2px", backgroundColor : "#f3f3f3", color : "#666666" } ] }, // 8 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { backgroundColor : "#ffffff", borderTop : "1px solid #c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #c7c7c7", backgroundColor : "#ffffff", color : "#666666" }, { padding : "3px 4px 2px", borderBottom : "1px solid #c7c7c7", backgroundColor : "#f3f3f3", color : "#666666" } ] }, // 9 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px solid #c7c7c7" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#f3f3f3", color : "#666666", borderRight : "1px solid #e7e7e7", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", borderTop : "1px solid #e7e7e7", borderRight : "1px solid #e7e7e7", color : "#666666" } ] }, // 10 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#f8f8f8", color : "#666666" }, { padding : "3px 4px 2px", backgroundColor : "#ebebeb", color : "#666666" } ] }, // 11 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, ht1stRowStyle : { padding : "3px 4px 2px", borderTop : "1px solid #000000", borderBottom : "1px solid #000000", backgroundColor : "#333333", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#ffffff", color : "#666666" }, { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#f8f8f8", color : "#666666" } ] }, // 12 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#333333", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#f8f8f8", color : "#666666", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" } ] }, // 13 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#333333", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" } ] }, // Blue theme ====================================================== // 14 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" } ] }, // 15 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" }, { padding : "3px 4px 2px", backgroundColor : "#f6f8fa", color : "#3d76ab" } ] }, // 16 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { backgroundColor : "#ffffff", borderTop : "1px solid #a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #a6bcd1", backgroundColor : "#ffffff", color : "#3d76ab" }, { padding : "3px 4px 2px", borderBottom : "1px solid #a6bcd1", backgroundColor : "#f6f8fa", color : "#3d76ab" } ] }, // 17 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px solid #a6bcd1" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#f6f8fa", color : "#3d76ab", borderRight : "1px solid #e1eef7", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", borderTop : "1px solid #e1eef7", borderRight : "1px solid #e1eef7", color : "#3d76ab" } ] }, // 18 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#fafbfc", color : "#3d76ab" }, { padding : "3px 4px 2px", backgroundColor : "#e6ecf2", color : "#3d76ab" } ] }, // 19 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, ht1stRowStyle : { padding : "3px 4px 2px", borderTop : "1px solid #466997", borderBottom : "1px solid #466997", backgroundColor : "#6284ab", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#ffffff", color : "#3d76ab" }, { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#f6f8fa", color : "#3d76ab" } ] }, // 20 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#6284ab", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#f6f8fa", color : "#3d76ab", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" } ] }, // 21 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#6284ab", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" } ] } ]; if(typeof window.nhn=='undefined'){window.nhn = {};} if (!nhn.husky){nhn.husky = {};} nhn.husky.oMockDebugger = { log_MessageStart: function() {}, log_MessageEnd: function() {}, log_MessageStepStart: function() {}, log_MessageStepEnd: function() {}, log_CallHandlerStart: function() {}, log_CallHandlerEnd: function() {}, handleException: function() {}, setApp: function() {} }; //{ /** * @fileOverview This file contains Husky framework core * @name HuskyCore.js */ nhn.husky.HuskyCore = jindo.$Class({ name : "HuskyCore", aCallerStack : null, $init : function(htOptions){ this.htOptions = htOptions||{}; if( this.htOptions.oDebugger ){ if( !nhn.husky.HuskyCore._cores ) { nhn.husky.HuskyCore._cores = []; nhn.husky.HuskyCore.getCore = function() { return nhn.husky.HuskyCore._cores; }; } nhn.husky.HuskyCore._cores.push(this); this.htOptions.oDebugger.setApp(this); } // To prevent processing a Husky message before all the plugins are registered and ready, // Queue up all the messages here until the application's status is changed to READY this.messageQueue = []; this.oMessageMap = {}; this.oDisabledMessage = {}; this.aPlugins = []; this.appStatus = nhn.husky.APP_STATUS.NOT_READY; this.aCallerStack = []; this._fnWaitForPluginReady = jindo.$Fn(this._waitForPluginReady, this).bind(); // Register the core as a plugin so it can receive messages this.registerPlugin(this); }, setDebugger: function(oDebugger) { this.htOptions.oDebugger = oDebugger; oDebugger.setApp(this); }, exec : function(msg, args, oEvent){ // If the application is not yet ready just queue the message if(this.appStatus == nhn.husky.APP_STATUS.NOT_READY){ this.messageQueue[this.messageQueue.length] = {'msg':msg, 'args':args, 'event':oEvent}; return true; } this.exec = this._exec; this.exec(msg, args, oEvent); }, delayedExec : function(msg, args, nDelay, oEvent){ var fExec = jindo.$Fn(this.exec, this).bind(msg, args, oEvent); setTimeout(fExec, nDelay); }, _exec : function(msg, args, oEvent){ return (this._exec = this.htOptions.oDebugger?this._execWithDebugger:this._execWithoutDebugger).call(this, msg, args, oEvent); }, _execWithDebugger : function(msg, args, oEvent){ this.htOptions.oDebugger.log_MessageStart(msg, args); var bResult = this._doExec(msg, args, oEvent); this.htOptions.oDebugger.log_MessageEnd(msg, args); return bResult; }, _execWithoutDebugger : function(msg, args, oEvent){ return this._doExec(msg, args, oEvent); }, _doExec : function(msg, args, oEvent){ var bContinue = false; if(!this.oDisabledMessage[msg]){ var allArgs = []; if(args && args.length){ var iLen = args.length; for(var i=0; i<iLen; i++){allArgs[i] = args[i];} } if(oEvent){allArgs[allArgs.length] = oEvent;} bContinue = this._execMsgStep("BEFORE", msg, allArgs); if(bContinue){bContinue = this._execMsgStep("ON", msg, allArgs);} if(bContinue){bContinue = this._execMsgStep("AFTER", msg, allArgs);} } return bContinue; }, registerPlugin : function(oPlugin){ if(!oPlugin){throw("An error occured in registerPlugin(): invalid plug-in");} oPlugin.nIdx = this.aPlugins.length; oPlugin.oApp = this; this.aPlugins[oPlugin.nIdx] = oPlugin; // If the plugin does not specify that it takes time to be ready, change the stauts to READY right away if(oPlugin.status != nhn.husky.PLUGIN_STATUS.NOT_READY){oPlugin.status = nhn.husky.PLUGIN_STATUS.READY;} // If run() function had been called already, need to recreate the message map if(this.appStatus != nhn.husky.APP_STATUS.NOT_READY){ for(var funcName in oPlugin){ if(funcName.match(/^\$(LOCAL|BEFORE|ON|AFTER)_/)){ this.addToMessageMap(funcName, oPlugin); } } } this.exec("MSG_PLUGIN_REGISTERED", [oPlugin]); return oPlugin.nIdx; }, disableMessage : function(sMessage, bDisable){this.oDisabledMessage[sMessage] = bDisable;}, registerBrowserEvent : function(obj, sEvent, sMessage, aParams, nDelay){ aParams = aParams || []; var func = (nDelay)?jindo.$Fn(this.delayedExec, this).bind(sMessage, aParams, nDelay):jindo.$Fn(this.exec, this).bind(sMessage, aParams); return jindo.$Fn(func, this).attach(obj, sEvent); }, run : function(htOptions){ this.htRunOptions = htOptions || {}; // Change the status from NOT_READY to let exec to process all the way this._changeAppStatus(nhn.husky.APP_STATUS.WAITING_FOR_PLUGINS_READY); // Process all the messages in the queue var iQueueLength = this.messageQueue.length; for(var i=0; i<iQueueLength; i++){ var curMsgAndArgs = this.messageQueue[i]; this.exec(curMsgAndArgs.msg, curMsgAndArgs.args, curMsgAndArgs.event); } this._fnWaitForPluginReady(); }, acceptLocalBeforeFirstAgain : function(oPlugin, bAccept){ // LOCAL_BEFORE_FIRST will be fired again if oPlugin._husky_bRun == false oPlugin._husky_bRun = !bAccept; }, // Use this also to update the mapping createMessageMap : function(sMsgHandler){ this.oMessageMap[sMsgHandler] = []; var nLen = this.aPlugins.length; for(var i=0; i<nLen; i++){this._doAddToMessageMap(sMsgHandler, this.aPlugins[i]);} }, addToMessageMap : function(sMsgHandler, oPlugin){ // cannot "ADD" unless the map is already created. // the message will be added automatically to the mapping when it is first passed anyways, so do not add now if(!this.oMessageMap[sMsgHandler]){return;} this._doAddToMessageMap(sMsgHandler, oPlugin); }, _changeAppStatus : function(appStatus){ this.appStatus = appStatus; // Initiate MSG_APP_READY if the application's status is being switched to READY if(this.appStatus == nhn.husky.APP_STATUS.READY){this.exec("MSG_APP_READY");} }, _execMsgStep : function(sMsgStep, sMsg, args){ return (this._execMsgStep = this.htOptions.oDebugger?this._execMsgStepWithDebugger:this._execMsgStepWithoutDebugger).call(this, sMsgStep, sMsg, args); }, _execMsgStepWithDebugger : function(sMsgStep, sMsg, args){ this.htOptions.oDebugger.log_MessageStepStart(sMsgStep, sMsg, args); var bStatus = this._execMsgHandler("$"+sMsgStep+"_"+sMsg, args); this.htOptions.oDebugger.log_MessageStepEnd(sMsgStep, sMsg, args); return bStatus; }, _execMsgStepWithoutDebugger : function(sMsgStep, sMsg, args){ return this._execMsgHandler ("$"+sMsgStep+"_"+sMsg, args); }, _execMsgHandler : function(sMsgHandler, args){ var i; if(!this.oMessageMap[sMsgHandler]){ this.createMessageMap(sMsgHandler); } var aPlugins = this.oMessageMap[sMsgHandler]; var iNumOfPlugins = aPlugins.length; if(iNumOfPlugins === 0){return true;} var bResult = true; // two similar codes were written twice due to the performace. if(sMsgHandler.match(/^\$(BEFORE|ON|AFTER)_MSG_APP_READY$/)){ for(i=0; i<iNumOfPlugins; i++){ if(this._execHandler(aPlugins[i], sMsgHandler, args) === false){ bResult = false; break; } } }else{ for(i=0; i<iNumOfPlugins; i++){ if(!aPlugins[i]._husky_bRun){ aPlugins[i]._husky_bRun = true; if(typeof aPlugins[i].$LOCAL_BEFORE_FIRST == "function" && this._execHandler(aPlugins[i], "$LOCAL_BEFORE_FIRST", [sMsgHandler, args]) === false){continue;} } if(typeof aPlugins[i].$LOCAL_BEFORE_ALL == "function"){ if(this._execHandler(aPlugins[i], "$LOCAL_BEFORE_ALL", [sMsgHandler, args]) === false){continue;} } if(this._execHandler(aPlugins[i], sMsgHandler, args) === false){ bResult = false; break; } } } return bResult; }, _execHandler : function(oPlugin, sHandler, args){ return (this._execHandler = this.htOptions.oDebugger?this._execHandlerWithDebugger:this._execHandlerWithoutDebugger).call(this, oPlugin, sHandler, args); }, _execHandlerWithDebugger : function(oPlugin, sHandler, args){ this.htOptions.oDebugger.log_CallHandlerStart(oPlugin, sHandler, args); var bResult; try{ this.aCallerStack.push(oPlugin); bResult = oPlugin[sHandler].apply(oPlugin, args); this.aCallerStack.pop(); }catch(e){ this.htOptions.oDebugger.handleException(e); bResult = false; } this.htOptions.oDebugger.log_CallHandlerEnd(oPlugin, sHandler, args); return bResult; }, _execHandlerWithoutDebugger : function(oPlugin, sHandler, args){ this.aCallerStack.push(oPlugin); var bResult = oPlugin[sHandler].apply(oPlugin, args); this.aCallerStack.pop(); return bResult; }, _doAddToMessageMap : function(sMsgHandler, oPlugin){ if(typeof oPlugin[sMsgHandler] != "function"){return;} var aMap = this.oMessageMap[sMsgHandler]; // do not add if the plugin is already in the mapping for(var i=0, iLen=aMap.length; i<iLen; i++){ if(this.oMessageMap[sMsgHandler][i] == oPlugin){return;} } this.oMessageMap[sMsgHandler][i] = oPlugin; }, _waitForPluginReady : function(){ var bAllReady = true; for(var i=0; i<this.aPlugins.length; i++){ if(this.aPlugins[i].status == nhn.husky.PLUGIN_STATUS.NOT_READY){ bAllReady = false; break; } } if(bAllReady){ this._changeAppStatus(nhn.husky.APP_STATUS.READY); }else{ setTimeout(this._fnWaitForPluginReady, 100); } } }); //} nhn.husky.APP_STATUS = { 'NOT_READY' : 0, 'WAITING_FOR_PLUGINS_READY' : 1, 'READY' : 2 }; nhn.husky.PLUGIN_STATUS = { 'NOT_READY' : 0, 'READY' : 1 }; if(typeof window.nhn=='undefined'){window.nhn = {};} nhn.CurrentSelection_IE = function(){ this.getCommonAncestorContainer = function(){ try{ this._oSelection = this._document.selection; if(this._oSelection.type == "Control"){ return this._oSelection.createRange().item(0); }else{ return this._oSelection.createRangeCollection().item(0).parentElement(); } }catch(e){ return this._document.body; } }; this.isCollapsed = function(){ this._oSelection = this._document.selection; return this._oSelection.type == "None"; }; }; nhn.CurrentSelection_FF = function(){ this.getCommonAncestorContainer = function(){ return this._getSelection().commonAncestorContainer; }; this.isCollapsed = function(){ var oSelection = this._window.getSelection(); if(oSelection.rangeCount<1){ return true; } return oSelection.getRangeAt(0).collapsed; }; this._getSelection = function(){ try{ return this._window.getSelection().getRangeAt(0); }catch(e){ return this._document.createRange(); } }; }; nhn.CurrentSelection = new (jindo.$Class({ $init : function(){ var oAgentInfo = jindo.$Agent().navigator(); if(oAgentInfo.ie && document.selection){ nhn.CurrentSelection_IE.apply(this); }else{ nhn.CurrentSelection_FF.apply(this); } }, setWindow : function(oWin){ this._window = oWin; this._document = oWin.document; } }))(); /** * @fileOverview This file contains a cross-browser implementation of W3C's DOM Range * @name W3CDOMRange.js */ nhn.W3CDOMRange = jindo.$Class({ $init : function(win){ this.reset(win); }, reset : function(win){ this._window = win; this._document = this._window.document; this.collapsed = true; this.commonAncestorContainer = this._document.body; this.endContainer = this._document.body; this.endOffset = 0; this.startContainer = this._document.body; this.startOffset = 0; this.oBrowserSelection = new nhn.BrowserSelection(this._window); this.selectionLoaded = this.oBrowserSelection.selectionLoaded; }, cloneContents : function(){ var oClonedContents = this._document.createDocumentFragment(); var oTmpContainer = this._document.createDocumentFragment(); var aNodes = this._getNodesInRange(); if(aNodes.length < 1){return oClonedContents;} var oClonedContainers = this._constructClonedTree(aNodes, oTmpContainer); // oTopContainer = aNodes[aNodes.length-1].parentNode and this is not part of the initial array and only those child nodes should be cloned var oTopContainer = oTmpContainer.firstChild; if(oTopContainer){ var elCurNode = oTopContainer.firstChild; var elNextNode; while(elCurNode){ elNextNode = elCurNode.nextSibling; oClonedContents.appendChild(elCurNode); elCurNode = elNextNode; } } oClonedContainers = this._splitTextEndNodes({oStartContainer: oClonedContainers.oStartContainer, iStartOffset: this.startOffset, oEndContainer: oClonedContainers.oEndContainer, iEndOffset: this.endOffset}); if(oClonedContainers.oStartContainer && oClonedContainers.oStartContainer.previousSibling){ nhn.DOMFix.parentNode(oClonedContainers.oStartContainer).removeChild(oClonedContainers.oStartContainer.previousSibling); } if(oClonedContainers.oEndContainer && oClonedContainers.oEndContainer.nextSibling){ nhn.DOMFix.parentNode(oClonedContainers.oEndContainer).removeChild(oClonedContainers.oEndContainer.nextSibling); } return oClonedContents; }, _constructClonedTree : function(aNodes, oClonedParentNode){ var oClonedStartContainer = null; var oClonedEndContainer = null; var oStartContainer = this.startContainer; var oEndContainer = this.endContainer; var _recurConstructClonedTree = function(aAllNodes, iCurIdx, oClonedParentNode){ if(iCurIdx < 0){return iCurIdx;} var iChildIdx = iCurIdx-1; var oCurNodeCloneWithChildren = aAllNodes[iCurIdx].cloneNode(false); if(aAllNodes[iCurIdx] == oStartContainer){oClonedStartContainer = oCurNodeCloneWithChildren;} if(aAllNodes[iCurIdx] == oEndContainer){oClonedEndContainer = oCurNodeCloneWithChildren;} while(iChildIdx >= 0 && nhn.DOMFix.parentNode(aAllNodes[iChildIdx]) == aAllNodes[iCurIdx]){ iChildIdx = this._recurConstructClonedTree(aAllNodes, iChildIdx, oCurNodeCloneWithChildren); } // this may trigger an error message in IE when an erroneous script is inserted oClonedParentNode.insertBefore(oCurNodeCloneWithChildren, oClonedParentNode.firstChild); return iChildIdx; }; this._recurConstructClonedTree = _recurConstructClonedTree; aNodes[aNodes.length] = nhn.DOMFix.parentNode(aNodes[aNodes.length-1]); this._recurConstructClonedTree(aNodes, aNodes.length-1, oClonedParentNode); return {oStartContainer: oClonedStartContainer, oEndContainer: oClonedEndContainer}; }, cloneRange : function(){ return this._copyRange(new nhn.W3CDOMRange(this._window)); }, _copyRange : function(oClonedRange){ oClonedRange.collapsed = this.collapsed; oClonedRange.commonAncestorContainer = this.commonAncestorContainer; oClonedRange.endContainer = this.endContainer; oClonedRange.endOffset = this.endOffset; oClonedRange.startContainer = this.startContainer; oClonedRange.startOffset = this.startOffset; oClonedRange._document = this._document; return oClonedRange; }, collapse : function(toStart){ if(toStart){ this.endContainer = this.startContainer; this.endOffset = this.startOffset; }else{ this.startContainer = this.endContainer; this.startOffset = this.endOffset; } this._updateRangeInfo(); }, compareBoundaryPoints : function(how, sourceRange){ switch(how){ case nhn.W3CDOMRange.START_TO_START: return this._compareEndPoint(this.startContainer, this.startOffset, sourceRange.startContainer, sourceRange.startOffset); case nhn.W3CDOMRange.START_TO_END: return this._compareEndPoint(this.endContainer, this.endOffset, sourceRange.startContainer, sourceRange.startOffset); case nhn.W3CDOMRange.END_TO_END: return this._compareEndPoint(this.endContainer, this.endOffset, sourceRange.endContainer, sourceRange.endOffset); case nhn.W3CDOMRange.END_TO_START: return this._compareEndPoint(this.startContainer, this.startOffset, sourceRange.endContainer, sourceRange.endOffset); } }, _findBody : function(oNode){ if(!oNode){return null;} while(oNode){ if(oNode.tagName == "BODY"){return oNode;} oNode = nhn.DOMFix.parentNode(oNode); } return null; }, _compareEndPoint : function(oContainerA, iOffsetA, oContainerB, iOffsetB){ return this.oBrowserSelection.compareEndPoints(oContainerA, iOffsetA, oContainerB, iOffsetB); var iIdxA, iIdxB; if(!oContainerA || this._findBody(oContainerA) != this._document.body){ oContainerA = this._document.body; iOffsetA = 0; } if(!oContainerB || this._findBody(oContainerB) != this._document.body){ oContainerB = this._document.body; iOffsetB = 0; } var compareIdx = function(iIdxA, iIdxB){ // iIdxX == -1 when the node is the commonAncestorNode // if iIdxA == -1 // -> [[<nodeA>...<nodeB></nodeB>]]...</nodeA> // if iIdxB == -1 // -> <nodeB>...[[<nodeA></nodeA>...</nodeB>]] if(iIdxB == -1){iIdxB = iIdxA+1;} if(iIdxA < iIdxB){return -1;} if(iIdxA == iIdxB){return 0;} return 1; }; var oCommonAncestor = this._getCommonAncestorContainer(oContainerA, oContainerB); // ================================================================================================================================================ // Move up both containers so that both containers are direct child nodes of the common ancestor node. From there, just compare the offset // Add 0.5 for each contaienrs that has "moved up" since the actual node is wrapped by 1 or more parent nodes and therefore its position is somewhere between idx & idx+1 // <COMMON_ANCESTOR>NODE1<P>NODE2</P>NODE3</COMMON_ANCESTOR> // The position of NODE2 in COMMON_ANCESTOR is somewhere between after NODE1(idx1) and before NODE3(idx2), so we let that be 1.5 // container node A in common ancestor container var oNodeA = oContainerA; var oTmpNode = null; if(oNodeA != oCommonAncestor){ while((oTmpNode = nhn.DOMFix.parentNode(oNodeA)) != oCommonAncestor){oNodeA = oTmpNode;} iIdxA = this._getPosIdx(oNodeA)+0.5; }else{ iIdxA = iOffsetA; } // container node B in common ancestor container var oNodeB = oContainerB; if(oNodeB != oCommonAncestor){ while((oTmpNode = nhn.DOMFix.parentNode(oNodeB)) != oCommonAncestor){oNodeB = oTmpNode;} iIdxB = this._getPosIdx(oNodeB)+0.5; }else{ iIdxB = iOffsetB; } return compareIdx(iIdxA, iIdxB); }, _getCommonAncestorContainer : function(oNode1, oNode2){ oNode1 = oNode1 || this.startContainer; oNode2 = oNode2 || this.endContainer; var oComparingNode = oNode2; while(oNode1){ while(oComparingNode){ if(oNode1 == oComparingNode){return oNode1;} oComparingNode = nhn.DOMFix.parentNode(oComparingNode); } oComparingNode = oNode2; oNode1 = nhn.DOMFix.parentNode(oNode1); } return this._document.body; }, deleteContents : function(){ if(this.collapsed){return;} this._splitTextEndNodesOfTheRange(); var aNodes = this._getNodesInRange(); if(aNodes.length < 1){return;} var oPrevNode = aNodes[0].previousSibling; while(oPrevNode && this._isBlankTextNode(oPrevNode)){oPrevNode = oPrevNode.previousSibling;} var oNewStartContainer, iNewOffset = -1; if(!oPrevNode){ oNewStartContainer = nhn.DOMFix.parentNode(aNodes[0]); iNewOffset = 0; } for(var i=0; i<aNodes.length; i++){ var oNode = aNodes[i]; if(!oNode.firstChild || this._isAllChildBlankText(oNode)){ if(oNewStartContainer == oNode){ iNewOffset = this._getPosIdx(oNewStartContainer); oNewStartContainer = nhn.DOMFix.parentNode(oNode); } nhn.DOMFix.parentNode(oNode).removeChild(oNode); }else{ // move the starting point to out of the parent container if the starting point of parent container is meant to be removed // [<span>A]B</span> // -> []<span>B</span> // without these lines, the result would yeild to // -> <span>[]B</span> if(oNewStartContainer == oNode && iNewOffset === 0){ iNewOffset = this._getPosIdx(oNewStartContainer); oNewStartContainer = nhn.DOMFix.parentNode(oNode); } } } if(!oPrevNode){ this.setStart(oNewStartContainer, iNewOffset, true, true); }else{ if(oPrevNode.tagName == "BODY"){ this.setStartBefore(oPrevNode, true); }else{ this.setStartAfter(oPrevNode, true); } } this.collapse(true); }, extractContents : function(){ var oClonedContents = this.cloneContents(); this.deleteContents(); return oClonedContents; }, getInsertBeforeNodes : function(){ var oFirstNode = null; var oParentContainer; if(this.startContainer.nodeType == "3"){ oParentContainer = nhn.DOMFix.parentNode(this.startContainer); if(this.startContainer.nodeValue.length <= this.startOffset){ oFirstNode = this.startContainer.nextSibling; }else{ oFirstNode = this.startContainer.splitText(this.startOffset); } }else{ oParentContainer = this.startContainer; oFirstNode = nhn.DOMFix.childNodes(this.startContainer)[this.startOffset]; } if(!oFirstNode || !nhn.DOMFix.parentNode(oFirstNode)){oFirstNode = null;} return {elParent: oParentContainer, elBefore: oFirstNode}; }, insertNode : function(newNode){ var oInsertBefore = this.getInsertBeforeNodes(); oInsertBefore.elParent.insertBefore(newNode, oInsertBefore.elBefore); this.setStartBefore(newNode); }, selectNode : function(refNode){ this.reset(this._window); this.setStartBefore(refNode); this.setEndAfter(refNode); }, selectNodeContents : function(refNode){ this.reset(this._window); this.setStart(refNode, 0, true); this.setEnd(refNode, nhn.DOMFix.childNodes(refNode).length); }, _endsNodeValidation : function(oNode, iOffset){ if(!oNode || this._findBody(oNode) != this._document.body){throw new Error("INVALID_NODE_TYPE_ERR oNode is not part of current document");} if(oNode.nodeType == 3){ if(iOffset > oNode.nodeValue.length){iOffset = oNode.nodeValue.length;} }else{ if(iOffset > nhn.DOMFix.childNodes(oNode).length){iOffset = nhn.DOMFix.childNodes(oNode).length;} } return iOffset; }, setEnd : function(refNode, offset, bSafe, bNoUpdate){ if(!bSafe){offset = this._endsNodeValidation(refNode, offset);} this.endContainer = refNode; this.endOffset = offset; if(!bNoUpdate){ if(!this.startContainer || this._compareEndPoint(this.startContainer, this.startOffset, this.endContainer, this.endOffset) != -1){ this.collapse(false); }else{ this._updateRangeInfo(); } } }, setEndAfter : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setEndAfter");} if(refNode.tagName == "BODY"){ this.setEnd(refNode, nhn.DOMFix.childNodes(refNode).length, true, bNoUpdate); return; } this.setEnd(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode)+1, true, bNoUpdate); }, setEndBefore : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setEndBefore");} if(refNode.tagName == "BODY"){ this.setEnd(refNode, 0, true, bNoUpdate); return; } this.setEnd(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode), true, bNoUpdate); }, setStart : function(refNode, offset, bSafe, bNoUpdate){ if(!bSafe){offset = this._endsNodeValidation(refNode, offset);} this.startContainer = refNode; this.startOffset = offset; if(!bNoUpdate){ if(!this.endContainer || this._compareEndPoint(this.startContainer, this.startOffset, this.endContainer, this.endOffset) != -1){ this.collapse(true); }else{ this._updateRangeInfo(); } } }, setStartAfter : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setStartAfter");} if(refNode.tagName == "BODY"){ this.setStart(refNode, nhn.DOMFix.childNodes(refNode).length, true, bNoUpdate); return; } this.setStart(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode)+1, true, bNoUpdate); }, setStartBefore : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setStartBefore");} if(refNode.tagName == "BODY"){ this.setStart(refNode, 0, true, bNoUpdate); return; } this.setStart(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode), true, bNoUpdate); }, surroundContents : function(newParent){ newParent.appendChild(this.extractContents()); this.insertNode(newParent); this.selectNode(newParent); }, toString : function(){ var oTmpContainer = this._document.createElement("DIV"); oTmpContainer.appendChild(this.cloneContents()); return oTmpContainer.textContent || oTmpContainer.innerText || ""; }, // this.oBrowserSelection.getCommonAncestorContainer which uses browser's built-in API runs faster but may return an incorrect value. // Call this function to fix the problem. // // In IE, the built-in API would return an incorrect value when, // 1. commonAncestorContainer is not selectable // AND // 2. The selected area will look the same when its child node is selected // eg) // when <P><SPAN>TEST</SPAN></p> is selected, <SPAN>TEST</SPAN> will be returned as commonAncestorContainer fixCommonAncestorContainer : function(){ if(!jindo.$Agent().navigator().ie){ return; } this.commonAncestorContainer = this._getCommonAncestorContainer(); }, _isBlankTextNode : function(oNode){ if(oNode.nodeType == 3 && oNode.nodeValue == ""){return true;} return false; }, _isAllChildBlankText : function(elNode){ for(var i=0, nLen=elNode.childNodes.length; i<nLen; i++){ if(!this._isBlankTextNode(elNode.childNodes[i])){return false;} } return true; }, _getPosIdx : function(refNode){ var idx = 0; for(var node = refNode.previousSibling; node; node = node.previousSibling){idx++;} return idx; }, _updateRangeInfo : function(){ if(!this.startContainer){ this.reset(this._window); return; } // isCollapsed may not function correctly when the cursor is located, // (below a table) AND (at the end of the document where there's no P tag or anything else to actually hold the cursor) this.collapsed = this.oBrowserSelection.isCollapsed(this) || (this.startContainer === this.endContainer && this.startOffset === this.endOffset); // this.collapsed = this._isCollapsed(this.startContainer, this.startOffset, this.endContainer, this.endOffset); this.commonAncestorContainer = this.oBrowserSelection.getCommonAncestorContainer(this); // this.commonAncestorContainer = this._getCommonAncestorContainer(this.startContainer, this.endContainer); }, _isCollapsed : function(oStartContainer, iStartOffset, oEndContainer, iEndOffset){ var bCollapsed = false; if(oStartContainer == oEndContainer && iStartOffset == iEndOffset){ bCollapsed = true; }else{ var oActualStartNode = this._getActualStartNode(oStartContainer, iStartOffset); var oActualEndNode = this._getActualEndNode(oEndContainer, iEndOffset); // Take the parent nodes on the same level for easier comparison when they're next to each other // eg) From // <A> // <B> // <C> // </C> // </B> // <D> // <E> // <F> // </F> // </E> // </D> // </A> // , it's easier to compare the position of B and D rather than C and F because they are siblings // // If the range were collapsed, oActualEndNode will precede oActualStartNode by doing this oActualStartNode = this._getNextNode(this._getPrevNode(oActualStartNode)); oActualEndNode = this._getPrevNode(this._getNextNode(oActualEndNode)); if(oActualStartNode && oActualEndNode && oActualEndNode.tagName != "BODY" && (this._getNextNode(oActualEndNode) == oActualStartNode || (oActualEndNode == oActualStartNode && this._isBlankTextNode(oActualEndNode))) ){ bCollapsed = true; } } return bCollapsed; }, _splitTextEndNodesOfTheRange : function(){ var oEndPoints = this._splitTextEndNodes({oStartContainer: this.startContainer, iStartOffset: this.startOffset, oEndContainer: this.endContainer, iEndOffset: this.endOffset}); this.startContainer = oEndPoints.oStartContainer; this.startOffset = oEndPoints.iStartOffset; this.endContainer = oEndPoints.oEndContainer; this.endOffset = oEndPoints.iEndOffset; }, _splitTextEndNodes : function(oEndPoints){ oEndPoints = this._splitStartTextNode(oEndPoints); oEndPoints = this._splitEndTextNode(oEndPoints); return oEndPoints; }, _splitStartTextNode : function(oEndPoints){ var oStartContainer = oEndPoints.oStartContainer; var iStartOffset = oEndPoints.iStartOffset; var oEndContainer = oEndPoints.oEndContainer; var iEndOffset = oEndPoints.iEndOffset; if(!oStartContainer){return oEndPoints;} if(oStartContainer.nodeType != 3){return oEndPoints;} if(iStartOffset === 0){return oEndPoints;} if(oStartContainer.nodeValue.length <= iStartOffset){return oEndPoints;} var oLastPart = oStartContainer.splitText(iStartOffset); if(oStartContainer == oEndContainer){ iEndOffset -= iStartOffset; oEndContainer = oLastPart; } oStartContainer = oLastPart; iStartOffset = 0; return {oStartContainer: oStartContainer, iStartOffset: iStartOffset, oEndContainer: oEndContainer, iEndOffset: iEndOffset}; }, _splitEndTextNode : function(oEndPoints){ var oStartContainer = oEndPoints.oStartContainer; var iStartOffset = oEndPoints.iStartOffset; var oEndContainer = oEndPoints.oEndContainer; var iEndOffset = oEndPoints.iEndOffset; if(!oEndContainer){return oEndPoints;} if(oEndContainer.nodeType != 3){return oEndPoints;} if(iEndOffset >= oEndContainer.nodeValue.length){return oEndPoints;} if(iEndOffset === 0){return oEndPoints;} oEndContainer.splitText(iEndOffset); return {oStartContainer: oStartContainer, iStartOffset: iStartOffset, oEndContainer: oEndContainer, iEndOffset: iEndOffset}; }, _getNodesInRange : function(){ if(this.collapsed){return [];} var oStartNode = this._getActualStartNode(this.startContainer, this.startOffset); var oEndNode = this._getActualEndNode(this.endContainer, this.endOffset); return this._getNodesBetween(oStartNode, oEndNode); }, _getActualStartNode : function(oStartContainer, iStartOffset){ var oStartNode = oStartContainer; if(oStartContainer.nodeType == 3){ if(iStartOffset >= oStartContainer.nodeValue.length){ oStartNode = this._getNextNode(oStartContainer); if(oStartNode.tagName == "BODY"){oStartNode = null;} }else{ oStartNode = oStartContainer; } }else{ if(iStartOffset < nhn.DOMFix.childNodes(oStartContainer).length){ oStartNode = nhn.DOMFix.childNodes(oStartContainer)[iStartOffset]; }else{ oStartNode = this._getNextNode(oStartContainer); if(oStartNode.tagName == "BODY"){oStartNode = null;} } } return oStartNode; }, _getActualEndNode : function(oEndContainer, iEndOffset){ var oEndNode = oEndContainer; if(iEndOffset === 0){ oEndNode = this._getPrevNode(oEndContainer); if(oEndNode.tagName == "BODY"){oEndNode = null;} }else if(oEndContainer.nodeType == 3){ oEndNode = oEndContainer; }else{ oEndNode = nhn.DOMFix.childNodes(oEndContainer)[iEndOffset-1]; } return oEndNode; }, _getNextNode : function(oNode){ if(!oNode || oNode.tagName == "BODY"){return this._document.body;} if(oNode.nextSibling){return oNode.nextSibling;} return this._getNextNode(nhn.DOMFix.parentNode(oNode)); }, _getPrevNode : function(oNode){ if(!oNode || oNode.tagName == "BODY"){return this._document.body;} if(oNode.previousSibling){return oNode.previousSibling;} return this._getPrevNode(nhn.DOMFix.parentNode(oNode)); }, // includes partially selected // for <div id="a"><div id="b"></div></div><div id="c"></div>, _getNodesBetween(b, c) will yield to b, "a" and c _getNodesBetween : function(oStartNode, oEndNode){ var aNodesBetween = []; this._nNodesBetweenLen = 0; if(!oStartNode || !oEndNode){return aNodesBetween;} // IE may throw an exception on "oCurNode = oCurNode.nextSibling;" when oCurNode is 'invalid', not null or undefined but somehow 'invalid'. // It happened during browser's build-in UNDO with control range selected(table). try{ this._recurGetNextNodesUntil(oStartNode, oEndNode, aNodesBetween); }catch(e){ return []; } return aNodesBetween; }, _recurGetNextNodesUntil : function(oNode, oEndNode, aNodesBetween){ if(!oNode){return false;} if(!this._recurGetChildNodesUntil(oNode, oEndNode, aNodesBetween)){return false;} var oNextToChk = oNode.nextSibling; while(!oNextToChk){ if(!(oNode = nhn.DOMFix.parentNode(oNode))){return false;} aNodesBetween[this._nNodesBetweenLen++] = oNode; if(oNode == oEndNode){return false;} oNextToChk = oNode.nextSibling; } return this._recurGetNextNodesUntil(oNextToChk, oEndNode, aNodesBetween); }, _recurGetChildNodesUntil : function(oNode, oEndNode, aNodesBetween){ if(!oNode){return false;} var bEndFound = false; var oCurNode = oNode; if(oCurNode.firstChild){ oCurNode = oCurNode.firstChild; while(oCurNode){ if(!this._recurGetChildNodesUntil(oCurNode, oEndNode, aNodesBetween)){ bEndFound = true; break; } oCurNode = oCurNode.nextSibling; } } aNodesBetween[this._nNodesBetweenLen++] = oNode; if(bEndFound){return false;} if(oNode == oEndNode){return false;} return true; } }); nhn.W3CDOMRange.START_TO_START = 0; nhn.W3CDOMRange.START_TO_END = 1; nhn.W3CDOMRange.END_TO_END = 2; nhn.W3CDOMRange.END_TO_START = 3; /** * @fileOverview This file contains a cross-browser function that implements all of the W3C's DOM Range specification and some more * @name HuskyRange.js */ nhn.HuskyRange = jindo.$Class({ _rxCursorHolder : /^(?:\uFEFF|\u00A0|\u200B|<br>)$/i, setWindow : function(win){ this.reset(win || window); }, $init : function(win){ this.HUSKY_BOOMARK_START_ID_PREFIX = "husky_bookmark_start_"; this.HUSKY_BOOMARK_END_ID_PREFIX = "husky_bookmark_end_"; this.sBlockElement = "P|DIV|LI|H[1-6]|PRE"; this.sBlockContainer = "BODY|TABLE|TH|TR|TD|UL|OL|BLOCKQUOTE|FORM"; this.rxBlockElement = new RegExp("^("+this.sBlockElement+")$"); this.rxBlockContainer = new RegExp("^("+this.sBlockContainer+")$"); this.rxLineBreaker = new RegExp("^("+this.sBlockElement+"|"+this.sBlockContainer+")$"); this.setWindow(win); }, select : function(){ try{ this.oBrowserSelection.selectRange(this); }catch(e){} }, setFromSelection : function(iNum){ this.setRange(this.oBrowserSelection.getRangeAt(iNum), true); }, setRange : function(oW3CRange, bSafe){ this.reset(this._window); this.setStart(oW3CRange.startContainer, oW3CRange.startOffset, bSafe, true); this.setEnd(oW3CRange.endContainer, oW3CRange.endOffset, bSafe); }, setEndNodes : function(oSNode, oENode){ this.reset(this._window); this.setEndAfter(oENode, true); this.setStartBefore(oSNode); }, splitTextAtBothEnds : function(){ this._splitTextEndNodesOfTheRange(); }, getStartNode : function(){ if(this.collapsed){ if(this.startContainer.nodeType == 3){ if(this.startOffset === 0){return null;} if(this.startContainer.nodeValue.length <= this.startOffset){return null;} return this.startContainer; } return null; } if(this.startContainer.nodeType == 3){ if(this.startOffset >= this.startContainer.nodeValue.length){return this._getNextNode(this.startContainer);} return this.startContainer; }else{ if(this.startOffset >= nhn.DOMFix.childNodes(this.startContainer).length){return this._getNextNode(this.startContainer);} return nhn.DOMFix.childNodes(this.startContainer)[this.startOffset]; } }, getEndNode : function(){ if(this.collapsed){return this.getStartNode();} if(this.endContainer.nodeType == 3){ if(this.endOffset === 0){return this._getPrevNode(this.endContainer);} return this.endContainer; }else{ if(this.endOffset === 0){return this._getPrevNode(this.endContainer);} return nhn.DOMFix.childNodes(this.endContainer)[this.endOffset-1]; } }, getNodeAroundRange : function(bBefore, bStrict){ if(!this.collapsed){return this.getStartNode();} if(this.startContainer && this.startContainer.nodeType == 3){return this.startContainer;} //if(this.collapsed && this.startContainer && this.startContainer.nodeType == 3) return this.startContainer; //if(!this.collapsed || (this.startContainer && this.startContainer.nodeType == 3)) return this.getStartNode(); var oBeforeRange, oAfterRange, oResult; if(this.startOffset >= nhn.DOMFix.childNodes(this.startContainer).length){ oAfterRange = this._getNextNode(this.startContainer); }else{ oAfterRange = nhn.DOMFix.childNodes(this.startContainer)[this.startOffset]; } if(this.endOffset === 0){ oBeforeRange = this._getPrevNode(this.endContainer); }else{ oBeforeRange = nhn.DOMFix.childNodes(this.endContainer)[this.endOffset-1]; } if(bBefore){ oResult = oBeforeRange; if(!oResult && !bStrict){oResult = oAfterRange;} }else{ oResult = oAfterRange; if(!oResult && !bStrict){oResult = oBeforeRange;} } return oResult; }, _getXPath : function(elNode){ var sXPath = ""; while(elNode && elNode.nodeType == 1){ sXPath = "/" + elNode.tagName+"["+this._getPosIdx4XPath(elNode)+"]" + sXPath; elNode = nhn.DOMFix.parentNode(elNode); } return sXPath; }, _getPosIdx4XPath : function(refNode){ var idx = 0; for(var node = refNode.previousSibling; node; node = node.previousSibling){ if(node.tagName == refNode.tagName){idx++;} } return idx; }, // this was written specifically for XPath Bookmark and it may not perform correctly for general purposes _evaluateXPath : function(sXPath, oDoc){ sXPath = sXPath.substring(1, sXPath.length-1); var aXPath = sXPath.split(/\//); var elNode = oDoc.body; for(var i=2; i<aXPath.length && elNode; i++){ aXPath[i].match(/([^\[]+)\[(\d+)/i); var sTagName = RegExp.$1; var nIdx = RegExp.$2; var aAllNodes = nhn.DOMFix.childNodes(elNode); var aNodes = []; var nLength = aAllNodes.length; var nCount = 0; for(var ii=0; ii<nLength; ii++){ if(aAllNodes[ii].tagName == sTagName){aNodes[nCount++] = aAllNodes[ii];} } if(aNodes.length < nIdx){ elNode = null; }else{ elNode = aNodes[nIdx]; } } return elNode; }, _evaluateXPathBookmark : function(oBookmark){ var sXPath = oBookmark["sXPath"]; var nTextNodeIdx = oBookmark["nTextNodeIdx"]; var nOffset = oBookmark["nOffset"]; var elContainer = this._evaluateXPath(sXPath, this._document); if(nTextNodeIdx > -1 && elContainer){ var aChildNodes = nhn.DOMFix.childNodes(elContainer); var elNode = null; var nIdx = nTextNodeIdx; var nOffsetLeft = nOffset; while((elNode = aChildNodes[nIdx]) && elNode.nodeType == 3 && elNode.nodeValue.length < nOffsetLeft){ nOffsetLeft -= elNode.nodeValue.length; nIdx++; } elContainer = nhn.DOMFix.childNodes(elContainer)[nIdx]; nOffset = nOffsetLeft; } if(!elContainer){ elContainer = this._document.body; nOffset = 0; } return {elContainer: elContainer, nOffset: nOffset}; }, // this was written specifically for XPath Bookmark and it may not perform correctly for general purposes getXPathBookmark : function(){ var nTextNodeIdx1 = -1; var htEndPt1 = {elContainer: this.startContainer, nOffset: this.startOffset}; var elNode1 = this.startContainer; if(elNode1.nodeType == 3){ htEndPt1 = this._getFixedStartTextNode(); nTextNodeIdx1 = this._getPosIdx(htEndPt1.elContainer); elNode1 = nhn.DOMFix.parentNode(elNode1); } var sXPathNode1 = this._getXPath(elNode1); var oBookmark1 = {sXPath:sXPathNode1, nTextNodeIdx:nTextNodeIdx1, nOffset: htEndPt1.nOffset}; if(this.collapsed){ var oBookmark2 = {sXPath:sXPathNode1, nTextNodeIdx:nTextNodeIdx1, nOffset: htEndPt1.nOffset}; }else{ var nTextNodeIdx2 = -1; var htEndPt2 = {elContainer: this.endContainer, nOffset: this.endOffset}; var elNode2 = this.endContainer; if(elNode2.nodeType == 3){ htEndPt2 = this._getFixedEndTextNode(); nTextNodeIdx2 = this._getPosIdx(htEndPt2.elContainer); elNode2 = nhn.DOMFix.parentNode(elNode2); } var sXPathNode2 = this._getXPath(elNode2); var oBookmark2 = {sXPath:sXPathNode2, nTextNodeIdx:nTextNodeIdx2, nOffset: htEndPt2.nOffset}; } return [oBookmark1, oBookmark2]; }, moveToXPathBookmark : function(aBookmark){ if(!aBookmark){return false;} var oBookmarkInfo1 = this._evaluateXPathBookmark(aBookmark[0]); var oBookmarkInfo2 = this._evaluateXPathBookmark(aBookmark[1]); if(!oBookmarkInfo1["elContainer"] || !oBookmarkInfo2["elContainer"]){return;} this.startContainer = oBookmarkInfo1["elContainer"]; this.startOffset = oBookmarkInfo1["nOffset"]; this.endContainer = oBookmarkInfo2["elContainer"]; this.endOffset = oBookmarkInfo2["nOffset"]; return true; }, _getFixedTextContainer : function(elNode, nOffset){ while(elNode && elNode.nodeType == 3 && elNode.previousSibling && elNode.previousSibling.nodeType == 3){ nOffset += elNode.previousSibling.nodeValue.length; elNode = elNode.previousSibling; } return {elContainer:elNode, nOffset:nOffset}; }, _getFixedStartTextNode : function(){ return this._getFixedTextContainer(this.startContainer, this.startOffset); }, _getFixedEndTextNode : function(){ return this._getFixedTextContainer(this.endContainer, this.endOffset); }, placeStringBookmark : function(){ if(this.collapsed || jindo.$Agent().navigator().ie || jindo.$Agent().navigator().firefox){ return this.placeStringBookmark_NonWebkit(); }else{ return this.placeStringBookmark_Webkit(); } }, placeStringBookmark_NonWebkit : function(){ var sTmpId = (new Date()).getTime(); var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToEnd(); var oEndMarker = this._document.createElement("SPAN"); oEndMarker.id = this.HUSKY_BOOMARK_END_ID_PREFIX+sTmpId; oInsertionPoint.insertNode(oEndMarker); var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToStart(); var oStartMarker = this._document.createElement("SPAN"); oStartMarker.id = this.HUSKY_BOOMARK_START_ID_PREFIX+sTmpId; oInsertionPoint.insertNode(oStartMarker); // IE에서 빈 SPAN의 앞뒤로 커서가 이동하지 않아 문제가 발생 할 수 있어, 보이지 않는 특수 문자를 임시로 넣어 줌. if(jindo.$Agent().navigator().ie){ // SPAN의 위치가 TD와 TD 사이에 있을 경우, 텍스트 삽입 시 알수 없는 오류가 발생한다. // TD와 TD사이에서는 텍스트 삽입이 필요 없음으로 그냥 try/catch로 처리 try{ oStartMarker.innerHTML = unescape("%uFEFF"); }catch(e){} try{ oEndMarker.innerHTML = unescape("%uFEFF"); }catch(e){} } this.moveToBookmark(sTmpId); return sTmpId; }, placeStringBookmark_Webkit : function(){ var sTmpId = (new Date()).getTime(); var elInsertBefore, elInsertParent; // Do not insert the bookmarks between TDs as it will break the rendering in Chrome/Safari // -> modify the insertion position from [<td>abc</td>]<td>abc</td> to <td>[abc]</td><td>abc</td> var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToEnd(); elInsertBefore = this._document.createTextNode(""); oInsertionPoint.insertNode(elInsertBefore); elInsertParent = elInsertBefore.parentNode; if(elInsertBefore.previousSibling && elInsertBefore.previousSibling.tagName == "TD"){ elInsertParent = elInsertBefore.previousSibling; elInsertBefore = null; } var oEndMarker = this._document.createElement("SPAN"); oEndMarker.id = this.HUSKY_BOOMARK_END_ID_PREFIX+sTmpId; elInsertParent.insertBefore(oEndMarker, elInsertBefore); var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToStart(); elInsertBefore = this._document.createTextNode(""); oInsertionPoint.insertNode(elInsertBefore); elInsertParent = elInsertBefore.parentNode; if(elInsertBefore.nextSibling && elInsertBefore.nextSibling.tagName == "TD"){ elInsertParent = elInsertBefore.nextSibling; elInsertBefore = elInsertParent.firstChild; } var oStartMarker = this._document.createElement("SPAN"); oStartMarker.id = this.HUSKY_BOOMARK_START_ID_PREFIX+sTmpId; elInsertParent.insertBefore(oStartMarker, elInsertBefore); //elInsertBefore.parentNode.removeChild(elInsertBefore); this.moveToBookmark(sTmpId); return sTmpId; }, cloneRange : function(){ return this._copyRange(new nhn.HuskyRange(this._window)); }, moveToBookmark : function(vBookmark){ if(typeof(vBookmark) != "object"){ return this.moveToStringBookmark(vBookmark); }else{ return this.moveToXPathBookmark(vBookmark); } }, getStringBookmark : function(sBookmarkID, bEndBookmark){ if(bEndBookmark){ return this._document.getElementById(this.HUSKY_BOOMARK_END_ID_PREFIX+sBookmarkID); }else{ return this._document.getElementById(this.HUSKY_BOOMARK_START_ID_PREFIX+sBookmarkID); } }, moveToStringBookmark : function(sBookmarkID, bIncludeBookmark){ var oStartMarker = this.getStringBookmark(sBookmarkID); var oEndMarker = this.getStringBookmark(sBookmarkID, true); if(!oStartMarker || !oEndMarker){return false;} this.reset(this._window); if(bIncludeBookmark){ this.setEndAfter(oEndMarker); this.setStartBefore(oStartMarker); }else{ this.setEndBefore(oEndMarker); this.setStartAfter(oStartMarker); } return true; }, removeStringBookmark : function(sBookmarkID){ /* var oStartMarker = this._document.getElementById(this.HUSKY_BOOMARK_START_ID_PREFIX+sBookmarkID); var oEndMarker = this._document.getElementById(this.HUSKY_BOOMARK_END_ID_PREFIX+sBookmarkID); if(oStartMarker) nhn.DOMFix.parentNode(oStartMarker).removeChild(oStartMarker); if(oEndMarker) nhn.DOMFix.parentNode(oEndMarker).removeChild(oEndMarker); */ this._removeAll(this.HUSKY_BOOMARK_START_ID_PREFIX+sBookmarkID); this._removeAll(this.HUSKY_BOOMARK_END_ID_PREFIX+sBookmarkID); }, _removeAll : function(sID){ var elNode; while((elNode = this._document.getElementById(sID))){ nhn.DOMFix.parentNode(elNode).removeChild(elNode); } }, collapseToStart : function(){ this.collapse(true); }, collapseToEnd : function(){ this.collapse(false); }, createAndInsertNode : function(sTagName){ var tmpNode = this._document.createElement(sTagName); this.insertNode(tmpNode); return tmpNode; }, getNodes : function(bSplitTextEndNodes, fnFilter){ if(bSplitTextEndNodes){this._splitTextEndNodesOfTheRange();} var aAllNodes = this._getNodesInRange(); var aFilteredNodes = []; if(!fnFilter){return aAllNodes;} for(var i=0; i<aAllNodes.length; i++){ if(fnFilter(aAllNodes[i])){aFilteredNodes[aFilteredNodes.length] = aAllNodes[i];} } return aFilteredNodes; }, getTextNodes : function(bSplitTextEndNodes){ var txtFilter = function(oNode){ if (oNode.nodeType == 3 && oNode.nodeValue != "\n" && oNode.nodeValue != ""){ return true; }else{ return false; } }; return this.getNodes(bSplitTextEndNodes, txtFilter); }, surroundContentsWithNewNode : function(sTagName){ var oNewParent = this._document.createElement(sTagName); this.surroundContents(oNewParent); return oNewParent; }, isRangeinRange : function(oAnoterRange, bIncludePartlySelected){ var startToStart = this.compareBoundaryPoints(this.W3CDOMRange.START_TO_START, oAnoterRange); var startToEnd = this.compareBoundaryPoints(this.W3CDOMRange.START_TO_END, oAnoterRange); var endToStart = this.compareBoundaryPoints(this.W3CDOMRange.ND_TO_START, oAnoterRange); var endToEnd = this.compareBoundaryPoints(this.W3CDOMRange.END_TO_END, oAnoterRange); if(startToStart <= 0 && endToEnd >= 0){return true;} if(bIncludePartlySelected){ if(startToEnd == 1){return false;} if(endToStart == -1){return false;} return true; } return false; }, isNodeInRange : function(oNode, bIncludePartlySelected, bContentOnly){ var oTmpRange = new nhn.HuskyRange(this._window); if(bContentOnly && oNode.firstChild){ oTmpRange.setStartBefore(oNode.firstChild); oTmpRange.setEndAfter(oNode.lastChild); }else{ oTmpRange.selectNode(oNode); } return this.isRangeInRange(oTmpRange, bIncludePartlySelected); }, pasteText : function(sText){ this.pasteHTML(sText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;").replace(/"/g, "&quot;")); }, pasteHTML : function(sHTML){ var oTmpDiv = this._document.createElement("DIV"); oTmpDiv.innerHTML = sHTML; if(!oTmpDiv.firstChild){ this.deleteContents(); return; } var oFirstNode = oTmpDiv.firstChild; var oLastNode = oTmpDiv.lastChild; var clone = this.cloneRange(); var sBM = clone.placeStringBookmark(); this.collapseToStart(); while(oTmpDiv.lastChild){this.insertNode(oTmpDiv.lastChild);} this.setEndNodes(oFirstNode, oLastNode); // delete the content later as deleting it first may mass up the insertion point // eg) <p>[A]BCD</p> ---paste O---> O<p>BCD</p> clone.moveToBookmark(sBM); clone.deleteContents(); clone.removeStringBookmark(sBM); }, toString : function(){ this.toString = nhn.W3CDOMRange.prototype.toString; return this.toString(); }, toHTMLString : function(){ var oTmpContainer = this._document.createElement("DIV"); oTmpContainer.appendChild(this.cloneContents()); return oTmpContainer.innerHTML; }, findAncestorByTagName : function(sTagName){ var oNode = this.commonAncestorContainer; while(oNode && oNode.tagName != sTagName){oNode = nhn.DOMFix.parentNode(oNode);} return oNode; }, selectNodeContents : function(oNode){ if(!oNode){return;} var oFirstNode = oNode.firstChild?oNode.firstChild:oNode; var oLastNode = oNode.lastChild?oNode.lastChild:oNode; this.reset(this._window); if(oFirstNode.nodeType == 3){ this.setStart(oFirstNode, 0, true); }else{ this.setStartBefore(oFirstNode); } if(oLastNode.nodeType == 3){ this.setEnd(oLastNode, oLastNode.nodeValue.length, true); }else{ this.setEndAfter(oLastNode); } }, /** * 노드의 취소선/밑줄 정보를 확인한다 * 관련 BTS [SMARTEDITORSUS-26] * @param {Node} oNode 취소선/밑줄을 확인할 노드 * @param {String} sValue textDecoration 정보 * @see nhn.HuskyRange#_checkTextDecoration */ _hasTextDecoration : function(oNode, sValue){ if(!oNode || !oNode.style){ return false; } if(oNode.style.textDecoration.indexOf(sValue) > -1){ return true; } if(sValue === "underline" && oNode.tagName === "U"){ return true; } if(sValue === "line-through" && (oNode.tagName === "S" || oNode.tagName === "STRIKE")){ return true; } return false; }, /** * 노드에 취소선/밑줄을 적용한다 * 관련 BTS [SMARTEDITORSUS-26] * [FF] 노드의 Style 에 textDecoration 을 추가한다 * [FF 외] U/STRIKE 태그를 추가한다 * @param {Node} oNode 취소선/밑줄을 적용할 노드 * @param {String} sValue textDecoration 정보 * @see nhn.HuskyRange#_checkTextDecoration */ _setTextDecoration : function(oNode, sValue){ if (jindo.$Agent().navigator().firefox) { // FF oNode.style.textDecoration = (oNode.style.textDecoration) ? oNode.style.textDecoration + " " + sValue : sValue; } else{ if(sValue === "underline"){ oNode.innerHTML = "<U>" + oNode.innerHTML + "</U>" }else if(sValue === "line-through"){ oNode.innerHTML = "<STRIKE>" + oNode.innerHTML + "</STRIKE>" } } }, /** * 인자로 전달받은 노드 상위의 취소선/밑줄 정보를 확인하여 노드에 적용한다 * 관련 BTS [SMARTEDITORSUS-26] * @param {Node} oNode 취소선/밑줄을 적용할 노드 */ _checkTextDecoration : function(oNode){ if(oNode.tagName !== "SPAN"){ return; } var bUnderline = false, bLineThrough = false, sTextDecoration = "", oParentNode = null; oChildNode = oNode.firstChild; /* check child */ while(oChildNode){ if(oChildNode.nodeType === 1){ bUnderline = (bUnderline || oChildNode.tagName === "U"); bLineThrough = (bLineThrough || oChildNode.tagName === "S" || oChildNode.tagName === "STRIKE"); } if(bUnderline && bLineThrough){ return; } oChildNode = oChildNode.nextSibling; } oParentNode = nhn.DOMFix.parentNode(oNode); /* check parent */ while(oParentNode && oParentNode.tagName !== "BODY"){ if(oParentNode.nodeType !== 1){ oParentNode = nhn.DOMFix.parentNode(oParentNode); continue; } if(!bUnderline && this._hasTextDecoration(oParentNode, "underline")){ bUnderline = true; this._setTextDecoration(oNode, "underline"); // set underline } if(!bLineThrough && this._hasTextDecoration(oParentNode, "line-through")){ bLineThrough = true; this._setTextDecoration(oNode, "line-through"); // set line-through } if(bUnderline && bLineThrough){ return; } oParentNode = nhn.DOMFix.parentNode(oParentNode); } }, /** * Range에 속한 노드들에 스타일을 적용한다 * @param {Object} oStyle 적용할 스타일을 가지는 Object (예) 글꼴 색 적용의 경우 { color : "#0075c8" } * @param {Object} [oAttribute] 적용할 속성을 가지는 Object (예) 맞춤범 검사의 경우 { _sm2_spchk: "강남콩", class: "se2_check_spell" } * @param {String} [sNewSpanMarker] 새로 추가된 SPAN 노드를 나중에 따로 처리해야하는 경우 마킹을 위해 사용하는 문자열 * @param {Boolean} [bIncludeLI] LI 도 스타일 적용에 포함할 것인지의 여부 [COM-1051] _getStyleParentNodes 메서드 참고하기 * @param {Boolean} [bCheckTextDecoration] 취소선/밑줄 처리를 적용할 것인지 여부 [SMARTEDITORSUS-26] _setTextDecoration 메서드 참고하기 */ styleRange : function(oStyle, oAttribute, sNewSpanMarker, bIncludeLI, bCheckTextDecoration){ var aStyleParents = this.aStyleParents = this._getStyleParentNodes(sNewSpanMarker, bIncludeLI); if(aStyleParents.length < 1){return;} var sName, sValue; for(var i=0; i<aStyleParents.length; i++){ for(var x in oStyle){ sName = x; sValue = oStyle[sName]; if(typeof sValue != "string"){continue;} // [SMARTEDITORSUS-26] 글꼴 색을 적용할 때 취소선/밑줄의 색상도 처리되도록 추가 if(bCheckTextDecoration && oStyle.color){ this._checkTextDecoration(aStyleParents[i]); } aStyleParents[i].style[sName] = sValue; } if(!oAttribute){continue;} for(var x in oAttribute){ sName = x; sValue = oAttribute[sName]; if(typeof sValue != "string"){continue;} if(sName == "class"){ jindo.$Element(aStyleParents[i]).addClass(sValue); }else{ aStyleParents[i].setAttribute(sName, sValue); } } } this.reset(this._window); this.setStartBefore(aStyleParents[0]); this.setEndAfter(aStyleParents[aStyleParents.length-1]); }, expandBothEnds : function(){ this.expandStart(); this.expandEnd(); }, expandStart : function(){ if(this.startContainer.nodeType == 3 && this.startOffset !== 0){return;} var elActualStartNode = this._getActualStartNode(this.startContainer, this.startOffset); elActualStartNode = this._getPrevNode(elActualStartNode); if(elActualStartNode.tagName == "BODY"){ this.setStartBefore(elActualStartNode); }else{ this.setStartAfter(elActualStartNode); } }, expandEnd : function(){ if(this.endContainer.nodeType == 3 && this.endOffset < this.endContainer.nodeValue.length){return;} var elActualEndNode = this._getActualEndNode(this.endContainer, this.endOffset); elActualEndNode = this._getNextNode(elActualEndNode); if(elActualEndNode.tagName == "BODY"){ this.setEndAfter(elActualEndNode); }else{ this.setEndBefore(elActualEndNode); } }, /** * Style 을 적용할 노드를 가져온다 * @param {String} [sNewSpanMarker] 새로 추가하는 SPAN 노드를 마킹을 위해 사용하는 문자열 * @param {Boolean} [bIncludeLI] LI 도 스타일 적용에 포함할 것인지의 여부 * @return {Array} Style 을 적용할 노드 배열 */ _getStyleParentNodes : function(sNewSpanMarker, bIncludeLI){ this._splitTextEndNodesOfTheRange(); var oSNode = this.getStartNode(); var oENode = this.getEndNode(); var aAllNodes = this._getNodesInRange(); var aResult = []; var nResult = 0; var oNode, oTmpNode, iStartRelPos, iEndRelPos, oSpan; var nInitialLength = aAllNodes.length; var arAllBottomNodes = jindo.$A(aAllNodes).filter(function(v){return (!v.firstChild || (bIncludeLI && v.tagName=="LI"));}); // [COM-1051] 본문내용을 한 줄만 입력하고 번호 매긴 상태에서 글자크기를 변경하면 번호크기는 변하지 않는 문제 // 부모 노드 중 LI 가 있고, 해당 LI 의 모든 자식 노드가 선택된 상태라면 LI에도 스타일을 적용하도록 처리함 // --- Range 에 LI 가 포함되지 않은 경우, LI 를 포함하도록 처리 var elTmpNode = this.commonAncestorContainer; if(bIncludeLI){ while(elTmpNode){ if(elTmpNode.tagName == "LI"){ if(this._isFullyContained(elTmpNode, arAllBottomNodes)){ aResult[nResult++] = elTmpNode; } break; } elTmpNode = elTmpNode.parentNode; } } for(var i=0; i<nInitialLength; i++){ oNode = aAllNodes[i]; if(!oNode){continue;} // --- Range 에 LI 가 포함된 경우에 대한 LI 확인 if(bIncludeLI && oNode.tagName == "LI" && this._isFullyContained(oNode, arAllBottomNodes)){ aResult[nResult++] = oNode; continue; } if(oNode.nodeType != 3){continue;} if(oNode.nodeValue == "" || oNode.nodeValue.match(/^(\r|\n)+$/)){continue;} var oParentNode = nhn.DOMFix.parentNode(oNode); // 부모 노드가 SPAN 인 경우에는 새로운 SPAN 을 생성하지 않고 SPAN 을 리턴 배열에 추가함 if(oParentNode.tagName == "SPAN"){ if(this._isFullyContained(oParentNode, arAllBottomNodes, oNode)){ aResult[nResult++] = oParentNode; continue; } }else{ // [SMARTEDITORSUS-1513] 선택된 영역을 single node로 감싸는 상위 span 노드가 있으면 리턴 배열에 추가 var oParentSingleSpan = this._findParentSingleSpan(oParentNode); if(oParentSingleSpan){ aResult[nResult++] = oParentSingleSpan; continue; } } oSpan = this._document.createElement("SPAN"); oParentNode.insertBefore(oSpan, oNode); oSpan.appendChild(oNode); aResult[nResult++] = oSpan; if(sNewSpanMarker){oSpan.setAttribute(sNewSpanMarker, "true");} } this.setStartBefore(oSNode); this.setEndAfter(oENode); return aResult; }, /** * [SMARTEDITORSUS-1513][SMARTEDITORSUS-1648] 해당노드가 single child로 묶이는 상위 span 노드가 있는지 찾는다. * @param {Node} oNode 검사할 노드 * @return {Element} 상위 span 노드, 없으면 null */ _findParentSingleSpan : function(oNode){ if(!oNode){ return null; } // ZWNBSP 문자가 같이 있는 경우도 있기 때문에 실제 노드를 카운팅해야 함 for(var i = 0, nCnt = 0, sValue, oChild, aChildNodes = oNode.childNodes; (oChild = aChildNodes[i]); i++){ sValue = oChild.nodeValue; if(this._rxCursorHolder.test(sValue)){ continue; }else{ nCnt++; } if(nCnt > 1){ // 싱글노드가 아니면 더이상 찾지 않고 null 반환 return null; } } if(oNode.nodeName === "SPAN"){ return oNode; }else{ return this._findParentSingleSpan(oNode.parentNode); } }, /** * 컨테이너 엘리먼트(elContainer)의 모든 자식노드가 노드 배열(waAllNodes)에 속하는지 확인한다 * 첫 번째 자식 노드와 마지막 자식 노드가 노드 배열에 속하는지를 확인한다 * @param {Element} elContainer 컨테이너 엘리먼트 * @param {jindo.$A} waAllNodes Node 의 $A 배열 * @param {Node} [oNode] 성능을 위한 옵션 노드로 컨테이너의 첫 번째 혹은 마지막 자식 노드와 같으면 indexOf 함수 사용을 줄일 수 있음 * @return {Array} Style 을 적용할 노드 배열 */ // check if all the child nodes of elContainer are in waAllNodes _isFullyContained : function(elContainer, waAllNodes, oNode){ var nSIdx, nEIdx; var oTmpNode = this._getVeryFirstRealChild(elContainer); // do quick checks before trying indexOf() because indexOf() function is very slow // oNode is optional if(oNode && oTmpNode == oNode){ nSIdx = 1; }else{ nSIdx = waAllNodes.indexOf(oTmpNode); } if(nSIdx != -1){ oTmpNode = this._getVeryLastRealChild(elContainer); if(oNode && oTmpNode == oNode){ nEIdx = 1; }else{ nEIdx = waAllNodes.indexOf(oTmpNode); } } return (nSIdx != -1 && nEIdx != -1); }, _getVeryFirstChild : function(oNode){ if(oNode.firstChild){return this._getVeryFirstChild(oNode.firstChild);} return oNode; }, _getVeryLastChild : function(oNode){ if(oNode.lastChild){return this._getVeryLastChild(oNode.lastChild);} return oNode; }, _getFirstRealChild : function(oNode){ var oFirstNode = oNode.firstChild; while(oFirstNode && oFirstNode.nodeType == 3 && oFirstNode.nodeValue == ""){oFirstNode = oFirstNode.nextSibling;} return oFirstNode; }, _getLastRealChild : function(oNode){ var oLastNode = oNode.lastChild; while(oLastNode && oLastNode.nodeType == 3 && oLastNode.nodeValue == ""){oLastNode = oLastNode.previousSibling;} return oLastNode; }, _getVeryFirstRealChild : function(oNode){ var oFirstNode = this._getFirstRealChild(oNode); if(oFirstNode){return this._getVeryFirstRealChild(oFirstNode);} return oNode; }, _getVeryLastRealChild : function(oNode){ var oLastNode = this._getLastRealChild(oNode); if(oLastNode){return this._getVeryLastChild(oLastNode);} return oNode; }, _getLineStartInfo : function(node){ var frontEndFinal = null; var frontEnd = node; var lineBreaker = node; var bParentBreak = false; var rxLineBreaker = this.rxLineBreaker; // vertical(parent) search function getLineStart(node){ if(!node){return;} if(frontEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; frontEndFinal = frontEnd; bParentBreak = true; return; }else{ frontEnd = node; } getFrontEnd(node.previousSibling); if(frontEndFinal){return;} getLineStart(nhn.DOMFix.parentNode(node)); } // horizontal(sibling) search function getFrontEnd(node){ if(!node){return;} if(frontEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; frontEndFinal = frontEnd; bParentBreak = false; return; } if(node.firstChild && node.tagName != "TABLE"){ var curNode = node.lastChild; while(curNode && !frontEndFinal){ getFrontEnd(curNode); curNode = curNode.previousSibling; } }else{ frontEnd = node; } if(!frontEndFinal){ getFrontEnd(node.previousSibling); } } if(rxLineBreaker.test(node.tagName)){ frontEndFinal = node; }else{ getLineStart(node); } return {oNode: frontEndFinal, oLineBreaker: lineBreaker, bParentBreak: bParentBreak}; }, _getLineEndInfo : function(node){ var backEndFinal = null; var backEnd = node; var lineBreaker = node; var bParentBreak = false; var rxLineBreaker = this.rxLineBreaker; // vertical(parent) search function getLineEnd(node){ if(!node){return;} if(backEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; backEndFinal = backEnd; bParentBreak = true; return; }else{ backEnd = node; } getBackEnd(node.nextSibling); if(backEndFinal){return;} getLineEnd(nhn.DOMFix.parentNode(node)); } // horizontal(sibling) search function getBackEnd(node){ if(!node){return;} if(backEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; backEndFinal = backEnd; bParentBreak = false; return; } if(node.firstChild && node.tagName != "TABLE"){ var curNode = node.firstChild; while(curNode && !backEndFinal){ getBackEnd(curNode); curNode = curNode.nextSibling; } }else{ backEnd = node; } if(!backEndFinal){ getBackEnd(node.nextSibling); } } if(rxLineBreaker.test(node.tagName)){ backEndFinal = node; }else{ getLineEnd(node); } return {oNode: backEndFinal, oLineBreaker: lineBreaker, bParentBreak: bParentBreak}; }, getLineInfo : function(bAfter){ var bAfter = bAfter || false; var oSNode = this.getStartNode(); var oENode = this.getEndNode(); // oSNode && oENode will be null if the range is currently collapsed and the cursor is not located in the middle of a text node. if(!oSNode){oSNode = this.getNodeAroundRange(!bAfter, true);} if(!oENode){oENode = this.getNodeAroundRange(!bAfter, true);} var oStart = this._getLineStartInfo(oSNode); var oStartNode = oStart.oNode; var oEnd = this._getLineEndInfo(oENode); var oEndNode = oEnd.oNode; if(oSNode != oStartNode || oENode != oEndNode){ // check if the start node is positioned after the range's ending point // or // if the end node is positioned before the range's starting point var iRelativeStartPos = this._compareEndPoint(nhn.DOMFix.parentNode(oStartNode), this._getPosIdx(oStartNode), this.endContainer, this.endOffset); var iRelativeEndPos = this._compareEndPoint(nhn.DOMFix.parentNode(oEndNode), this._getPosIdx(oEndNode)+1, this.startContainer, this.startOffset); if(!(iRelativeStartPos <= 0 && iRelativeEndPos >= 0)){ oSNode = this.getNodeAroundRange(false, true); oENode = this.getNodeAroundRange(false, true); oStart = this._getLineStartInfo(oSNode); oEnd = this._getLineEndInfo(oENode); } } return {oStart: oStart, oEnd: oEnd}; }, /** * 커서홀더나 공백을 제외한 child 노드가 하나만 있는 경우만 node 를 반환한다. * @param {Node} oNode 확인할 노드 * @return {Node} single child node를 반환한다. 없거나 두개 이상이면 null 을 반환 */ _findSingleChild : function(oNode){ if(!oNode){ return null; } var oSingleChild = null; // ZWNBSP 문자가 같이 있는 경우도 있기 때문에 실제 노드를 카운팅해야 함 for(var i = 0, nCnt = 0, sValue, oChild, aChildNodes = oNode.childNodes; (oChild = aChildNodes[i]); i++){ sValue = oChild.nodeValue; if(this._rxCursorHolder.test(sValue)){ continue; }else{ oSingleChild = oChild; nCnt++; } if(nCnt > 1){ // 싱글노드가 아니면 더이상 찾지 않고 null 반환 return null; } } return oSingleChild; }, /** * 해당요소의 최하위까지 검색해 커서홀더만 감싸고 있는지 여부를 반환 * @param {Node} oNode 확인할 노드 * @return {Boolean} 커서홀더만 있는 경우 true 반환 */ _hasCursorHolderOnly : function(oNode){ if(!oNode || oNode.nodeType !== 1){ return false; } if(this._rxCursorHolder.test(oNode.innerHTML)){ return true; }else{ return this._hasCursorHolderOnly(this._findSingleChild(oNode)); } } }).extend(nhn.W3CDOMRange); /** * @fileOverview This file contains cross-browser selection function * @name BrowserSelection.js */ nhn.BrowserSelection = function(win){ this.init = function(win){ this._window = win || window; this._document = this._window.document; }; this.init(win); // [SMARTEDITORSUS-888] IE9 이후로 document.createRange 를 지원 /* var oAgentInfo = jindo.$Agent().navigator(); if(oAgentInfo.ie){ nhn.BrowserSelectionImpl_IE.apply(this); }else{ nhn.BrowserSelectionImpl_FF.apply(this); }*/ if(!!this._document.createRange){ nhn.BrowserSelectionImpl_FF.apply(this); }else{ nhn.BrowserSelectionImpl_IE.apply(this); } this.selectRange = function(oRng){ this.selectNone(); this.addRange(oRng); }; this.selectionLoaded = true; if(!this._oSelection){this.selectionLoaded = false;} }; nhn.BrowserSelectionImpl_FF = function(){ this._oSelection = this._window.getSelection(); this.getRangeAt = function(iNum){ iNum = iNum || 0; try{ var oFFRange = this._oSelection.getRangeAt(iNum); }catch(e){return new nhn.W3CDOMRange(this._window);} return this._FFRange2W3CRange(oFFRange); }; this.addRange = function(oW3CRange){ var oFFRange = this._W3CRange2FFRange(oW3CRange); this._oSelection.addRange(oFFRange); }; this.selectNone = function(){ this._oSelection.removeAllRanges(); }; this.getCommonAncestorContainer = function(oW3CRange){ var oFFRange = this._W3CRange2FFRange(oW3CRange); return oFFRange.commonAncestorContainer; }; this.isCollapsed = function(oW3CRange){ var oFFRange = this._W3CRange2FFRange(oW3CRange); return oFFRange.collapsed; }; this.compareEndPoints = function(elContainerA, nOffsetA, elContainerB, nOffsetB){ var oFFRangeA = this._document.createRange(); var oFFRangeB = this._document.createRange(); oFFRangeA.setStart(elContainerA, nOffsetA); oFFRangeB.setStart(elContainerB, nOffsetB); oFFRangeA.collapse(true); oFFRangeB.collapse(true); try{ return oFFRangeA.compareBoundaryPoints(1, oFFRangeB); }catch(e){ return 1; } }; this._FFRange2W3CRange = function(oFFRange){ var oW3CRange = new nhn.W3CDOMRange(this._window); oW3CRange.setStart(oFFRange.startContainer, oFFRange.startOffset, true); oW3CRange.setEnd(oFFRange.endContainer, oFFRange.endOffset, true); return oW3CRange; }; this._W3CRange2FFRange = function(oW3CRange){ var oFFRange = this._document.createRange(); oFFRange.setStart(oW3CRange.startContainer, oW3CRange.startOffset); oFFRange.setEnd(oW3CRange.endContainer, oW3CRange.endOffset); return oFFRange; }; }; nhn.BrowserSelectionImpl_IE = function(){ this._oSelection = this._document.selection; this.oLastRange = { oBrowserRange : null, elStartContainer : null, nStartOffset : -1, elEndContainer : null, nEndOffset : -1 }; this._updateLastRange = function(oBrowserRange, oW3CRange){ this.oLastRange.oBrowserRange = oBrowserRange; this.oLastRange.elStartContainer = oW3CRange.startContainer; this.oLastRange.nStartOffset = oW3CRange.startOffset; this.oLastRange.elEndContainer = oW3CRange.endContainer; this.oLastRange.nEndOffset = oW3CRange.endOffset; }; this.getRangeAt = function(iNum){ iNum = iNum || 0; var oW3CRange, oBrowserRange; if(this._oSelection.type == "Control"){ oW3CRange = new nhn.W3CDOMRange(this._window); var oSelectedNode = this._oSelection.createRange().item(iNum); // if the selction occurs in a different document, ignore if(!oSelectedNode || oSelectedNode.ownerDocument != this._document){return oW3CRange;} oW3CRange.selectNode(oSelectedNode); return oW3CRange; }else{ //oBrowserRange = this._oSelection.createRangeCollection().item(iNum); oBrowserRange = this._oSelection.createRange(); var oSelectedNode = oBrowserRange.parentElement(); // if the selction occurs in a different document, ignore if(!oSelectedNode || oSelectedNode.ownerDocument != this._document){ oW3CRange = new nhn.W3CDOMRange(this._window); return oW3CRange; } oW3CRange = this._IERange2W3CRange(oBrowserRange); return oW3CRange; } }; this.addRange = function(oW3CRange){ var oIERange = this._W3CRange2IERange(oW3CRange); oIERange.select(); }; this.selectNone = function(){ this._oSelection.empty(); }; this.getCommonAncestorContainer = function(oW3CRange){ return this._W3CRange2IERange(oW3CRange).parentElement(); }; this.isCollapsed = function(oW3CRange){ var oRange = this._W3CRange2IERange(oW3CRange); var oRange2 = oRange.duplicate(); oRange2.collapse(); return oRange.isEqual(oRange2); }; this.compareEndPoints = function(elContainerA, nOffsetA, elContainerB, nOffsetB){ var oIERangeA, oIERangeB; if(elContainerA === this.oLastRange.elStartContainer && nOffsetA === this.oLastRange.nStartOffset){ oIERangeA = this.oLastRange.oBrowserRange.duplicate(); oIERangeA.collapse(true); }else{ if(elContainerA === this.oLastRange.elEndContainer && nOffsetA === this.oLastRange.nEndOffset){ oIERangeA = this.oLastRange.oBrowserRange.duplicate(); oIERangeA.collapse(false); }else{ oIERangeA = this._getIERangeAt(elContainerA, nOffsetA); } } if(elContainerB === this.oLastRange.elStartContainer && nOffsetB === this.oLastRange.nStartOffset){ oIERangeB = this.oLastRange.oBrowserRange.duplicate(); oIERangeB.collapse(true); }else{ if(elContainerB === this.oLastRange.elEndContainer && nOffsetB === this.oLastRange.nEndOffset){ oIERangeB = this.oLastRange.oBrowserRange.duplicate(); oIERangeB.collapse(false); }else{ oIERangeB = this._getIERangeAt(elContainerB, nOffsetB); } } return oIERangeA.compareEndPoints("StartToStart", oIERangeB); }; this._W3CRange2IERange = function(oW3CRange){ if(this.oLastRange.elStartContainer === oW3CRange.startContainer && this.oLastRange.nStartOffset === oW3CRange.startOffset && this.oLastRange.elEndContainer === oW3CRange.endContainer && this.oLastRange.nEndOffset === oW3CRange.endOffset){ return this.oLastRange.oBrowserRange; } var oStartIERange = this._getIERangeAt(oW3CRange.startContainer, oW3CRange.startOffset); var oEndIERange = this._getIERangeAt(oW3CRange.endContainer, oW3CRange.endOffset); oStartIERange.setEndPoint("EndToEnd", oEndIERange); this._updateLastRange(oStartIERange, oW3CRange); return oStartIERange; }; this._getIERangeAt = function(oW3CContainer, iW3COffset){ var oIERange = this._document.body.createTextRange(); var oEndPointInfoForIERange = this._getSelectableNodeAndOffsetForIE(oW3CContainer, iW3COffset); var oSelectableNode = oEndPointInfoForIERange.oSelectableNodeForIE; var iIEOffset = oEndPointInfoForIERange.iOffsetForIE; oIERange.moveToElementText(oSelectableNode); oIERange.collapse(oEndPointInfoForIERange.bCollapseToStart); oIERange.moveStart("character", iIEOffset); return oIERange; }; this._getSelectableNodeAndOffsetForIE = function(oW3CContainer, iW3COffset){ // var oIERange = this._document.body.createTextRange(); var oNonTextNode = null; var aChildNodes = null; var iNumOfLeftNodesToCount = 0; if(oW3CContainer.nodeType == 3){ oNonTextNode = nhn.DOMFix.parentNode(oW3CContainer); aChildNodes = nhn.DOMFix.childNodes(oNonTextNode); iNumOfLeftNodesToCount = aChildNodes.length; }else{ oNonTextNode = oW3CContainer; aChildNodes = nhn.DOMFix.childNodes(oNonTextNode); //iNumOfLeftNodesToCount = iW3COffset; iNumOfLeftNodesToCount = (iW3COffset<aChildNodes.length)?iW3COffset:aChildNodes.length; } //@ room 4 improvement var oNodeTester = null; var iResultOffset = 0; var bCollapseToStart = true; for(var i=0; i<iNumOfLeftNodesToCount; i++){ oNodeTester = aChildNodes[i]; if(oNodeTester.nodeType == 3){ if(oNodeTester == oW3CContainer){break;} iResultOffset += oNodeTester.nodeValue.length; }else{ // oIERange.moveToElementText(oNodeTester); oNonTextNode = oNodeTester; iResultOffset = 0; bCollapseToStart = false; } } if(oW3CContainer.nodeType == 3){iResultOffset += iW3COffset;} return {oSelectableNodeForIE:oNonTextNode, iOffsetForIE: iResultOffset, bCollapseToStart: bCollapseToStart}; }; this._IERange2W3CRange = function(oIERange){ var oW3CRange = new nhn.W3CDOMRange(this._window); var oIEPointRange = null; var oPosition = null; oIEPointRange = oIERange.duplicate(); oIEPointRange.collapse(true); oPosition = this._getW3CContainerAndOffset(oIEPointRange, true); oW3CRange.setStart(oPosition.oContainer, oPosition.iOffset, true, true); var oCollapsedChecker = oIERange.duplicate(); oCollapsedChecker.collapse(true); if(oCollapsedChecker.isEqual(oIERange)){ oW3CRange.collapse(true); }else{ oIEPointRange = oIERange.duplicate(); oIEPointRange.collapse(false); oPosition = this._getW3CContainerAndOffset(oIEPointRange); oW3CRange.setEnd(oPosition.oContainer, oPosition.iOffset, true); } this._updateLastRange(oIERange, oW3CRange); return oW3CRange; }; this._getW3CContainerAndOffset = function(oIEPointRange, bStartPt){ var oRgOrigPoint = oIEPointRange; var oContainer = oRgOrigPoint.parentElement(); var offset = -1; var oRgTester = this._document.body.createTextRange(); var aChildNodes = nhn.DOMFix.childNodes(oContainer); var oPrevNonTextNode = null; var pointRangeIdx = 0; for(var i=0;i<aChildNodes.length;i++){ if(aChildNodes[i].nodeType == 3){continue;} oRgTester.moveToElementText(aChildNodes[i]); if(oRgTester.compareEndPoints("StartToStart", oIEPointRange)>=0){break;} oPrevNonTextNode = aChildNodes[i]; } var pointRangeIdx = i; if(pointRangeIdx !== 0 && aChildNodes[pointRangeIdx-1].nodeType == 3){ var oRgTextStart = this._document.body.createTextRange(); var oCurTextNode = null; if(oPrevNonTextNode){ oRgTextStart.moveToElementText(oPrevNonTextNode); oRgTextStart.collapse(false); oCurTextNode = oPrevNonTextNode.nextSibling; }else{ oRgTextStart.moveToElementText(oContainer); oRgTextStart.collapse(true); oCurTextNode = oContainer.firstChild; } var oRgTextsUpToThePoint = oRgOrigPoint.duplicate(); oRgTextsUpToThePoint.setEndPoint("StartToStart", oRgTextStart); var textCount = oRgTextsUpToThePoint.text.replace(/[\r\n]/g,"").length; while(textCount > oCurTextNode.nodeValue.length && oCurTextNode.nextSibling){ textCount -= oCurTextNode.nodeValue.length; oCurTextNode = oCurTextNode.nextSibling; } // this will enforce IE to re-reference oCurTextNode var oTmp = oCurTextNode.nodeValue; if(bStartPt && oCurTextNode.nextSibling && oCurTextNode.nextSibling.nodeType == 3 && textCount == oCurTextNode.nodeValue.length){ textCount -= oCurTextNode.nodeValue.length; oCurTextNode = oCurTextNode.nextSibling; } oContainer = oCurTextNode; offset = textCount; }else{ oContainer = oRgOrigPoint.parentElement(); offset = pointRangeIdx; } return {"oContainer" : oContainer, "iOffset" : offset}; }; }; nhn.DOMFix = new (jindo.$Class({ $init : function(){ if(jindo.$Agent().navigator().ie || jindo.$Agent().navigator().opera){ this.childNodes = this._childNodes_Fix; this.parentNode = this._parentNode_Fix; }else{ this.childNodes = this._childNodes_Native; this.parentNode = this._parentNode_Native; } }, _parentNode_Native : function(elNode){ return elNode.parentNode; }, _parentNode_Fix : function(elNode){ if(!elNode){return elNode;} while(elNode.previousSibling){elNode = elNode.previousSibling;} return elNode.parentNode; }, _childNodes_Native : function(elNode){ return elNode.childNodes; }, _childNodes_Fix : function(elNode){ var aResult = null; var nCount = 0; if(elNode){ var aResult = []; elNode = elNode.firstChild; while(elNode){ aResult[nCount++] = elNode; elNode=elNode.nextSibling; } } return aResult; } }))(); /*[ * ADD_APP_PROPERTY * * 주요 오브젝트를 모든 플러그인에서 this.oApp를 통해서 직접 접근 가능 하도록 등록한다. * * sPropertyName string 등록명 * oProperty object 등록시킬 오브젝트 * ---------------------------------------------------------------------------]*/ /*[ * REGISTER_BROWSER_EVENT * * 특정 브라우저 이벤트가 발생 했을때 Husky 메시지를 발생 시킨다. * * obj HTMLElement 브라우저 이벤트를 발생 시킬 HTML 엘리먼트 * sEvent string 발생 대기 할 브라우저 이벤트 * sMsg string 발생 할 Husky 메시지 * aParams array 메시지에 넘길 파라미터 * nDelay number 브라우저 이벤트 발생 후 Husky 메시지 발생 사이에 딜레이를 주고 싶을 경우 설정. (1/1000초 단위) * ---------------------------------------------------------------------------]*/ /*[ * DISABLE_MESSAGE * * 특정 메시지를 코어에서 무시하고 라우팅 하지 않도록 비활성화 한다. * * sMsg string 비활성화 시킬 메시지 * ---------------------------------------------------------------------------]*/ /*[ * ENABLE_MESSAGE * * 무시하도록 설정된 메시지를 무시하지 않도록 활성화 한다. * * sMsg string 활성화 시킬 메시지 * ---------------------------------------------------------------------------]*/ /*[ * EXEC_ON_READY_FUNCTION * * oApp.run({fnOnAppReady:fnOnAppReady})와 같이 run 호출 시점에 지정된 함수가 있을 경우 이를 MSG_APP_READY 시점에 실행 시킨다. * 코어에서 자동으로 발생시키는 메시지로 직접 발생시키지는 않도록 한다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc Husky Framework에서 자주 사용되는 메시지를 처리하는 플러그인 */ nhn.husky.CorePlugin = jindo.$Class({ name : "CorePlugin", // nStatus = 0(request not sent), 1(request sent), 2(response received) // sContents = response htLazyLoadRequest_plugins : {}, htLazyLoadRequest_allFiles : {}, htHTMLLoaded : {}, $AFTER_MSG_APP_READY : function(){ this.oApp.exec("EXEC_ON_READY_FUNCTION", []); }, $ON_ADD_APP_PROPERTY : function(sPropertyName, oProperty){ this.oApp[sPropertyName] = oProperty; }, $ON_REGISTER_BROWSER_EVENT : function(obj, sEvent, sMsg, aParams, nDelay){ this.oApp.registerBrowserEvent(obj, sEvent, sMsg, aParams, nDelay); }, $ON_DISABLE_MESSAGE : function(sMsg){ this.oApp.disableMessage(sMsg, true); }, $ON_ENABLE_MESSAGE : function(sMsg){ this.oApp.disableMessage(sMsg, false); }, $ON_LOAD_FULL_PLUGIN : function(aFilenames, sClassName, sMsgName, oThisRef, oArguments){ var oPluginRef = oThisRef.$this || oThisRef; // var nIdx = _nIdx||0; var sFilename = aFilenames[0]; if(!this.htLazyLoadRequest_plugins[sFilename]){ this.htLazyLoadRequest_plugins[sFilename] = {nStatus:1, sContents:""}; } if(this.htLazyLoadRequest_plugins[sFilename].nStatus === 2){ //this.oApp.delayedExec("MSG_FULL_PLUGIN_LOADED", [sFilename, sClassName, sMsgName, oThisRef, oArguments, false], 0); this.oApp.exec("MSG_FULL_PLUGIN_LOADED", [sFilename, sClassName, sMsgName, oThisRef, oArguments, false]); }else{ this._loadFullPlugin(aFilenames, sClassName, sMsgName, oThisRef, oArguments, 0); } }, _loadFullPlugin : function(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx){ jindo.LazyLoading.load(nhn.husky.SE2M_Configuration.LazyLoad.sJsBaseURI+"/"+aFilenames[nIdx], jindo.$Fn(function(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx){ var sCurFilename = aFilenames[nIdx]; // plugin filename var sFilename = aFilenames[0]; if(nIdx == aFilenames.length-1){ this.htLazyLoadRequest_plugins[sFilename].nStatus=2; this.oApp.exec("MSG_FULL_PLUGIN_LOADED", [aFilenames, sClassName, sMsgName, oThisRef, oArguments]); return; } //this.oApp.exec("LOAD_FULL_PLUGIN", [aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx+1]); this._loadFullPlugin(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx+1); }, this).bind(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx), "utf-8" ); }, $ON_MSG_FULL_PLUGIN_LOADED : function(aFilenames, sClassName, sMsgName, oThisRef, oArguments, oRes){ // oThisRef.$this는 현재 로드되는 플러그인이 parent 인스턴스일 경우 존재 함. oThisRef.$this는 현재 플러그인(oThisRef)를 parent로 삼고 있는 인스턴스 // oThisRef에 $this 속성이 없다면 parent가 아닌 일반 인스턴스 // oPluginRef는 결과적으로 상속 관계가 있다면 자식 인스턴스를 아니라면 일반적인 인스턴스를 가짐 var oPluginRef = oThisRef.$this || oThisRef; var sFilename = aFilenames; // now the source code is loaded, remove the loader handlers for(var i=0, nLen=oThisRef._huskyFLT.length; i<nLen; i++){ var sLoaderHandlerName = "$BEFORE_"+oThisRef._huskyFLT[i]; // if child class has its own loader function, remove the loader from current instance(parent) only var oRemoveFrom = (oThisRef.$this && oThisRef[sLoaderHandlerName])?oThisRef:oPluginRef; oRemoveFrom[sLoaderHandlerName] = null; this.oApp.createMessageMap(sLoaderHandlerName); } var oPlugin = eval(sClassName+".prototype"); //var oPlugin = eval("new "+sClassName+"()"); var bAcceptLocalBeforeFirstAgain = false; // if there were no $LOCAL_BEFORE_FIRST in already-loaded script, set to accept $LOCAL_BEFORE_FIRST next time as the function could be included in the lazy-loaded script. if(typeof oPluginRef["$LOCAL_BEFORE_FIRST"] !== "function"){ this.oApp.acceptLocalBeforeFirstAgain(oPluginRef, true); } for(var x in oPlugin){ // 자식 인스턴스에 parent를 override하는 함수가 없다면 parent 인스턴스에 함수 복사 해 줌. 이때 함수만 복사하고, 나머지 속성들은 현재 인스턴스에 존재 하지 않을 경우에만 복사. if(oThisRef.$this && (!oThisRef[x] || (typeof oPlugin[x] === "function" && x != "constructor"))){ oThisRef[x] = jindo.$Fn(oPlugin[x], oPluginRef).bind(); } // 현재 인스턴스에 함수 복사 해 줌. 이때 함수만 복사하고, 나머지 속성들은 현재 인스턴스에 존재 하지 않을 경우에만 복사 if(oPlugin[x] && (!oPluginRef[x] || (typeof oPlugin[x] === "function" && x != "constructor"))){ oPluginRef[x] = oPlugin[x]; // 새로 추가되는 함수가 메시지 핸들러라면 메시지 매핑에 추가 해 줌 if(x.match(/^\$(LOCAL|BEFORE|ON|AFTER)_/)){ this.oApp.addToMessageMap(x, oPluginRef); } } } if(bAcceptLocalBeforeFirstAgain){ this.oApp.acceptLocalBeforeFirstAgain(oPluginRef, true); } // re-send the message after all the jindo.$super handlers are executed if(!oThisRef.$this){ this.oApp.exec(sMsgName, oArguments); } }, $ON_LOAD_HTML : function(sId){ if(this.htHTMLLoaded[sId]) return; var elTextarea = jindo.$("_llh_"+sId); if(!elTextarea) return; this.htHTMLLoaded[sId] = true; var elTmp = document.createElement("DIV"); elTmp.innerHTML = elTextarea.value; while(elTmp.firstChild){ elTextarea.parentNode.insertBefore(elTmp.firstChild, elTextarea); } }, $ON_EXEC_ON_READY_FUNCTION : function(){ if(typeof this.oApp.htRunOptions.fnOnAppReady == "function"){this.oApp.htRunOptions.fnOnAppReady();} } }); //{ /** * @fileOverview This file contains Husky plugin that bridges the HuskyRange function * @name hp_HuskyRangeManager.js */ nhn.husky.HuskyRangeManager = jindo.$Class({ name : "HuskyRangeManager", oWindow : null, $init : function(win){ this.oWindow = win || window; }, $BEFORE_MSG_APP_READY : function(){ if(this.oWindow && this.oWindow.tagName == "IFRAME"){ this.oWindow = this.oWindow.contentWindow; nhn.CurrentSelection.setWindow(this.oWindow); } this.oApp.exec("ADD_APP_PROPERTY", ["getSelection", jindo.$Fn(this.getSelection, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getEmptySelection", jindo.$Fn(this.getEmptySelection, this).bind()]); }, $ON_SET_EDITING_WINDOW : function(oWindow){ this.oWindow = oWindow; }, getEmptySelection : function(oWindow){ var oHuskyRange = new nhn.HuskyRange(oWindow || this.oWindow); return oHuskyRange; }, getSelection : function(oWindow){ this.oApp.exec("RESTORE_IE_SELECTION", []); var oHuskyRange = this.getEmptySelection(oWindow); // this may throw an exception if the selected is area is not yet shown try{ oHuskyRange.setFromSelection(); }catch(e){} return oHuskyRange; } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to the tool bar UI * @name hp_SE2M_Toolbar.js */ nhn.husky.SE2M_Toolbar = jindo.$Class({ name : "SE2M_Toolbar", toolbarArea : null, toolbarButton : null, uiNameTag : "uiName", // 0: unknown // 1: all enabled // 2: all disabled nUIStatus : 1, sUIClassPrefix : "husky_seditor_ui_", aUICmdMap : null, elFirstToolbarItem : null, _assignHTMLElements : function(oAppContainer){ oAppContainer = jindo.$(oAppContainer) || document; this.rxUI = new RegExp(this.sUIClassPrefix+"([^ ]+)"); //@ec[ this.toolbarArea = jindo.$$.getSingle(".se2_tool", oAppContainer); this.aAllUI = jindo.$$("[class*=" + this.sUIClassPrefix + "]", this.toolbarArea); this.elTextTool = jindo.$$.getSingle("div.husky_seditor_text_tool", this.toolbarArea); // [SMARTEDITORSUS-1124] 텍스트 툴바 버튼의 라운드 처리 //@ec] this.welToolbarArea = jindo.$Element(this.toolbarArea); for (var i = 0, nCount = this.aAllUI.length; i < nCount; i++) { if (this.rxUI.test(this.aAllUI[i].className)) { var sUIName = RegExp.$1; if(this.htUIList[sUIName] !== undefined){ continue; } this.htUIList[sUIName] = this.aAllUI[i]; this.htWrappedUIList[sUIName] = jindo.$Element(this.htUIList[sUIName]); } } if (jindo.$$.getSingle("DIV.se2_icon_tool") != null) { this.elFirstToolbarItem = jindo.$$.getSingle("DIV.se2_icon_tool UL.se2_itool1>li>button"); } }, $LOCAL_BEFORE_FIRST : function(sMsg) { var aToolItems = jindo.$$(">ul>li[class*=" + this.sUIClassPrefix + "]>button", this.elTextTool); var nItemLength = aToolItems.length; this.elFirstToolbarItem = this.elFirstToolbarItem || aToolItems[0]; this.elLastToolbarItem = aToolItems[nItemLength-1]; this.oApp.registerBrowserEvent(this.toolbarArea, "keydown", "NAVIGATE_TOOLBAR", []); }, $init : function(oAppContainer){ this.htUIList = {}; this.htWrappedUIList = {}; this.aUICmdMap = {}; this._assignHTMLElements(oAppContainer); this._setRoundedCornerButton(); // [SMARTEDITORSUS-1124] 텍스트 툴바 버튼의 라운드 처리 }, $ON_MSG_APP_READY : function(){ this.oApp.registerBrowserEvent(this.toolbarArea, "mouseover", "EVENT_TOOLBAR_MOUSEOVER", []); this.oApp.registerBrowserEvent(this.toolbarArea, "mouseout", "EVENT_TOOLBAR_MOUSEOUT", []); this.oApp.registerBrowserEvent(this.toolbarArea, "mousedown", "EVENT_TOOLBAR_MOUSEDOWN", []); /* var aBtns = jindo.$$("BUTTON", this.toolbarArea); for(var i=0; i<aBtns.length; i++){ this.oApp.registerBrowserEvent(aBtns[i], "focus", "EVENT_TOOLBAR_MOUSEOVER", []); this.oApp.registerBrowserEvent(aBtns[i], "blur", "EVENT_TOOLBAR_MOUSEOUT", []); } */ this.oApp.exec("ADD_APP_PROPERTY", ["getToolbarButtonByUIName", jindo.$Fn(this.getToolbarButtonByUIName, this).bind()]); //웹접근성 //이 단계에서 oAppContainer가 정의되지 않은 상태라서 this.toolbarArea변수값을 사용하지 못하고 아래와 같이 다시 정의하였음. var elTool = jindo.$$.getSingle(".se2_tool"); this.oApp.exec("REGISTER_HOTKEY", ["esc", "FOCUS_EDITING_AREA", [], elTool]); }, $ON_NAVIGATE_TOOLBAR : function(weEvent) { var TAB_KEY_CODE = 9; //이벤트가 발생한 엘리먼트가 마지막 아이템이고 TAB 키가 눌려졌다면 if ((weEvent.element == this.elLastToolbarItem) && (weEvent.key().keyCode == TAB_KEY_CODE) ) { if (weEvent.key().shift) { //do nothing } else { this.elFirstToolbarItem.focus(); weEvent.stopDefault(); } } //이벤트가 발생한 엘리먼트가 첫번째 아이템이고 TAB 키가 눌려졌다면 if (weEvent.element == this.elFirstToolbarItem && (weEvent.key().keyCode == TAB_KEY_CODE)) { if (weEvent.key().shift) { weEvent.stopDefault(); this.elLastToolbarItem.focus(); } } }, //포커스가 툴바에 있는 상태에서 단축키를 누르면 에디팅 영역으로 다시 포커스가 가도록 하는 함수. (웹접근성) $ON_FOCUS_EDITING_AREA : function() { this.oApp.exec("FOCUS"); }, $ON_TOGGLE_TOOLBAR_ACTIVE_LAYER : function(elLayer, elBtn, sOpenCmd, aOpenArgs, sCloseCmd, aCloseArgs){ this.oApp.exec("TOGGLE_ACTIVE_LAYER", [elLayer, "MSG_TOOLBAR_LAYER_SHOWN", [elLayer, elBtn, sOpenCmd, aOpenArgs], sCloseCmd, aCloseArgs]); }, $ON_MSG_TOOLBAR_LAYER_SHOWN : function(elLayer, elBtn, aOpenCmd, aOpenArgs){ this.oApp.exec("POSITION_TOOLBAR_LAYER", [elLayer, elBtn]); if(aOpenCmd){ this.oApp.exec(aOpenCmd, aOpenArgs); } }, $ON_SHOW_TOOLBAR_ACTIVE_LAYER : function(elLayer, sCmd, aArgs, elBtn){ this.oApp.exec("SHOW_ACTIVE_LAYER", [elLayer, sCmd, aArgs]); this.oApp.exec("POSITION_TOOLBAR_LAYER", [elLayer, elBtn]); }, $ON_ENABLE_UI : function(sUIName){ this._enableUI(sUIName); }, $ON_DISABLE_UI : function(sUIName){ this._disableUI(sUIName); }, $ON_SELECT_UI : function(sUIName){ var welUI = this.htWrappedUIList[sUIName]; if(!welUI){ return; } welUI.removeClass("hover"); welUI.addClass("active"); }, $ON_DESELECT_UI : function(sUIName){ var welUI = this.htWrappedUIList[sUIName]; if(!welUI){ return; } welUI.removeClass("active"); }, /** * [SMARTEDITORSUS-1646] 툴바버튼 선택상태를 토글링한다. * @param {String} sUIName 토글링할 툴바버튼 이름 */ $ON_TOGGLE_UI_SELECTED : function(sUIName){ var welUI = this.htWrappedUIList[sUIName]; if(!welUI){ return; } if(welUI.hasClass("active")){ welUI.removeClass("active"); }else{ welUI.removeClass("hover"); welUI.addClass("active"); } }, $ON_ENABLE_ALL_UI : function(htOptions){ if(this.nUIStatus === 1){ return; } var sUIName, className; htOptions = htOptions || {}; var waExceptions = jindo.$A(htOptions.aExceptions || []); for(sUIName in this.htUIList){ if(sUIName && !waExceptions.has(sUIName)){ this._enableUI(sUIName); } // if(sUIName) this.oApp.exec("ENABLE_UI", [sUIName]); } // jindo.$Element(this.toolbarArea).removeClass("off"); this.nUIStatus = 1; }, $ON_DISABLE_ALL_UI : function(htOptions){ if(this.nUIStatus === 2){ return; } var sUIName; htOptions = htOptions || {}; var waExceptions = jindo.$A(htOptions.aExceptions || []); var bLeavlActiveLayer = htOptions.bLeaveActiveLayer || false; if(!bLeavlActiveLayer){ this.oApp.exec("HIDE_ACTIVE_LAYER",[]); } for(sUIName in this.htUIList){ if(sUIName && !waExceptions.has(sUIName)){ this._disableUI(sUIName); } // if(sUIName) this.oApp.exec("DISABLE_UI", [sUIName]); } // jindo.$Element(this.toolbarArea).addClass("off"); this.nUIStatus = 2; }, $ON_MSG_STYLE_CHANGED : function(sAttributeName, attributeValue){ if(attributeValue === "@^"){ this.oApp.exec("SELECT_UI", [sAttributeName]); }else{ this.oApp.exec("DESELECT_UI", [sAttributeName]); } }, $ON_POSITION_TOOLBAR_LAYER : function(elLayer, htOption){ var nLayerLeft, nLayerRight, nToolbarLeft, nToolbarRight; elLayer = jindo.$(elLayer); htOption = htOption || {}; var elBtn = jindo.$(htOption.elBtn); var sAlign = htOption.sAlign; var nMargin = -1; if(!elLayer){ return; } if(elBtn && elBtn.tagName && elBtn.tagName == "BUTTON"){ elBtn.parentNode.appendChild(elLayer); } var welLayer = jindo.$Element(elLayer); if(sAlign != "right"){ elLayer.style.left = "0"; nLayerLeft = welLayer.offset().left; nLayerRight = nLayerLeft + elLayer.offsetWidth; nToolbarLeft = this.welToolbarArea.offset().left; nToolbarRight = nToolbarLeft + this.toolbarArea.offsetWidth; if(nLayerRight > nToolbarRight){ welLayer.css("left", (nToolbarRight-nLayerRight-nMargin)+"px"); } if(nLayerLeft < nToolbarLeft){ welLayer.css("left", (nToolbarLeft-nLayerLeft+nMargin)+"px"); } }else{ elLayer.style.right = "0"; nLayerLeft = welLayer.offset().left; nLayerRight = nLayerLeft + elLayer.offsetWidth; nToolbarLeft = this.welToolbarArea.offset().left; nToolbarRight = nToolbarLeft + this.toolbarArea.offsetWidth; if(nLayerRight > nToolbarRight){ welLayer.css("right", -1*(nToolbarRight-nLayerRight-nMargin)+"px"); } if(nLayerLeft < nToolbarLeft){ welLayer.css("right", -1*(nToolbarLeft-nLayerLeft+nMargin)+"px"); } } }, $ON_EVENT_TOOLBAR_MOUSEOVER : function(weEvent){ if(this.nUIStatus === 2){ return; } var aAffectedElements = this._getAffectedElements(weEvent.element); for(var i=0; i<aAffectedElements.length; i++){ if(!aAffectedElements[i].hasClass("active")){ aAffectedElements[i].addClass("hover"); } } }, $ON_EVENT_TOOLBAR_MOUSEOUT : function(weEvent){ if(this.nUIStatus === 2){ return; } var aAffectedElements = this._getAffectedElements(weEvent.element); for(var i=0; i<aAffectedElements.length; i++){ aAffectedElements[i].removeClass("hover"); } }, $ON_EVENT_TOOLBAR_MOUSEDOWN : function(weEvent){ var elTmp = weEvent.element; // Check if the button pressed is in active status and has a visible layer i.e. the button had been clicked and its layer is open already. (buttons like font styles-bold, underline-got no sub layer -> childNodes.length<=2) // -> In this case, do not close here(mousedown). The layer will be closed on "click". If we close the layer here, the click event will open it again because it toggles the visibility. while(elTmp){ if(elTmp.className && elTmp.className.match(/active/) && (elTmp.childNodes.length>2 || elTmp.parentNode.className.match(/se2_pair/))){ return; } elTmp = elTmp.parentNode; } this.oApp.exec("HIDE_ACTIVE_LAYER_IF_NOT_CHILD", [weEvent.element]); }, _enableUI : function(sUIName){ var i, nLen; this.nUIStatus = 0; var welUI = this.htWrappedUIList[sUIName]; var elUI = this.htUIList[sUIName]; if(!welUI){ return; } welUI.removeClass("off"); var aAllBtns = elUI.getElementsByTagName("BUTTON"); for(i=0, nLen=aAllBtns.length; i<nLen; i++){ aAllBtns[i].disabled = false; } // enable related commands var sCmd = ""; if(this.aUICmdMap[sUIName]){ for(i=0; i<this.aUICmdMap[sUIName].length;i++){ sCmd = this.aUICmdMap[sUIName][i]; this.oApp.exec("ENABLE_MESSAGE", [sCmd]); } } }, _disableUI : function(sUIName){ var i, nLen; this.nUIStatus = 0; var welUI = this.htWrappedUIList[sUIName]; var elUI = this.htUIList[sUIName]; if(!welUI){ return; } welUI.addClass("off"); welUI.removeClass("hover"); var aAllBtns = elUI.getElementsByTagName("BUTTON"); for(i=0, nLen=aAllBtns.length; i<nLen; i++){ aAllBtns[i].disabled = true; } // disable related commands var sCmd = ""; if(this.aUICmdMap[sUIName]){ for(i=0; i<this.aUICmdMap[sUIName].length;i++){ sCmd = this.aUICmdMap[sUIName][i]; this.oApp.exec("DISABLE_MESSAGE", [sCmd]); } } }, _getAffectedElements : function(el){ var elLi, welLi; // 버튼 클릭시에 return false를 해 주지 않으면 chrome에서 버튼이 포커스 가져가 버림. // 에디터 로딩 시에 일괄처리 할 경우 로딩 속도가 느려짐으로 hover시에 하나씩 처리 if(!el.bSE2_MDCancelled){ el.bSE2_MDCancelled = true; var aBtns = el.getElementsByTagName("BUTTON"); for(var i=0, nLen=aBtns.length; i<nLen; i++){ aBtns[i].onmousedown = function(){return false;}; } } if(!el || !el.tagName){ return []; } if((elLi = el).tagName == "BUTTON"){ // typical button // <LI> // <BUTTON> if((elLi = elLi.parentNode) && elLi.tagName == "LI" && this.rxUI.test(elLi.className)){ return [jindo.$Element(elLi)]; } // button pair // <LI> // <SPAN> // <BUTTON> // <SPAN> // <BUTTON> elLi = el; if((elLi = elLi.parentNode.parentNode) && elLi.tagName == "LI" && (welLi = jindo.$Element(elLi)).hasClass("se2_pair")){ return [welLi, jindo.$Element(el.parentNode)]; } return []; } // span in a button if((elLi = el).tagName == "SPAN"){ // <LI> // <BUTTON> // <SPAN> if((elLi = elLi.parentNode.parentNode) && elLi.tagName == "LI" && this.rxUI.test(elLi.className)){ return [jindo.$Element(elLi)]; } // <LI> // <SPAN> //글감과 글양식 if((elLi = elLi.parentNode) && elLi.tagName == "LI" && this.rxUI.test(elLi.className)){ return [jindo.$Element(elLi)]; } } return []; }, /* * 텍스트 툴바의 버튼 라운딩 처리 * [MOSS] "[UI개발1팀] 스마트에디터 텍스트툴바버튼 라운딩처리가이드" 참고 * - 버튼 라운드 처리를 위한 tool_bg 클래스 추가를 위한 엘리먼트 탐색은 _buttonRound 클래스 사용 (AU 추가클래스) */ _setRoundedCornerButton : function(){ var i, nLiLen, elLi, welLi, elSpan, aSingleLi, aFirstLi, aLastLi; aSingleLi = jindo.$$(">ul>li[class*=" + this.sUIClassPrefix + "]:only-child", this.elTextTool); // 단독형 버튼 좌/우측 라운드 처리 for(i=0, nLiLen=aSingleLi.length; i<nLiLen; i++){ elLi = aSingleLi[i]; welLi = jindo.$Element(elLi); if(welLi.hasClass("husky_seditor_ui_text_more") || welLi.hasClass("husky_seditor_ui_photo_attach") || welLi.hasClass("husky_seditor_ui_map_attach")){ continue; } welLi.addClass("single_child"); jindo.$Element(jindo.$$.getSingle('button>span._buttonRound', elLi)).addClass("tool_bg"); } // 버튼 좌측 라운드 처리 // ※ 주의: 더보기 하위의 버튼 라운드 처리의 경우도 있으므로 바로 하위 UL이 아닌 경우도 있음 aFirstLi = jindo.$$("ul>li[class*=" + this.sUIClassPrefix + "]:first-child", this.elTextTool); for(i=0, nLiLen=aFirstLi.length; i<nLiLen; i++){ elLi = aFirstLi[i]; welLi = jindo.$Element(elLi); if(welLi.hasClass("husky_seditor_ui_fontName") || welLi.hasClass("husky_seditor_ui_text_more") || welLi.hasClass("husky_seditor_ui_photo_attach") || welLi.hasClass("husky_seditor_ui_map_attach") || welLi.hasClass("single_child")){ continue; } welLi.addClass("first_child"); jindo.$Element(jindo.$$.getSingle('button>span._buttonRound', elLi)).addClass("tool_bg"); } // 버튼 우측 라운드 처리 // ※ 주의: 더보기 하위의 버튼 라운드 처리의 경우도 있으므로 바로 하위 UL이 아닌 경우도 있음 aLastLi = jindo.$$("ul>li[class*=" + this.sUIClassPrefix + "]:last-child", this.elTextTool); for(i=0, nLiLen=aLastLi.length; i<nLiLen; i++){ elLi = aLastLi[i]; welLi = jindo.$Element(elLi); if(welLi.hasClass("husky_seditor_ui_fontSize") || welLi.hasClass("husky_seditor_ui_text_more") || welLi.hasClass("husky_seditor_ui_photo_attach") || welLi.hasClass("husky_seditor_ui_map_attach") || welLi.hasClass("single_child")){ continue; } welLi.addClass("last_child"); jindo.$Element(jindo.$$.getSingle('button>span._buttonRound', elLi)).addClass("tool_bg"); } }, $ON_REGISTER_UI_EVENT : function(sUIName, sEvent, sCmd, aParams){ //[SMARTEDITORSUS-966][IE8 표준/IE 10] 호환 모드를 제거하고 사진 첨부 시 에디팅 영역의 // 커서 주위에 <sub><sup> 태그가 붙어서 글자가 매우 작게 되는 현상 //원인 : 아래의 [SMARTEDITORSUS-901] 수정 내용에서 윗첨자 아랫첨자 이벤트 등록 시 //해당 플러그인이 마크업에 없으면 this.htUIList에 존재하지 않아 getsingle 사용시 사진첨부에 이벤트가 걸렸음 //해결 : this.htUIList에 존재하지 않으면 이벤트를 등록하지 않음 if(!this.htUIList[sUIName]){ return; } // map cmd & ui var elButton; if(!this.aUICmdMap[sUIName]){this.aUICmdMap[sUIName] = [];} this.aUICmdMap[sUIName][this.aUICmdMap[sUIName].length] = sCmd; //[SMARTEDITORSUS-901]플러그인 태그 코드 추가 시 <li>태그와<button>태그 사이에 개행이 있으면 이벤트가 등록되지 않는 현상 //원인 : IE9, Chrome, FF, Safari 에서는 태그를 개행 시 그 개행을 text node로 인식하여 firstchild가 text 노드가 되어 버튼 이벤트가 할당되지 않음 //해결 : firstchild에 이벤트를 거는 것이 아니라, child 중 button 인 것에 이벤트를 걸도록 변경 elButton = jindo.$$.getSingle('button', this.htUIList[sUIName]); if(!elButton){return;} this.oApp.registerBrowserEvent(elButton, sEvent, sCmd, aParams); }, getToolbarButtonByUIName : function(sUIName){ return jindo.$$.getSingle("BUTTON", this.htUIList[sUIName]); } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the editing mode using a Button element * @name hp_SE2M_EditingModeChanger.js */ nhn.husky.SE2M_EditingModeChanger = jindo.$Class({ name : "SE2M_EditingModeChanger", htConversionMode : null, $init : function(elAppContainer, htConversionMode){ this.htConversionMode = htConversionMode; this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ elAppContainer = jindo.$(elAppContainer) || document; //@ec[ this.elWYSIWYGButton = jindo.$$.getSingle("BUTTON.se2_to_editor", elAppContainer); this.elHTMLSrcButton = jindo.$$.getSingle("BUTTON.se2_to_html", elAppContainer); this.elTEXTButton = jindo.$$.getSingle("BUTTON.se2_to_text", elAppContainer); this.elModeToolbar = jindo.$$.getSingle("DIV.se2_conversion_mode", elAppContainer); //@ec] this.welWYSIWYGButtonLi = jindo.$Element(this.elWYSIWYGButton.parentNode); this.welHTMLSrcButtonLi = jindo.$Element(this.elHTMLSrcButton.parentNode); this.welTEXTButtonLi = jindo.$Element(this.elTEXTButton.parentNode); }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["isUseModeChanger", jindo.$Fn(this.isUseModeChanger, this).bind()]); }, $ON_MSG_APP_READY : function(){ this.oApp.registerBrowserEvent(this.elWYSIWYGButton, "click", "EVENT_CHANGE_EDITING_MODE_CLICKED", ["WYSIWYG"]); this.oApp.registerBrowserEvent(this.elHTMLSrcButton, "click", "EVENT_CHANGE_EDITING_MODE_CLICKED", ["HTMLSrc"]); this.oApp.registerBrowserEvent(this.elTEXTButton, "click", "EVENT_CHANGE_EDITING_MODE_CLICKED", ["TEXT", false]); this.showModeChanger(); if(this.isUseModeChanger() === false && this.oApp.isUseVerticalResizer() === false){ this.elModeToolbar.style.display = "none"; } }, // [SMARTEDITORSUS-906][SMARTEDITORSUS-1433] Editing Mode 사용 여부 처리 (true:사용함/ false:사용하지 않음) showModeChanger : function(){ if(this.isUseModeChanger()){ this.elWYSIWYGButton.style.display = 'block'; this.elHTMLSrcButton.style.display = 'block'; this.elTEXTButton.style.display = 'block'; }else{ this.elWYSIWYGButton.style.display = 'none'; this.elHTMLSrcButton.style.display = 'none'; this.elTEXTButton.style.display = 'none'; } }, isUseModeChanger : function(){ return (typeof(this.htConversionMode) === 'undefined' || typeof(this.htConversionMode.bUseModeChanger) === 'undefined' || this.htConversionMode.bUseModeChanger === true) ? true : false; }, $ON_EVENT_CHANGE_EDITING_MODE_CLICKED : function(sMode, bNoAlertMsg){ if (sMode == 'TEXT') { //에디터 영역 내에 모든 내용 가져옴. var sContent = this.oApp.getIR(); // 내용이 있으면 경고창 띄우기 if (sContent.length > 0 && !bNoAlertMsg) { if ( !confirm(this.oApp.$MSG("SE2M_EditingModeChanger.confirmTextMode")) ) { return false; } } this.oApp.exec("CHANGE_EDITING_MODE", [sMode]); }else{ this.oApp.exec("CHANGE_EDITING_MODE", [sMode]); } if ('HTMLSrc' == sMode) { this.oApp.exec('MSG_NOTIFY_CLICKCR', ['htmlmode']); } else if ('TEXT' == sMode) { this.oApp.exec('MSG_NOTIFY_CLICKCR', ['textmode']); } else { this.oApp.exec('MSG_NOTIFY_CLICKCR', ['editormode']); } }, $ON_DISABLE_ALL_UI : function(htOptions){ htOptions = htOptions || {}; var waExceptions = jindo.$A(htOptions.aExceptions || []); if(waExceptions.has("mode_switcher")){ return; } if(this.oApp.getEditingMode() == "WYSIWYG"){ this.welWYSIWYGButtonLi.removeClass("active"); this.elHTMLSrcButton.disabled = true; this.elTEXTButton.disabled = true; } else if (this.oApp.getEditingMode() == 'TEXT') { this.welTEXTButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = true; this.elHTMLSrcButton.disabled = true; }else{ this.welHTMLSrcButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = true; this.elTEXTButton.disabled = true; } }, $ON_ENABLE_ALL_UI : function(){ if(this.oApp.getEditingMode() == "WYSIWYG"){ this.welWYSIWYGButtonLi.addClass("active"); this.elHTMLSrcButton.disabled = false; this.elTEXTButton.disabled = false; } else if (this.oApp.getEditingMode() == 'TEXT') { this.welTEXTButtonLi.addClass("active"); this.elWYSIWYGButton.disabled = false; this.elHTMLSrcButton.disabled = false; }else{ this.welHTMLSrcButtonLi.addClass("active"); this.elWYSIWYGButton.disabled = false; this.elTEXTButton.disabled = false; } }, $ON_CHANGE_EDITING_MODE : function(sMode){ if(sMode == "HTMLSrc"){ this.welWYSIWYGButtonLi.removeClass("active"); this.welHTMLSrcButtonLi.addClass("active"); this.welTEXTButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = false; this.elHTMLSrcButton.disabled = true; this.elTEXTButton.disabled = false; this.oApp.exec("HIDE_ALL_DIALOG_LAYER"); this.oApp.exec("DISABLE_ALL_UI", [{aExceptions:["mode_switcher"]}]); } else if (sMode == 'TEXT') { this.welWYSIWYGButtonLi.removeClass("active"); this.welHTMLSrcButtonLi.removeClass("active"); this.welTEXTButtonLi.addClass("active"); this.elWYSIWYGButton.disabled = false; this.elHTMLSrcButton.disabled = false; this.elTEXTButton.disabled = true; this.oApp.exec("HIDE_ALL_DIALOG_LAYER"); this.oApp.exec("DISABLE_ALL_UI", [{aExceptions:["mode_switcher"]}]); }else{ this.welWYSIWYGButtonLi.addClass("active"); this.welHTMLSrcButtonLi.removeClass("active"); this.welTEXTButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = true; this.elHTMLSrcButton.disabled = false; this.elTEXTButton.disabled = false; this.oApp.exec("RESET_STYLE_STATUS"); this.oApp.exec("ENABLE_ALL_UI", []); } } }); //} /*[ * LOAD_CONTENTS_FIELD * * 에디터 초기화 시에 넘어온 Contents(DB 저장 값)필드를 읽어 에디터에 설정한다. * * bDontAddUndo boolean Contents를 설정하면서 UNDO 히스토리는 추가 하지않는다. * ---------------------------------------------------------------------------]*/ /*[ * UPDATE_IR_FIELD * * 에디터의 IR값을 IR필드에 설정 한다. * * none * ---------------------------------------------------------------------------]*/ /*[ * CHANGE_EDITING_MODE * * 에디터의 편집 모드를 변경한다. * * sMode string 전환 할 모드명 * bNoFocus boolean 모드 전환 후에 에디터에 포커스를 강제로 할당하지 않는다. * ---------------------------------------------------------------------------]*/ /*[ * FOCUS * * 에디터 편집 영역에 포커스를 준다. * * none * ---------------------------------------------------------------------------]*/ /*[ * SET_IR * * IR값을 에디터에 설정 한다. * * none * ---------------------------------------------------------------------------]*/ /*[ * REGISTER_EDITING_AREA * * 편집 영역을 플러그인을 등록 시킨다. 원활한 모드 전환과 IR값 공유등를 위해서 초기화 시에 등록이 필요하다. * * oEditingAreaPlugin object 편집 영역 플러그인 인스턴스 * ---------------------------------------------------------------------------]*/ /*[ * MSG_EDITING_AREA_RESIZE_STARTED * * 편집 영역 사이즈 조절이 시작 되었음을 알리는 메시지. * * none * ---------------------------------------------------------------------------]*/ /*[ * RESIZE_EDITING_AREA * * 편집 영역 사이즈를 설정 한다. 변경 전후에 MSG_EDITIING_AREA_RESIZE_STARTED/MSG_EDITING_AREA_RESIZE_ENED를 발생 시켜 줘야 된다. * * ipNewWidth number 새 폭 * ipNewHeight number 새 높이 * ---------------------------------------------------------------------------]*/ /*[ * RESIZE_EDITING_AREA_BY * * 편집 영역 사이즈를 늘리거나 줄인다. 변경 전후에 MSG_EDITIING_AREA_RESIZE_STARTED/MSG_EDITING_AREA_RESIZE_ENED를 발생 시켜 줘야 된다. * 변경치를 입력하면 원래 사이즈에서 변경하여 px로 적용하며, width가 %로 설정된 경우에는 폭 변경치가 입력되어도 적용되지 않는다. * * ipWidthChange number 폭 변경치 * ipHeightChange number 높이 변경치 * ---------------------------------------------------------------------------]*/ /*[ * MSG_EDITING_AREA_RESIZE_ENDED * * 편집 영역 사이즈 조절이 끝났음을 알리는 메시지. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc IR 값과 복수개의 편집 영역을 관리하는 플러그인 */ nhn.husky.SE_EditingAreaManager = jindo.$Class({ name : "SE_EditingAreaManager", // Currently active plugin instance(SE_EditingArea_???) oActivePlugin : null, // Intermediate Representation of the content being edited. // This should be a textarea element. elContentsField : null, bIsDirty : false, bAutoResize : false, // [SMARTEDITORSUS-677] 에디터의 자동확장 기능 On/Off 여부 $init : function(sDefaultEditingMode, elContentsField, oDimension, fOnBeforeUnload, elAppContainer){ this.sDefaultEditingMode = sDefaultEditingMode; this.elContentsField = jindo.$(elContentsField); this._assignHTMLElements(elAppContainer); this.fOnBeforeUnload = fOnBeforeUnload; this.oEditingMode = {}; this.elContentsField.style.display = "none"; this.nMinWidth = parseInt((oDimension.nMinWidth || 60), 10); this.nMinHeight = parseInt((oDimension.nMinHeight || 60), 10); var oWidth = this._getSize([oDimension.nWidth, oDimension.width, this.elEditingAreaContainer.offsetWidth], this.nMinWidth); var oHeight = this._getSize([oDimension.nHeight, oDimension.height, this.elEditingAreaContainer.offsetHeight], this.nMinHeight); this.elEditingAreaContainer.style.width = oWidth.nSize + oWidth.sUnit; this.elEditingAreaContainer.style.height = oHeight.nSize + oHeight.sUnit; if(oWidth.sUnit === "px"){ elAppContainer.style.width = (oWidth.nSize + 2) + "px"; }else if(oWidth.sUnit === "%"){ elAppContainer.style.minWidth = this.nMinWidth + "px"; } }, _getSize : function(aSize, nMin){ var i, nLen, aRxResult, nSize, sUnit, sDefaultUnit = "px"; nMin = parseInt(nMin, 10); for(i=0, nLen=aSize.length; i<nLen; i++){ if(!aSize[i]){ continue; } if(!isNaN(aSize[i])){ nSize = parseInt(aSize[i], 10); sUnit = sDefaultUnit; break; } aRxResult = /([0-9]+)(.*)/i.exec(aSize[i]); if(!aRxResult || aRxResult.length < 2 || aRxResult[1] <= 0){ continue; } nSize = parseInt(aRxResult[1], 10); sUnit = aRxResult[2]; if(!sUnit){ sUnit = sDefaultUnit; } if(nSize < nMin && sUnit === sDefaultUnit){ nSize = nMin; } break; } if(!sUnit){ sUnit = sDefaultUnit; } if(isNaN(nSize) || (nSize < nMin && sUnit === sDefaultUnit)){ nSize = nMin; } return {nSize : nSize, sUnit : sUnit}; }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.elEditingAreaContainer = jindo.$$.getSingle("DIV.husky_seditor_editing_area_container", elAppContainer); //@ec] // [SMARTEDITORSUS-1585] this.toolbarArea = jindo.$$.getSingle(".se2_tool", elAppContainer); // --[SMARTEDITORSUS-1585] }, $BEFORE_MSG_APP_READY : function(msg){ this.oApp.exec("ADD_APP_PROPERTY", ["elEditingAreaContainer", this.elEditingAreaContainer]); this.oApp.exec("ADD_APP_PROPERTY", ["welEditingAreaContainer", jindo.$Element(this.elEditingAreaContainer)]); this.oApp.exec("ADD_APP_PROPERTY", ["getEditingAreaHeight", jindo.$Fn(this.getEditingAreaHeight, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getEditingAreaWidth", jindo.$Fn(this.getEditingAreaWidth, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getRawContents", jindo.$Fn(this.getRawContents, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getContents", jindo.$Fn(this.getContents, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getIR", jindo.$Fn(this.getIR, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["setContents", this.setContents]); this.oApp.exec("ADD_APP_PROPERTY", ["setIR", this.setIR]); this.oApp.exec("ADD_APP_PROPERTY", ["getEditingMode", jindo.$Fn(this.getEditingMode, this).bind()]); }, $ON_MSG_APP_READY : function(){ this.htOptions = this.oApp.htOptions[this.name] || {}; this.sDefaultEditingMode = this.htOptions["sDefaultEditingMode"] || this.sDefaultEditingMode; this.iframeWindow = this.oApp.getWYSIWYGWindow(); this.oApp.exec("REGISTER_CONVERTERS", []); this.oApp.exec("CHANGE_EDITING_MODE", [this.sDefaultEditingMode, true]); this.oApp.exec("LOAD_CONTENTS_FIELD", [false]); //[SMARTEDITORSUS-1327] IE 7/8에서 ALT+0으로 팝업 띄우고 esc클릭시 팝업창 닫히게 하려면 아래 부분 꼭 필요함. this.oApp.exec("REGISTER_HOTKEY", ["esc", "CLOSE_LAYER_POPUP", [], document]); if(!!this.fOnBeforeUnload){ window.onbeforeunload = this.fOnBeforeUnload; }else{ window.onbeforeunload = jindo.$Fn(function(){ // [SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] QuickEditor 설정 API 개선으로, submit 이후 발생하게 되는 beforeunload 이벤트 핸들링 제거 //this.oApp.exec("MSG_BEFOREUNLOAD_FIRED"); // --// [SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] //if(this.getContents() != this.elContentsField.value || this.bIsDirty){ if(this.getRawContents() != this.sCurrentRawContents || this.bIsDirty){ return this.oApp.$MSG("SE_EditingAreaManager.onExit"); } }, this).bind(); } }, $ON_CLOSE_LAYER_POPUP : function() { this.oApp.exec("ENABLE_ALL_UI"); // 모든 UI 활성화. this.oApp.exec("DESELECT_UI", ["helpPopup"]); this.oApp.exec("HIDE_ALL_DIALOG_LAYER", []); this.oApp.exec("HIDE_EDITING_AREA_COVER"); // 편집 영역 활성화. this.oApp.exec("FOCUS"); }, $AFTER_MSG_APP_READY : function(){ this.oApp.exec("UPDATE_RAW_CONTENTS"); if(!!this.oApp.htOptions[this.name] && this.oApp.htOptions[this.name].bAutoResize){ this.bAutoResize = this.oApp.htOptions[this.name].bAutoResize; } this.startAutoResize(); // [SMARTEDITORSUS-677] 편집영역 자동 확장 옵션이 TRUE이면 자동확장 시작 }, $ON_LOAD_CONTENTS_FIELD : function(bDontAddUndo){ var sContentsFieldValue = this.elContentsField.value; // [SMARTEDITORSUS-177] [IE9] 글 쓰기, 수정 시에 elContentsField 에 들어간 공백을 제거 // [SMARTEDITORSUS-312] [FF4] 인용구 첫번째,두번째 디자인 1회 선택 시 에디터에 적용되지 않음 sContentsFieldValue = sContentsFieldValue.replace(/^\s+/, ""); this.oApp.exec("SET_CONTENTS", [sContentsFieldValue, bDontAddUndo]); }, // 현재 contents를 form의 textarea에 세팅 해 줌. // form submit 전에 이 부분을 실행시켜야 됨. $ON_UPDATE_CONTENTS_FIELD : function(){ //this.oIRField.value = this.oApp.getIR(); this.elContentsField.value = this.oApp.getContents(); this.oApp.exec("UPDATE_RAW_CONTENTS"); //this.sCurrentRawContents = this.elContentsField.value; }, // 에디터의 현재 상태를 기억해 둠. 페이지를 떠날 때 이 값이 변경 됐는지 확인 해서 내용이 변경 됐다는 경고창을 띄움 // RawContents 대신 contents를 이용해도 되지만, contents 획득을 위해서는 변환기를 실행해야 되기 때문에 RawContents 이용 $ON_UPDATE_RAW_CONTENTS : function(){ this.sCurrentRawContents = this.oApp.getRawContents(); }, $BEFORE_CHANGE_EDITING_MODE : function(sMode){ if(!this.oEditingMode[sMode]){ return false; } this.stopAutoResize(); // [SMARTEDITORSUS-677] 해당 편집 모드에서의 자동확장을 중지함 this._oPrevActivePlugin = this.oActivePlugin; this.oActivePlugin = this.oEditingMode[sMode]; }, $AFTER_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ if(this._oPrevActivePlugin){ var sIR = this._oPrevActivePlugin.getIR(); this.oApp.exec("SET_IR", [sIR]); //this.oApp.exec("ENABLE_UI", [this._oPrevActivePlugin.sMode]); this._setEditingAreaDimension(); } //this.oApp.exec("DISABLE_UI", [this.oActivePlugin.sMode]); this.startAutoResize(); // [SMARTEDITORSUS-677] 변경된 편집 모드에서의 자동확장을 시작 if(!bNoFocus){ this.oApp.delayedExec("FOCUS", [], 0); } }, /** * 페이지를 떠날 때 alert을 표시할지 여부를 셋팅하는 함수. */ $ON_SET_IS_DIRTY : function(bIsDirty){ this.bIsDirty = bIsDirty; }, $ON_FOCUS : function(){ if(!this.oActivePlugin || typeof this.oActivePlugin.setIR != "function"){ return; } // [SMARTEDITORSUS-599] ipad 대응 이슈. // ios5에서는 this.iframe.contentWindow focus가 없어서 생긴 이슈. // document가 아닌 window에 focus() 주어야만 본문에 focus가 가고 입력이됨. //[SMARTEDITORSUS-1017] [iOS5대응] 모드 전환 시 textarea에 포커스가 있어도 글자가 입력이 안되는 현상 //원인 : WYSIWYG모드가 아닐 때에도 iframe의 contentWindow에 focus가 가면서 focus기능이 작동하지 않음 //해결 : WYSIWYG모드 일때만 실행 되도록 조건식 추가 및 기존에 blur처리 코드 삭제 //[SMARTEDITORSUS-1594] 크롬에서 웹접근성용 키로 빠져나간 후 다시 진입시 간혹 포커싱이 안되는 문제가 있어 iframe에 포커싱을 먼저 주도록 수정 if(!!this.iframeWindow && this.iframeWindow.document.hasFocus && !this.iframeWindow.document.hasFocus() && this.oActivePlugin.sMode == "WYSIWYG"){ this.iframeWindow.focus(); } this.oActivePlugin.focus(); }, $ON_IE_FOCUS : function(){ if(!this.oApp.oNavigator.ie){ return; } this.oApp.exec("FOCUS"); }, $ON_SET_CONTENTS : function(sContents, bDontAddUndoHistory){ this.setContents(sContents, bDontAddUndoHistory); }, $BEFORE_SET_IR : function(sIR, bDontAddUndoHistory){ bDontAddUndoHistory = bDontAddUndoHistory || false; if(!bDontAddUndoHistory){ this.oApp.exec("RECORD_UNDO_ACTION", ["BEFORE SET CONTENTS", {sSaveTarget:"BODY"}]); } }, $ON_SET_IR : function(sIR){ if(!this.oActivePlugin || typeof this.oActivePlugin.setIR != "function"){ return; } this.oActivePlugin.setIR(sIR); }, $AFTER_SET_IR : function(sIR, bDontAddUndoHistory){ bDontAddUndoHistory = bDontAddUndoHistory || false; if(!bDontAddUndoHistory){ this.oApp.exec("RECORD_UNDO_ACTION", ["AFTER SET CONTENTS", {sSaveTarget:"BODY"}]); } }, $ON_REGISTER_EDITING_AREA : function(oEditingAreaPlugin){ this.oEditingMode[oEditingAreaPlugin.sMode] = oEditingAreaPlugin; if(oEditingAreaPlugin.sMode == 'WYSIWYG'){ this.attachDocumentEvents(oEditingAreaPlugin.oEditingArea); } this._setEditingAreaDimension(oEditingAreaPlugin); }, $ON_MSG_EDITING_AREA_RESIZE_STARTED : function(){ // [SMARTEDITORSUS-1585] 글감, 글양식, 글장식을 열었을 때 리사이징이 발생하면 커버용 레이어가 사라지는 문제 개선 this._isLayerReasonablyShown = false; var elSelectedUI = jindo.$$.getSingle("ul[class^='se2_itool']>li.active", this.toolbarArea, {oneTimeOffCache : true}); if(elSelectedUI){ var elSelectedUIParent = elSelectedUI.parentNode; } // 글감 버튼을 포함한 부모는 ul.se2_itool2, 글장식, 글양식 버튼을 포함한 부모는 ul.se2_itool4 if(elSelectedUIParent && (elSelectedUIParent.className == "se2_itool2" || elSelectedUIParent.className == "se2_itool4")){ this._isLayerReasonablyShown = true; } // --[SMARTEDITORSUS-1585] this._fitElementInEditingArea(this.elEditingAreaContainer); this.oApp.exec("STOP_AUTORESIZE_EDITING_AREA"); // [SMARTEDITORSUS-677] 사용자가 편집영역 사이즈를 변경하면 자동확장 기능 중지 this.oApp.exec("SHOW_EDITING_AREA_COVER"); this.elEditingAreaContainer.style.overflow = "hidden"; // this.elResizingBoard.style.display = "block"; this.iStartingHeight = parseInt(this.elEditingAreaContainer.style.height, 10); }, /** * [SMARTEDITORSUS-677] 편집영역 자동확장 기능을 중지함 */ $ON_STOP_AUTORESIZE_EDITING_AREA : function(){ if(!this.bAutoResize){ return; } this.stopAutoResize(); this.bAutoResize = false; }, /** * [SMARTEDITORSUS-677] 해당 편집 모드에서의 자동확장을 시작함 */ startAutoResize : function(){ if(!this.bAutoResize || !this.oActivePlugin || typeof this.oActivePlugin.startAutoResize != "function"){ return; } this.oActivePlugin.startAutoResize(); }, /** * [SMARTEDITORSUS-677] 해당 편집 모드에서의 자동확장을 중지함 */ stopAutoResize : function(){ if(!this.bAutoResize || !this.oActivePlugin || typeof this.oActivePlugin.stopAutoResize != "function"){ return; } this.oActivePlugin.stopAutoResize(); }, $ON_RESIZE_EDITING_AREA: function(ipNewWidth, ipNewHeight){ if(ipNewWidth !== null && typeof ipNewWidth !== "undefined"){ this._resizeWidth(ipNewWidth, "px"); } if(ipNewHeight !== null && typeof ipNewHeight !== "undefined"){ this._resizeHeight(ipNewHeight, "px"); } this._fitElementInEditingArea(this.elResizingBoard); this._setEditingAreaDimension(); }, _resizeWidth : function(ipNewWidth, sUnit){ var iNewWidth = parseInt(ipNewWidth, 10); if(iNewWidth < this.nMinWidth){ iNewWidth = this.nMinWidth; } if(ipNewWidth){ this.elEditingAreaContainer.style.width = iNewWidth + sUnit; } }, _resizeHeight : function(ipNewHeight, sUnit){ var iNewHeight = parseInt(ipNewHeight, 10); if(iNewHeight < this.nMinHeight){ iNewHeight = this.nMinHeight; } if(ipNewHeight){ this.elEditingAreaContainer.style.height = iNewHeight + sUnit; } }, $ON_RESIZE_EDITING_AREA_BY : function(ipWidthChange, ipHeightChange){ var iWidthChange = parseInt(ipWidthChange, 10); var iHeightChange = parseInt(ipHeightChange, 10); var iWidth; var iHeight; if(ipWidthChange !== 0 && this.elEditingAreaContainer.style.width.indexOf("%") === -1){ iWidth = this.elEditingAreaContainer.style.width?parseInt(this.elEditingAreaContainer.style.width, 10)+iWidthChange:null; } if(iHeightChange !== 0){ iHeight = this.elEditingAreaContainer.style.height?this.iStartingHeight+iHeightChange:null; } if(!ipWidthChange && !iHeightChange){ return; } this.oApp.exec("RESIZE_EDITING_AREA", [iWidth, iHeight]); }, $ON_MSG_EDITING_AREA_RESIZE_ENDED : function(FnMouseDown, FnMouseMove, FnMouseUp){ // [SMARTEDITORSUS-1585] 글감, 글양식, 글장식을 열었을 때 리사이징이 발생하면 커버용 레이어가 사라지는 문제 개선 if(!this._isLayerReasonablyShown){ this.oApp.exec("HIDE_EDITING_AREA_COVER"); } // --[SMARTEDITORSUS-1585] this.elEditingAreaContainer.style.overflow = ""; // this.elResizingBoard.style.display = "none"; this._setEditingAreaDimension(); }, $ON_SHOW_EDITING_AREA_COVER : function(){ // this.elEditingAreaContainer.style.overflow = "hidden"; if(!this.elResizingBoard){ this.createCoverDiv(); } this.elResizingBoard.style.display = "block"; }, $ON_HIDE_EDITING_AREA_COVER : function(){ // this.elEditingAreaContainer.style.overflow = ""; if(!this.elResizingBoard){ return; } this.elResizingBoard.style.display = "none"; }, $ON_KEEP_WITHIN_EDITINGAREA : function(elLayer, nHeight){ var nTop = parseInt(elLayer.style.top, 10); if(nTop + elLayer.offsetHeight > this.oApp.elEditingAreaContainer.offsetHeight){ if(typeof nHeight == "number"){ elLayer.style.top = nTop - elLayer.offsetHeight - nHeight + "px"; }else{ elLayer.style.top = this.oApp.elEditingAreaContainer.offsetHeight - elLayer.offsetHeight + "px"; } } var nLeft = parseInt(elLayer.style.left, 10); if(nLeft + elLayer.offsetWidth > this.oApp.elEditingAreaContainer.offsetWidth){ elLayer.style.left = this.oApp.elEditingAreaContainer.offsetWidth - elLayer.offsetWidth + "px"; } }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, $ON_EVENT_EDITING_AREA_MOUSEDOWN : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, $ON_EVENT_EDITING_AREA_SCROLL : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, _setEditingAreaDimension : function(oEditingAreaPlugin){ oEditingAreaPlugin = oEditingAreaPlugin || this.oActivePlugin; this._fitElementInEditingArea(oEditingAreaPlugin.elEditingArea); }, _fitElementInEditingArea : function(el){ el.style.height = this.elEditingAreaContainer.offsetHeight+"px"; // el.style.width = this.elEditingAreaContainer.offsetWidth+"px"; // el.style.width = this.elEditingAreaContainer.style.width || (this.elEditingAreaContainer.offsetWidth+"px"); }, attachDocumentEvents : function(doc){ this.oApp.registerBrowserEvent(doc, "click", "EVENT_EDITING_AREA_CLICK"); this.oApp.registerBrowserEvent(doc, "dblclick", "EVENT_EDITING_AREA_DBLCLICK"); this.oApp.registerBrowserEvent(doc, "mousedown", "EVENT_EDITING_AREA_MOUSEDOWN"); this.oApp.registerBrowserEvent(doc, "mousemove", "EVENT_EDITING_AREA_MOUSEMOVE"); this.oApp.registerBrowserEvent(doc, "mouseup", "EVENT_EDITING_AREA_MOUSEUP"); this.oApp.registerBrowserEvent(doc, "mouseout", "EVENT_EDITING_AREA_MOUSEOUT"); this.oApp.registerBrowserEvent(doc, "mousewheel", "EVENT_EDITING_AREA_MOUSEWHEEL"); this.oApp.registerBrowserEvent(doc, "keydown", "EVENT_EDITING_AREA_KEYDOWN"); this.oApp.registerBrowserEvent(doc, "keypress", "EVENT_EDITING_AREA_KEYPRESS"); this.oApp.registerBrowserEvent(doc, "keyup", "EVENT_EDITING_AREA_KEYUP"); this.oApp.registerBrowserEvent(doc, "scroll", "EVENT_EDITING_AREA_SCROLL"); }, createCoverDiv : function(){ this.elResizingBoard = document.createElement("DIV"); this.elEditingAreaContainer.insertBefore(this.elResizingBoard, this.elEditingAreaContainer.firstChild); this.elResizingBoard.style.position = "absolute"; this.elResizingBoard.style.background = "#000000"; this.elResizingBoard.style.zIndex=100; this.elResizingBoard.style.border=1; this.elResizingBoard.style["opacity"] = 0.0; this.elResizingBoard.style.filter="alpha(opacity=0.0)"; this.elResizingBoard.style["MozOpacity"]=0.0; this.elResizingBoard.style["-moz-opacity"] = 0.0; this.elResizingBoard.style["-khtml-opacity"] = 0.0; this._fitElementInEditingArea(this.elResizingBoard); this.elResizingBoard.style.width = this.elEditingAreaContainer.offsetWidth+"px"; this.elResizingBoard.style.display = "none"; }, $ON_GET_COVER_DIV : function(sAttr,oReturn){ if(!!this.elResizingBoard) { oReturn[sAttr] = this.elResizingBoard; } }, getIR : function(){ if(!this.oActivePlugin){ return ""; } return this.oActivePlugin.getIR(); }, setIR : function(sIR, bDontAddUndo){ this.oApp.exec("SET_IR", [sIR, bDontAddUndo]); }, getRawContents : function(){ if(!this.oActivePlugin){ return ""; } return this.oActivePlugin.getRawContents(); }, getContents : function(){ var sIR = this.oApp.getIR(); var sContents; if(this.oApp.applyConverter){ sContents = this.oApp.applyConverter("IR_TO_DB", sIR, this.oApp.getWYSIWYGDocument()); }else{ sContents = sIR; } sContents = this._cleanContents(sContents); return sContents; }, _cleanContents : function(sContents){ return sContents.replace(new RegExp("(<img [^>]*>)"+unescape("%uFEFF")+"", "ig"), "$1"); }, setContents : function(sContents, bDontAddUndo){ var sIR; if(this.oApp.applyConverter){ sIR = this.oApp.applyConverter("DB_TO_IR", sContents, this.oApp.getWYSIWYGDocument()); }else{ sIR = sContents; } this.oApp.exec("SET_IR", [sIR, bDontAddUndo]); }, getEditingMode : function(){ return this.oActivePlugin.sMode; }, getEditingAreaWidth : function(){ return this.elEditingAreaContainer.offsetWidth; }, getEditingAreaHeight : function(){ return this.elEditingAreaContainer.offsetHeight; } }); //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to resizing the editing area vertically * @name hp_SE_EditingAreaVerticalResizer.js */ nhn.husky.SE_EditingAreaVerticalResizer = jindo.$Class({ name : "SE_EditingAreaVerticalResizer", oResizeGrip : null, sCookieNotice : "bHideResizeNotice", nEditingAreaMinHeight : null, // [SMARTEDITORSUS-677] 편집 영역의 최소 높이 htConversionMode : null, $init : function(elAppContainer, htConversionMode){ this.htConversionMode = htConversionMode; this._assignHTMLElements(elAppContainer); }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["isUseVerticalResizer", jindo.$Fn(this.isUseVerticalResizer, this).bind()]); }, $ON_MSG_APP_READY : function(){ //[SMARTEDITORSUS-941][iOS5대응]아이패드의 자동 확장 기능이 동작하지 않을 때 에디터 창보다 긴 내용을 작성하면 에디터를 뚫고 나오는 현상 //원인 : 자동확장 기능이 정지 될 경우 iframe에 스크롤이 생기지 않고, 창을 뚫고 나옴 //해결 : 항상 자동확장 기능이 켜져있도록 변경. 자동 확장 기능 관련한 이벤트 코드도 모바일 사파리에서 예외 처리 if(jindo.$Agent().navigator().msafari){ jindo.$Element(this.oResizeGrip).first().text('입력창 높이 자동 조정 바'); this.oResizeGrip.disabled = true; return; } this.$FnMouseDown = jindo.$Fn(this._mousedown, this); this.$FnMouseMove = jindo.$Fn(this._mousemove, this); this.$FnMouseUp = jindo.$Fn(this._mouseup, this); this.$FnMouseOver = jindo.$Fn(this._mouseover, this); this.$FnMouseOut = jindo.$Fn(this._mouseout, this); this.$FnMouseDown.attach(this.oResizeGrip, "mousedown"); this.$FnMouseOver.attach(this.oResizeGrip, "mouseover"); this.$FnMouseOut.attach(this.oResizeGrip, "mouseout"); this.oApp.exec("REGISTER_HOTKEY", ["shift+esc", "FOCUS_RESIZER"]); this.oApp.exec("ADD_APP_PROPERTY", ["checkResizeGripPosition", jindo.$Fn(this.checkResizeGripPosition, this).bind()]); // [SMARTEDITORSUS-677] if(!!this.welNoticeLayer && !Number(jindo.$Cookie().get(this.sCookieNotice))){ this.welNoticeLayer.delegate("click", "BUTTON.bt_clse", jindo.$Fn(this._closeNotice, this).bind()); this.welNoticeLayer.show(); } if(!!this.oApp.getEditingAreaHeight){ this.nEditingAreaMinHeight = this.oApp.getEditingAreaHeight(); // [SMARTEDITORSUS-677] 편집 영역의 최소 높이를 가져와 Gap 처리 시 사용 } this.showVerticalResizer(); if(this.isUseVerticalResizer() === false && this.oApp.isUseModeChanger() === false){ this.elModeToolbar.style.display = "none"; } }, // [SMARTEDITORSUS-906][SMARTEDITORSUS-1433] Resizbar 사용 여부 처리 (true:사용함/ false:사용하지 않음) showVerticalResizer : function(){ if(this.isUseVerticalResizer()){ this.oResizeGrip.style.display = 'block'; }else{ this.oResizeGrip.style.display = 'none'; } }, isUseVerticalResizer : function(){ return (typeof(this.htConversionMode) === 'undefined' || typeof(this.htConversionMode.bUseVerticalResizer) === 'undefined' || this.htConversionMode.bUseVerticalResizer === true) ? true : false; }, /** * [SMARTEDITORSUS-677] [에디터 자동확장 ON인 경우] * 입력창 크기 조절 바의 위치를 확인하여 브라우저 하단에 위치한 경우 자동확장을 멈춤 */ checkResizeGripPosition : function(bExpand){ var oDocument = jindo.$Document(); var nGap = (jindo.$Element(this.oResizeGrip).offset().top - oDocument.scrollPosition().top + 25) - oDocument.clientSize().height; if(nGap <= 0){ return; } if(bExpand){ if(this.nEditingAreaMinHeight > this.oApp.getEditingAreaHeight() - nGap){ // [SMARTEDITORSUS-822] 수정 모드인 경우에 대비 nGap = (-1) * (this.nEditingAreaMinHeight - this.oApp.getEditingAreaHeight()); } // Gap 만큼 편집영역 사이즈를 조절하여 // 사진 첨부나 붙여넣기 등의 사이즈가 큰 내용 추가가 있었을 때 입력창 크기 조절 바가 숨겨지지 않도록 함 this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED"); this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, (-1) * nGap]); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED"); } this.oApp.exec("STOP_AUTORESIZE_EDITING_AREA"); }, $ON_FOCUS_RESIZER : function(){ this.oApp.exec("IE_HIDE_CURSOR"); this.oResizeGrip.focus(); }, _assignHTMLElements : function(elAppContainer, htConversionMode){ //@ec[ this.oResizeGrip = jindo.$$.getSingle("BUTTON.husky_seditor_editingArea_verticalResizer", elAppContainer); this.elModeToolbar = jindo.$$.getSingle("DIV.se2_conversion_mode", elAppContainer); //@ec] this.welNoticeLayer = jindo.$Element(jindo.$$.getSingle("DIV.husky_seditor_resize_notice", elAppContainer)); this.welConversionMode = jindo.$Element(this.oResizeGrip.parentNode); }, _mouseover : function(oEvent){ oEvent.stopBubble(); this.welConversionMode.addClass("controller_on"); }, _mouseout : function(oEvent){ oEvent.stopBubble(); this.welConversionMode.removeClass("controller_on"); }, _mousedown : function(oEvent){ this.iStartHeight = oEvent.pos().clientY; this.iStartHeightOffset = oEvent.pos().layerY; this.$FnMouseMove.attach(document, "mousemove"); this.$FnMouseUp.attach(document, "mouseup"); this.iStartHeight = oEvent.pos().clientY; this.oApp.exec("HIDE_ACTIVE_LAYER"); this.oApp.exec("HIDE_ALL_DIALOG_LAYER"); this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); }, _mousemove : function(oEvent){ var iHeightChange = oEvent.pos().clientY - this.iStartHeight; this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, iHeightChange]); }, _mouseup : function(oEvent){ this.$FnMouseMove.detach(document, "mousemove"); this.$FnMouseUp.detach(document, "mouseup"); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); }, _closeNotice : function(){ this.welNoticeLayer.hide(); jindo.$Cookie().set(this.sCookieNotice, 1, 365*10); } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations directly related to editing the HTML source code using Textarea element * @name hp_SE_EditingArea_HTMLSrc.js * @required SE_EditingAreaManager */ nhn.husky.SE_EditingArea_HTMLSrc = jindo.$Class({ name : "SE_EditingArea_HTMLSrc", sMode : "HTMLSrc", bAutoResize : false, // [SMARTEDITORSUS-677] 해당 편집모드의 자동확장 기능 On/Off 여부 nMinHeight : null, // [SMARTEDITORSUS-677] 편집 영역의 최소 높이 $init : function(sTextArea) { this.elEditingArea = jindo.$(sTextArea); }, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); this.oApp.exec("REGISTER_EDITING_AREA", [this]); }, $ON_MSG_APP_READY : function() { if(!!this.oApp.getEditingAreaHeight){ this.nMinHeight = this.oApp.getEditingAreaHeight(); // [SMARTEDITORSUS-677] 편집 영역의 최소 높이를 가져와 자동 확장 처리를 할 때 사용 } }, $ON_CHANGE_EDITING_MODE : function(sMode) { if (sMode == this.sMode) { this.elEditingArea.style.display = "block"; } else { this.elEditingArea.style.display = "none"; } }, $AFTER_CHANGE_EDITING_MODE : function(sMode, bNoFocus) { if (sMode == this.sMode && !bNoFocus) { var o = new TextRange(this.elEditingArea); o.setSelection(0, 0); //[SMARTEDITORSUS-1017] [iOS5대응] 모드 전환 시 textarea에 포커스가 있어도 글자가 입력이 안되는 현상 //원인 : WYSIWYG모드가 아닐 때에도 iframe의 contentWindow에 focus가 가면서 focus기능이 작동하지 않음 //해결 : WYSIWYG모드 일때만 실행 되도록 조건식 추가 및 기존에 blur처리 코드 삭제 //모바일 textarea에서는 직접 클릭을해야만 키보드가 먹히기 때문에 우선은 커서가 안보이게 해서 사용자가 직접 클릭을 유도. // if(!!this.oNavigator.msafari){ // this.elEditingArea.blur(); // } } }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 시작 */ startAutoResize : function(){ var htOption = { nMinHeight : this.nMinHeight, wfnCallback : jindo.$Fn(this.oApp.checkResizeGripPosition, this).bind() }; //[SMARTEDITORSUS-941][iOS5대응]아이패드의 자동 확장 기능이 동작하지 않을 때 에디터 창보다 긴 내용을 작성하면 에디터를 뚫고 나오는 현상 //원인 : 자동확장 기능이 정지 될 경우 iframe에 스크롤이 생기지 않고, 창을 뚫고 나옴 //해결 : 항상 자동확장 기능이 켜져있도록 변경. 자동 확장 기능 관련한 이벤트 코드도 모바일 사파리에서 예외 처리 if(this.oNavigator.msafari){ htOption.wfnCallback = function(){}; } this.bAutoResize = true; this.AutoResizer = new nhn.husky.AutoResizer(this.elEditingArea, htOption); this.AutoResizer.bind(); }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 종료 */ stopAutoResize : function(){ this.AutoResizer.unbind(); }, getIR : function() { var sIR = this.getRawContents(); if (this.oApp.applyConverter) { sIR = this.oApp.applyConverter(this.sMode + "_TO_IR", sIR, this.oApp.getWYSIWYGDocument()); } return sIR; }, setIR : function(sIR) { if(sIR.toLowerCase() === "<br>" || sIR.toLowerCase() === "<p>&nbsp;</p>" || sIR.toLowerCase() === "<p><br></p>" || sIR.toLowerCase() === "<p></p>"){ sIR=""; } // [SMARTEDITORSUS-1589] 문서 모드가 Edge인 IE11에서 WYSIWYG 모드와 HTML 모드 전환 시, 문말에 무의미한 <br> 두 개가 첨가되는 현상으로 필터링 추가 var htBrowser = jindo.$Agent().navigator(); if(htBrowser.ie && htBrowser.nativeVersion == 11 && document.documentMode == 11){ // Edge 모드의 documentMode 값은 11 sIR = sIR.replace(/(<br><br>$)/, ""); } // --[SMARTEDITORSUS-1589] var sContent = sIR; if (this.oApp.applyConverter) { sContent = this.oApp.applyConverter("IR_TO_" + this.sMode, sContent, this.oApp.getWYSIWYGDocument()); } this.setRawContents(sContent); }, setRawContents : function(sContent) { if (typeof sContent !== 'undefined') { this.elEditingArea.value = sContent; } }, getRawContents : function() { return this.elEditingArea.value; }, focus : function() { this.elEditingArea.focus(); } }); /** * Selection for textfield * @author hooriza */ if (typeof window.TextRange == 'undefined') { window.TextRange = {}; } TextRange = function(oEl, oDoc) { this._o = oEl; this._oDoc = (oDoc || document); }; TextRange.prototype.getSelection = function() { var obj = this._o; var ret = [-1, -1]; if(isNaN(this._o.selectionStart)) { obj.focus(); // textarea support added by nagoon97 var range = this._oDoc.body.createTextRange(); var rangeField = null; rangeField = this._oDoc.selection.createRange().duplicate(); range.moveToElementText(obj); rangeField.collapse(true); range.setEndPoint("EndToEnd", rangeField); ret[0] = range.text.length; rangeField = this._oDoc.selection.createRange().duplicate(); range.moveToElementText(obj); rangeField.collapse(false); range.setEndPoint("EndToEnd", rangeField); ret[1] = range.text.length; obj.blur(); } else { ret[0] = obj.selectionStart; ret[1] = obj.selectionEnd; } return ret; }; TextRange.prototype.setSelection = function(start, end) { var obj = this._o; if (typeof end == 'undefined') { end = start; } if (obj.setSelectionRange) { obj.setSelectionRange(start, end); } else if (obj.createTextRange) { var range = obj.createTextRange(); range.collapse(true); range.moveStart("character", start); range.moveEnd("character", end - start); range.select(); obj.blur(); } }; TextRange.prototype.copy = function() { var r = this.getSelection(); return this._o.value.substring(r[0], r[1]); }; TextRange.prototype.paste = function(sStr) { var obj = this._o; var sel = this.getSelection(); var value = obj.value; var pre = value.substr(0, sel[0]); var post = value.substr(sel[1]); value = pre + sStr + post; obj.value = value; var n = 0; if (typeof this._oDoc.body.style.maxHeight == "undefined") { var a = pre.match(/\n/gi); n = ( a !== null ? a.length : 0 ); } this.setSelection(sel[0] + sStr.length - n); }; TextRange.prototype.cut = function() { var r = this.copy(); this.paste(''); return r; }; //} /** * @fileOverview This file contains Husky plugin that takes care of the operations directly related to editing the HTML source code using Textarea element * @name hp_SE_EditingArea_TEXT.js * @required SE_EditingAreaManager */ nhn.husky.SE_EditingArea_TEXT = jindo.$Class({ name : "SE_EditingArea_TEXT", sMode : "TEXT", sRxConverter : '@[0-9]+@', bAutoResize : false, // [SMARTEDITORSUS-677] 해당 편집모드의 자동확장 기능 On/Off 여부 nMinHeight : null, // [SMARTEDITORSUS-677] 편집 영역의 최소 높이 $init : function(sTextArea) { this.elEditingArea = jindo.$(sTextArea); }, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); this.oApp.exec("REGISTER_EDITING_AREA", [this]); this.oApp.exec("ADD_APP_PROPERTY", ["getTextAreaContents", jindo.$Fn(this.getRawContents, this).bind()]); }, $ON_MSG_APP_READY : function() { if(!!this.oApp.getEditingAreaHeight){ this.nMinHeight = this.oApp.getEditingAreaHeight(); // [SMARTEDITORSUS-677] 편집 영역의 최소 높이를 가져와 자동 확장 처리를 할 때 사용 } }, $ON_REGISTER_CONVERTERS : function() { this.oApp.exec("ADD_CONVERTER", ["IR_TO_TEXT", jindo.$Fn(this.irToText, this).bind()]); this.oApp.exec("ADD_CONVERTER", ["TEXT_TO_IR", jindo.$Fn(this.textToIr, this).bind()]); }, $ON_CHANGE_EDITING_MODE : function(sMode) { if (sMode == this.sMode) { this.elEditingArea.style.display = "block"; } else { this.elEditingArea.style.display = "none"; } }, $AFTER_CHANGE_EDITING_MODE : function(sMode, bNoFocus) { if (sMode == this.sMode && !bNoFocus) { var o = new TextRange(this.elEditingArea); o.setSelection(0, 0); } //[SMARTEDITORSUS-1017] [iOS5대응] 모드 전환 시 textarea에 포커스가 있어도 글자가 입력이 안되는 현상 //원인 : WYSIWYG모드가 아닐 때에도 iframe의 contentWindow에 focus가 가면서 focus기능이 작동하지 않음 //해결 : WYSIWYG모드 일때만 실행 되도록 조건식 추가 및 기존에 blur처리 코드 삭제 //모바일 textarea에서는 직접 클릭을해야만 키보드가 먹히기 때문에 우선은 커서가 안보이게 해서 사용자가 직접 클릭을 유도. // if(!!this.oNavigator.msafari){ // this.elEditingArea.blur(); // } }, irToText : function(sHtml) { var sContent = sHtml, nIdx = 0; var aTemp = sContent.match(new RegExp(this.sRxConverter)); // applyConverter에서 추가한 sTmpStr를 잠시 제거해준다. if (aTemp !== null) { sContent = sContent.replace(new RegExp(this.sRxConverter), ""); } //0.안보이는 값들에 대한 정리. (에디터 모드에 view와 text모드의 view를 동일하게 해주기 위해서) sContent = sContent.replace(/\r/g, '');// MS엑셀 테이블에서 tr별로 분리해주는 역할이\r이기 때문에 text모드로 변경시에 가독성을 위해 \r 제거하는 것은 임시 보류. - 11.01.28 by cielo sContent = sContent.replace(/[\n|\t]/g, ''); // 개행문자, 안보이는 공백 제거 sContent = sContent.replace(/[\v|\f]/g, ''); // 개행문자, 안보이는 공백 제거 //1. 먼저, 빈 라인 처리 . sContent = sContent.replace(/<p><br><\/p>/gi, '\n'); sContent = sContent.replace(/<P>&nbsp;<\/P>/gi, '\n'); //2. 빈 라인 이외에 linebreak 처리. sContent = sContent.replace(/<br(\s)*\/?>/gi, '\n'); // br 태그를 개행문자로 sContent = sContent.replace(/<br(\s[^\/]*)?>/gi, '\n'); // br 태그를 개행문자로 sContent = sContent.replace(/<\/p(\s[^\/]*)?>/gi, '\n'); // p 태그를 개행문자로 sContent = sContent.replace(/<\/li(\s[^\/]*)?>/gi, '\n'); // li 태그를 개행문자로 [SMARTEDITORSUS-107]개행 추가 sContent = sContent.replace(/<\/tr(\s[^\/]*)?>/gi, '\n'); // tr 태그를 개행문자로 [SMARTEDITORSUS-107]개행 추가 // 마지막 \n은 로직상 불필요한 linebreak를 제공하므로 제거해준다. nIdx = sContent.lastIndexOf('\n'); if (nIdx > -1 && sContent.substring(nIdx) == '\n') { sContent = sContent.substring(0, nIdx); } sContent = jindo.$S(sContent).stripTags().toString(); sContent = this.unhtmlSpecialChars(sContent); if (aTemp !== null) { // 제거했던sTmpStr를 추가해준다. sContent = aTemp[0] + sContent; } return sContent; }, textToIr : function(sHtml) { if (!sHtml) { return; } var sContent = sHtml, aTemp = null; // applyConverter에서 추가한 sTmpStr를 잠시 제거해준다. sTmpStr도 하나의 string으로 인식하는 경우가 있기 때문. aTemp = sContent.match(new RegExp(this.sRxConverter)); if (aTemp !== null) { sContent = sContent.replace(aTemp[0], ""); } sContent = this.htmlSpecialChars(sContent); sContent = this._addLineBreaker(sContent); if (aTemp !== null) { sContent = aTemp[0] + sContent; } return sContent; }, _addLineBreaker : function(sContent){ if(this.oApp.sLineBreaker === "BR"){ return sContent.replace(/\r?\n/g, "<BR>"); } var oContent = new StringBuffer(), aContent = sContent.split('\n'), // \n을 기준으로 블럭을 나눈다. aContentLng = aContent.length, sTemp = ""; for (var i = 0; i < aContentLng; i++) { sTemp = jindo.$S(aContent[i]).trim().$value(); if (i === aContentLng -1 && sTemp === "") { break; } if (sTemp !== null && sTemp !== "") { oContent.append('<P>'); oContent.append(aContent[i]); oContent.append('</P>'); } else { if (!jindo.$Agent().navigator().ie) { oContent.append('<P><BR></P>'); } else { oContent.append('<P>&nbsp;<\/P>'); } } } return oContent.toString(); }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 시작 */ startAutoResize : function(){ var htOption = { nMinHeight : this.nMinHeight, wfnCallback : jindo.$Fn(this.oApp.checkResizeGripPosition, this).bind() }; //[SMARTEDITORSUS-941][iOS5대응]아이패드의 자동 확장 기능이 동작하지 않을 때 에디터 창보다 긴 내용을 작성하면 에디터를 뚫고 나오는 현상 //원인 : 자동확장 기능이 정지 될 경우 iframe에 스크롤이 생기지 않고, 창을 뚫고 나옴 //해결 : 항상 자동확장 기능이 켜져있도록 변경. 자동 확장 기능 관련한 이벤트 코드도 모바일 사파리에서 예외 처리 if(this.oNavigator.msafari){ htOption.wfnCallback = function(){}; } this.bAutoResize = true; this.AutoResizer = new nhn.husky.AutoResizer(this.elEditingArea, htOption); this.AutoResizer.bind(); }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 종료 */ stopAutoResize : function(){ this.AutoResizer.unbind(); }, getIR : function() { var sIR = this.getRawContents(); if (this.oApp.applyConverter) { sIR = this.oApp.applyConverter(this.sMode + "_TO_IR", sIR, this.oApp.getWYSIWYGDocument()); } return sIR; }, setIR : function(sIR) { var sContent = sIR; if (this.oApp.applyConverter) { sContent = this.oApp.applyConverter("IR_TO_" + this.sMode, sContent, this.oApp.getWYSIWYGDocument()); } this.setRawContents(sContent); }, setRawContents : function(sContent) { if (typeof sContent !== 'undefined') { this.elEditingArea.value = sContent; } }, getRawContents : function() { return this.elEditingArea.value; }, focus : function() { this.elEditingArea.focus(); }, /** * HTML 태그에 해당하는 글자가 먹히지 않도록 바꿔주기 * * 동작) & 를 &amp; 로, < 를 &lt; 로, > 를 &gt; 로 바꿔준다 * * @param {String} sText * @return {String} */ htmlSpecialChars : function(sText) { return sText.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;'); }, /** * htmlSpecialChars 의 반대 기능의 함수 * * 동작) &amp, &lt, &gt, &nbsp 를 각각 &, <, >, 빈칸으로 바꿔준다 * * @param {String} sText * @return {String} */ unhtmlSpecialChars : function(sText) { return sText.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&'); } }); /*[ * REFRESH_WYSIWYG * * (FF전용) WYSIWYG 모드를 비활성화 후 다시 활성화 시킨다. FF에서 WYSIWYG 모드가 일부 비활성화 되는 문제용 * 주의] REFRESH_WYSIWYG후에는 본문의 selection이 깨져서 커서 제일 앞으로 가는 현상이 있음. (stringbookmark로 처리해야함.) * * none * ---------------------------------------------------------------------------]*/ /*[ * ENABLE_WYSIWYG * * 비활성화된 WYSIWYG 편집 영역을 활성화 시킨다. * * none * ---------------------------------------------------------------------------]*/ /*[ * DISABLE_WYSIWYG * * WYSIWYG 편집 영역을 비활성화 시킨다. * * none * ---------------------------------------------------------------------------]*/ /*[ * PASTE_HTML * * HTML을 편집 영역에 삽입한다. * * sHTML string 삽입할 HTML * oPSelection object 붙여 넣기 할 영역, 생략시 현재 커서 위치 * ---------------------------------------------------------------------------]*/ /*[ * RESTORE_IE_SELECTION * * (IE전용) 에디터에서 포커스가 나가는 시점에 기억해둔 포커스를 복구한다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc WYSIWYG 모드를 제공하는 플러그인 */ nhn.husky.SE_EditingArea_WYSIWYG = jindo.$Class({ name : "SE_EditingArea_WYSIWYG", status : nhn.husky.PLUGIN_STATUS.NOT_READY, sMode : "WYSIWYG", iframe : null, doc : null, bStopCheckingBodyHeight : false, bAutoResize : false, // [SMARTEDITORSUS-677] 해당 편집모드의 자동확장 기능 On/Off 여부 nBodyMinHeight : 0, nScrollbarWidth : 0, iLastUndoRecorded : 0, // iMinUndoInterval : 50, _nIFrameReadyCount : 50, bWYSIWYGEnabled : false, $init : function(iframe){ this.iframe = jindo.$(iframe); var oAgent = jindo.$Agent().navigator(); // IE에서 에디터 초기화 시에 임의적으로 iframe에 포커스를 반쯤(IME 입력 안되고 커서만 깜박이는 상태) 주는 현상을 막기 위해서 일단 iframe을 숨겨 뒀다가 CHANGE_EDITING_MODE에서 위지윅 전환 시 보여준다. // 이런 현상이 다양한 요소에 의해서 발생하며 발견된 몇가지 경우는, // - frameset으로 페이지를 구성한 후에 한개의 frame안에 버튼을 두어 에디터로 링크 할 경우 // - iframe과 동일 페이지에 존재하는 text field에 값을 할당 할 경우 if(oAgent.ie){ this.iframe.style.display = "none"; } // IE8 : 찾기/바꾸기에서 글자 일부에 스타일이 적용된 경우 찾기가 안되는 브라우저 버그로 인해 EmulateIE7 파일을 사용 // <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> this.sBlankPageURL = "smart_editor2_inputarea.html"; this.sBlankPageURL_EmulateIE7 = "smart_editor2_inputarea_ie8.html"; this.aAddtionalEmulateIE7 = []; this.htOptions = nhn.husky.SE2M_Configuration.SE_EditingAreaManager; if (this.htOptions) { this.sBlankPageURL = this.htOptions.sBlankPageURL || this.sBlankPageURL; this.sBlankPageURL_EmulateIE7 = this.htOptions.sBlankPageURL_EmulateIE7 || this.sBlankPageURL_EmulateIE7; this.aAddtionalEmulateIE7 = this.htOptions.aAddtionalEmulateIE7 || this.aAddtionalEmulateIE7; } this.aAddtionalEmulateIE7.push(8); // IE8은 Default 사용 this.sIFrameSrc = this.sBlankPageURL; if(oAgent.ie && jindo.$A(this.aAddtionalEmulateIE7).has(oAgent.nativeVersion)) { this.sIFrameSrc = this.sBlankPageURL_EmulateIE7; } var sIFrameSrc = this.sIFrameSrc, iframe = this.iframe, fHandlerSuccess = jindo.$Fn(this.initIframe, this).bind(), fHandlerFail =jindo.$Fn(function(){this.iframe.src = sIFrameSrc;}, this).bind(); if(!oAgent.ie || (oAgent.version >=9 && !!document.addEventListener)){ iframe.addEventListener("load", fHandlerSuccess, false); iframe.addEventListener("error", fHandlerFail, false); }else{ iframe.attachEvent("onload", fHandlerSuccess); iframe.attachEvent("onerror", fHandlerFail); } iframe.src = sIFrameSrc; this.elEditingArea = iframe; }, $BEFORE_MSG_APP_READY : function(){ this.oEditingArea = this.iframe.contentWindow.document; this.oApp.exec("REGISTER_EDITING_AREA", [this]); this.oApp.exec("ADD_APP_PROPERTY", ["getWYSIWYGWindow", jindo.$Fn(this.getWindow, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getWYSIWYGDocument", jindo.$Fn(this.getDocument, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["isWYSIWYGEnabled", jindo.$Fn(this.isWYSIWYGEnabled, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getRawHTMLContents", jindo.$Fn(this.getRawHTMLContents, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["setRawHTMLContents", jindo.$Fn(this.setRawHTMLContents, this).bind()]); if (!!this.isWYSIWYGEnabled()) { this.oApp.exec('ENABLE_WYSIWYG_RULER', []); } this.oApp.registerBrowserEvent(this.getDocument().body, 'paste', 'EVENT_EDITING_AREA_PASTE'); }, $ON_MSG_APP_READY : function(){ if(!this.oApp.hasOwnProperty("saveSnapShot")){ this.$ON_EVENT_EDITING_AREA_MOUSEUP = function(){}; this._recordUndo = function(){}; } // uncomment this line if you wish to use the IE-style cursor in FF // this.getDocument().body.style.cursor = "text"; // Do not update this._oIERange until the document is actually clicked (focus was given by mousedown->mouseup) // Without this, iframe cannot be re-selected(by RESTORE_IE_SELECTION) if the document hasn't been clicked // mousedown on iframe -> focus goes into the iframe doc -> beforedeactivate is fired -> empty selection is saved by the plugin -> empty selection is recovered in RESTORE_IE_SELECTION this._bIERangeReset = true; if(this.oApp.oNavigator.ie){ jindo.$Fn( function(weEvent){ var oSelection = this.iframe.contentWindow.document.selection; if(oSelection && oSelection.type.toLowerCase() === 'control' && weEvent.key().keyCode === 8){ this.oApp.exec("EXECCOMMAND", ['delete', false, false]); weEvent.stop(); } this._bIERangeReset = false; }, this ).attach(this.iframe.contentWindow.document, "keydown"); jindo.$Fn( function(weEvent){ this._oIERange = null; this._bIERangeReset = true; }, this ).attach(this.iframe.contentWindow.document.body, "mousedown"); jindo.$Fn(this._onIEBeforeDeactivate, this).attach(this.iframe.contentWindow.document.body, "beforedeactivate"); jindo.$Fn( function(weEvent){ this._bIERangeReset = false; }, this ).attach(this.iframe.contentWindow.document.body, "mouseup"); }else{ //this.getDocument().execCommand('useCSS', false, false); //this.getDocument().execCommand('styleWithCSS', false, false); //this.document.execCommand("insertBrOnReturn", false, false); } // DTD가 quirks가 아닐 경우 body 높이 100%가 제대로 동작하지 않아서 타임아웃을 돌며 높이를 수동으로 계속 할당 해 줌 // body 높이가 제대로 설정 되지 않을 경우, 보기에는 이상없어 보이나 마우스로 텍스트 선택이 잘 안된다든지 하는 이슈가 있음 this.fnSetBodyHeight = jindo.$Fn(this._setBodyHeight, this).bind(); this.fnCheckBodyChange = jindo.$Fn(this._checkBodyChange, this).bind(); this.fnSetBodyHeight(); this._setScrollbarWidth(); }, /** * 스크롤바의 사이즈 측정하여 설정 */ _setScrollbarWidth : function(){ var oDocument = this.getDocument(), elScrollDiv = oDocument.createElement("div"); elScrollDiv.style.width = "100px"; elScrollDiv.style.height = "100px"; elScrollDiv.style.overflow = "scroll"; elScrollDiv.style.position = "absolute"; elScrollDiv.style.top = "-9999px"; oDocument.body.appendChild(elScrollDiv); this.nScrollbarWidth = elScrollDiv.offsetWidth - elScrollDiv.clientWidth; oDocument.body.removeChild(elScrollDiv); }, /** * [SMARTEDITORSUS-677] 붙여넣기나 내용 입력에 대한 편집영역 자동 확장 처리 */ $AFTER_EVENT_EDITING_AREA_KEYUP : function(oEvent){ if(!this.bAutoResize){ return; } var oKeyInfo = oEvent.key(); if((oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40) || oKeyInfo.alt || oKeyInfo.ctrl || oKeyInfo.keyCode === 16){ return; } this._setAutoResize(); }, /** * [SMARTEDITORSUS-677] 붙여넣기나 내용 입력에 대한 편집영역 자동 확장 처리 */ $AFTER_PASTE_HTML : function(){ if(!this.bAutoResize){ return; } this._setAutoResize(); }, /** * [SMARTEDITORSUS-677] WYSIWYG 편집 영역 자동 확장 처리 시작 */ startAutoResize : function(){ this.oApp.exec("STOP_CHECKING_BODY_HEIGHT"); this.bAutoResize = true; var oBrowser = this.oApp.oNavigator; // [SMARTEDITORSUS-887] [블로그 1단] 자동확장 모드에서 에디터 가로사이즈보다 큰 사진을 추가했을 때 가로스크롤이 안생기는 문제 if(oBrowser.ie && oBrowser.version < 9){ jindo.$Element(this.getDocument().body).css({ "overflow" : "visible" }); // { "overflowX" : "visible", "overflowY" : "hidden" } 으로 설정하면 세로 스크롤 뿐 아니라 가로 스크롤도 보이지 않는 문제가 있어 // { "overflow" : "visible" } 로 처리하고 에디터의 container 사이즈를 늘려 세로 스크롤이 보이지 않도록 처리해야 함 // [한계] 자동 확장 모드에서 내용이 늘어날 때 세로 스크롤이 보였다가 없어지는 문제 }else{ jindo.$Element(this.getDocument().body).css({ "overflowX" : "visible", "overflowY" : "hidden" }); } this._setAutoResize(); this.nCheckBodyInterval = setInterval(this.fnCheckBodyChange, 500); this.oApp.exec("START_FLOAT_TOOLBAR"); // set scroll event }, /** * [SMARTEDITORSUS-677] WYSIWYG 편집 영역 자동 확장 처리 종료 */ stopAutoResize : function(){ this.bAutoResize = false; clearInterval(this.nCheckBodyInterval); this.oApp.exec("STOP_FLOAT_TOOLBAR"); // remove scroll event jindo.$Element(this.getDocument().body).css({ "overflow" : "visible", "overflowY" : "visible" }); this.oApp.exec("START_CHECKING_BODY_HEIGHT"); }, /** * [SMARTEDITORSUS-677] 편집 영역 Body가 변경되었는지 주기적으로 확인 */ _checkBodyChange : function(){ if(!this.bAutoResize){ return; } var nBodyLength = this.getDocument().body.innerHTML.length; if(nBodyLength !== this.nBodyLength){ this.nBodyLength = nBodyLength; this._setAutoResize(); } }, /** * [SMARTEDITORSUS-677] 자동 확장 처리에서 적용할 Resize Body Height를 구함 */ _getResizeHeight : function(){ var elBody = this.getDocument().body, welBody, nBodyHeight, aCopyStyle = ['width', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'lineHeight', 'letterSpacing', 'textTransform', 'wordSpacing'], oCss, i; if(!this.oApp.oNavigator.firefox && !this.oApp.oNavigator.safari){ if(this.oApp.oNavigator.ie && this.oApp.oNavigator.version === 8 && document.documentMode === 8){ jindo.$Element(elBody).css("height", "0px"); } nBodyHeight = parseInt(elBody.scrollHeight, 10); if(nBodyHeight < this.nBodyMinHeight){ nBodyHeight = this.nBodyMinHeight; } return nBodyHeight; } // Firefox && Safari if(!this.elDummy){ this.elDummy = document.createElement('div'); this.elDummy.className = "se2_input_wysiwyg"; this.oApp.elEditingAreaContainer.appendChild(this.elDummy); this.elDummy.style.cssText = 'position:absolute !important; left:-9999px !important; top:-9999px !important; z-index: -9999 !important; overflow: auto !important;'; this.elDummy.style.height = this.nBodyMinHeight + "px"; } welBody = jindo.$Element(elBody); i = aCopyStyle.length; oCss = {}; while(i--){ oCss[aCopyStyle[i]] = welBody.css(aCopyStyle[i]); } if(oCss.lineHeight.indexOf("px") > -1){ oCss.lineHeight = (parseInt(oCss.lineHeight, 10)/parseInt(oCss.fontSize, 10)); } jindo.$Element(this.elDummy).css(oCss); this.elDummy.innerHTML = elBody.innerHTML; nBodyHeight = this.elDummy.scrollHeight; return nBodyHeight; }, /** * [SMARTEDITORSUS-677] WYSIWYG 자동 확장 처리 */ _setAutoResize : function(){ var elBody = this.getDocument().body, welBody = jindo.$Element(elBody), nBodyHeight, nContainerHeight, oCurrentStyle, nStyleSize, bExpand = false, oBrowser = this.oApp.oNavigator; this.nTopBottomMargin = this.nTopBottomMargin || (parseInt(welBody.css("marginTop"), 10) + parseInt(welBody.css("marginBottom"), 10)); this.nBodyMinHeight = this.nBodyMinHeight || (this.oApp.getEditingAreaHeight() - this.nTopBottomMargin); if((oBrowser.ie && oBrowser.nativeVersion >= 9) || oBrowser.chrome){ // 내용이 줄어도 scrollHeight가 줄어들지 않음 welBody.css("height", "0px"); this.iframe.style.height = "0px"; } nBodyHeight = this._getResizeHeight(); if(oBrowser.ie){ // 내용 뒤로 공간이 남아 보일 수 있으나 추가로 Container높이를 더하지 않으면 // 내용 가장 뒤에서 Enter를 하는 경우 아래위로 흔들려 보이는 문제가 발생 if(nBodyHeight > this.nBodyMinHeight){ oCurrentStyle = this.oApp.getCurrentStyle(); nStyleSize = parseInt(oCurrentStyle.fontSize, 10) * oCurrentStyle.lineHeight; if(nStyleSize < this.nTopBottomMargin){ nStyleSize = this.nTopBottomMargin; } nContainerHeight = nBodyHeight + nStyleSize; nContainerHeight += 18; bExpand = true; }else{ nBodyHeight = this.nBodyMinHeight; nContainerHeight = this.nBodyMinHeight + this.nTopBottomMargin; } // }else if(oBrowser.safari){ // -- 사파리에서 내용이 줄어들지 않는 문제가 있어 Firefox 방식으로 변경함 // // [Chrome/Safari] 크롬이나 사파리에서는 Body와 iframe높이서 서로 연관되어 늘어나므로, // // nContainerHeight를 추가로 더하는 경우 setTimeout 시 무한 증식되는 문제가 발생할 수 있음 // nBodyHeight = nBodyHeight > this.nBodyMinHeight ? nBodyHeight - this.nTopBottomMargin : this.nBodyMinHeight; // nContainerHeight = nBodyHeight + this.nTopBottomMargin; }else{ // [FF] nContainerHeight를 추가로 더하였음. setTimeout 시 무한 증식되는 문제가 발생할 수 있음 if(nBodyHeight > this.nBodyMinHeight){ oCurrentStyle = this.oApp.getCurrentStyle(); nStyleSize = parseInt(oCurrentStyle.fontSize, 10) * oCurrentStyle.lineHeight; if(nStyleSize < this.nTopBottomMargin){ nStyleSize = this.nTopBottomMargin; } nContainerHeight = nBodyHeight + nStyleSize; bExpand = true; }else{ nBodyHeight = this.nBodyMinHeight; nContainerHeight = this.nBodyMinHeight + this.nTopBottomMargin; } } if(!oBrowser.firefox){ welBody.css("height", nBodyHeight + "px"); } this.iframe.style.height = nContainerHeight + "px"; // 편집영역 IFRAME의 높이 변경 this.oApp.welEditingAreaContainer.height(nContainerHeight); // 편집영역 IFRAME을 감싸는 DIV 높이 변경 //[SMARTEDITORSUS-941][iOS5대응]아이패드의 자동 확장 기능이 동작하지 않을 때 에디터 창보다 긴 내용을 작성하면 에디터를 뚫고 나오는 현상 //원인 : 자동확장 기능이 정지 될 경우 iframe에 스크롤이 생기지 않고, 창을 뚫고 나옴 //해결 : 항상 자동확장 기능이 켜져있도록 변경. 자동 확장 기능 관련한 이벤트 코드도 모바일 사파리에서 예외 처리 if(!this.oApp.oNavigator.msafari){ this.oApp.checkResizeGripPosition(bExpand); } }, /** * 스크롤 처리를 위해 편집영역 Body의 사이즈를 확인하고 설정함 * 편집영역 자동확장 기능이 Off인 경우에 주기적으로 실행됨 */ _setBodyHeight : function(){ if( this.bStopCheckingBodyHeight ){ // 멈춰야 하는 경우 true, 계속 체크해야 하면 false // 위지윅 모드에서 다른 모드로 변경할 때 "document는 css를 사용 할수 없습니다." 라는 error 가 발생. // 그래서 on_change_mode에서 bStopCheckingBodyHeight 를 true로 변경시켜줘야 함. return; } var elBody = this.getDocument().body, welBody = jindo.$Element(elBody), nMarginTopBottom = parseInt(welBody.css("marginTop"), 10) + parseInt(welBody.css("marginBottom"), 10), nContainerOffset = this.oApp.getEditingAreaHeight(), nMinBodyHeight = nContainerOffset - nMarginTopBottom, nBodyHeight = welBody.height(), nScrollHeight, nNewBodyHeight; this.nTopBottomMargin = nMarginTopBottom; if(nBodyHeight === 0){ // [SMARTEDITORSUS-144] height 가 0 이고 내용이 없으면 크롬10 에서 캐럿이 보이지 않음 welBody.css("height", nMinBodyHeight + "px"); setTimeout(this.fnSetBodyHeight, 500); return; } welBody.css("height", "0px"); // [SMARTEDITORSUS-257] IE9, 크롬에서 내용을 삭제해도 스크롤이 남아있는 문제 처리 // body 에 내용이 없어져도 scrollHeight 가 줄어들지 않아 height 를 강제로 0 으로 설정 nScrollHeight = parseInt(elBody.scrollHeight, 10); nNewBodyHeight = (nScrollHeight > nContainerOffset ? nScrollHeight - nMarginTopBottom : nMinBodyHeight); // nMarginTopBottom 을 빼지 않으면 스크롤이 계속 늘어나는 경우가 있음 (참고 [BLOGSUS-17421]) if(this._isHorizontalScrollbarVisible()){ nNewBodyHeight -= this.nScrollbarWidth; } welBody.css("height", nNewBodyHeight + "px"); setTimeout(this.fnSetBodyHeight, 500); }, /** * 가로 스크롤바 생성 확인 */ _isHorizontalScrollbarVisible : function(){ var oDocument = this.getDocument(); if(oDocument.documentElement.clientWidth < oDocument.documentElement.scrollWidth){ //oDocument.body.clientWidth < oDocument.body.scrollWidth || return true; } return false; }, /** * body의 offset체크를 멈추게 하는 함수. */ $ON_STOP_CHECKING_BODY_HEIGHT :function(){ if(!this.bStopCheckingBodyHeight){ this.bStopCheckingBodyHeight = true; } }, /** * body의 offset체크를 계속 진행. */ $ON_START_CHECKING_BODY_HEIGHT :function(){ if(this.bStopCheckingBodyHeight){ this.bStopCheckingBodyHeight = false; this.fnSetBodyHeight(); } }, $ON_IE_CHECK_EXCEPTION_FOR_SELECTION_PRESERVATION : function(){ // 현재 선택된 앨리먼트가 iframe이라면, 셀렉션을 따로 기억 해 두지 않아도 유지 됨으로 RESTORE_IE_SELECTION을 타지 않도록 this._oIERange을 지워준다. // (필요 없을 뿐더러 저장 시 문제 발생) var oSelection = this.getDocument().selection; if(oSelection && oSelection.type === "Control"){ this._oIERange = null; } /* // [SMARTEDITORSUS-978] HuskyRange.js 의 [SMARTEDITORSUS-888] 이슈 수정과 관련 var tmpSelection = this.getDocument().selection, oRange, elNode; if(tmpSelection.type === "Control"){ oRange = tmpSelection.createRange(); elNode = oRange.item(0); if(elNode && elNode.tagName === "IFRAME"){ this._oIERange = null; } } */ }, _onIEBeforeDeactivate : function(wev){ var tmpSelection, tmpRange; this.oApp.delayedExec("IE_CHECK_EXCEPTION_FOR_SELECTION_PRESERVATION", [], 0); if(this._oIERange){ return; } // without this, cursor won't make it inside a table. // mousedown(_oIERange gets reset) -> beforedeactivate(gets fired for table) -> RESTORE_IE_SELECTION if(this._bIERangeReset){ return; } this._oIERange = this.oApp.getSelection().cloneRange(); /* [SMARTEDITORSUS-978] HuskyRange.js 의 [SMARTEDITORSUS-888] 이슈 수정과 관련 tmpSelection = this.getDocument().selection; tmpRange = tmpSelection.createRange(); // Control range does not have parentElement if(tmpRange.parentElement && tmpRange.parentElement() && tmpRange.parentElement().tagName === "INPUT"){ this._oIERange = this._oPrevIERange; }else{ this._oIERange = tmpRange; } */ }, $ON_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ if(sMode === this.sMode){ // [SMARTEDITORSUS-1213][IE9, 10] 사진 삭제 후 zindex 1000인 div가 잔존하는데, 그 위로 썸네일 drag를 시도하다 보니 drop이 불가능. var htBrowser = jindo.$Agent().navigator(); if(htBrowser.ie && htBrowser.nativeVersion > 8){ var elFirstChild = jindo.$$.getSingle("DIV.husky_seditor_editing_area_container").childNodes[0]; if((elFirstChild.tagName == "DIV") && (elFirstChild.style.zIndex == 1000)){ elFirstChild.parentNode.removeChild(elFirstChild); } } // --[SMARTEDITORSUS-1213] this.iframe.style.display = "block"; this.oApp.exec("REFRESH_WYSIWYG", []); this.oApp.exec("SET_EDITING_WINDOW", [this.getWindow()]); this.oApp.exec("START_CHECKING_BODY_HEIGHT"); }else{ this.iframe.style.display = "none"; this.oApp.exec("STOP_CHECKING_BODY_HEIGHT"); } }, $AFTER_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ this._oIERange = null; }, $ON_REFRESH_WYSIWYG : function(){ if(!jindo.$Agent().navigator().firefox){ return; } this._disableWYSIWYG(); this._enableWYSIWYG(); }, $ON_ENABLE_WYSIWYG : function(){ this._enableWYSIWYG(); }, $ON_DISABLE_WYSIWYG : function(){ this._disableWYSIWYG(); }, $ON_IE_HIDE_CURSOR : function(){ if(!this.oApp.oNavigator.ie){ return; } this._onIEBeforeDeactivate(); // De-select the default selection. // [SMARTEDITORSUS-978] IE9에서 removeAllRanges로 제거되지 않아 // 이전 IE와 동일하게 empty 방식을 사용하도록 하였으나 doc.selection.type이 None인 경우 에러 // Range를 재설정 해주어 selectNone 으로 처리되도록 예외처리 var oSelection = this.oApp.getWYSIWYGDocument().selection; if(oSelection && oSelection.createRange){ try{ oSelection.empty(); }catch(e){ // [SMARTEDITORSUS-1003] IE9 / doc.selection.type === "None" oSelection = this.oApp.getSelection(); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } }else{ this.oApp.getEmptySelection().oBrowserSelection.selectNone(); } }, $AFTER_SHOW_ACTIVE_LAYER : function(){ this.oApp.exec("IE_HIDE_CURSOR",[]); this.bActiveLayerShown = true; }, $BEFORE_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ this._bKeyDown = true; }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ if(this.oApp.getEditingMode() !== this.sMode){ return; } var oKeyInfo = oEvent.key(); if(this.oApp.oNavigator.ie){ //var oKeyInfo = oEvent.key(); switch(oKeyInfo.keyCode){ case 33: this._pageUp(oEvent); break; case 34: this._pageDown(oEvent); break; case 8: // [SMARTEDITORSUS-495][SMARTEDITORSUS-548] IE에서 표가 삭제되지 않는 문제 this._backspace(oEvent); break; default: } }else if(this.oApp.oNavigator.firefox){ // [SMARTEDITORSUS-151] FF 에서 표가 삭제되지 않는 문제 if(oKeyInfo.keyCode === 8){ // backspace this._backspace(oEvent); } } this._recordUndo(oKeyInfo); // 첫번째 Delete 키 입력 전의 상태가 저장되도록 KEYDOWN 시점에 저장 }, /** * [SMARTEDITORSUS-1575] 커서홀더 제거 * [SMARTEDITORSUS-151][SMARTEDITORSUS-495][SMARTEDITORSUS-548] IE와 FF에서 표 삭제 */ _backspace : function(weEvent){ var oSelection = this.oApp.getSelection(), preNode = null; if(!oSelection.collapsed){ return; } preNode = oSelection.getNodeAroundRange(true, false); if(preNode && preNode.nodeType === 3){ if(/^[\n]*$/.test(preNode.nodeValue)){ preNode = preNode.previousSibling; }else if(preNode.nodeValue === "\u200B" || preNode.nodeValue === "\uFEFF"){ // [SMARTEDITORSUS-1575] 공백대신 커서홀더 삽입된 상태라서 빈라인에서 백스페이스를 두번 쳐야 윗쪽라인으로 올라가기 때문에 한번 쳐서 올라갈 수 있도록 커서홀더 제거 preNode.nodeValue = ""; } } if(!!preNode && preNode.nodeType === 1 && preNode.tagName === "TABLE"){ jindo.$Element(preNode).leave(); weEvent.stop(jindo.$Event.CANCEL_ALL); } }, $BEFORE_EVENT_EDITING_AREA_KEYUP : function(oEvent){ // IE(6) sometimes fires keyup events when it should not and when it happens the keyup event gets fired without a keydown event if(!this._bKeyDown){ return false; } this._bKeyDown = false; }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(oEvent){ this.oApp.saveSnapShot(); }, $BEFORE_PASTE_HTML : function(){ if(this.oApp.getEditingMode() !== this.sMode){ this.oApp.exec("CHANGE_EDITING_MODE", [this.sMode]); } }, $ON_PASTE_HTML : function(sHTML, oPSelection, bNoUndo){ var oSelection, oNavigator, sTmpBookmark, oStartContainer, aImgChild, elLastImg, elChild, elNextChild; if(this.oApp.getEditingMode() !== this.sMode){ return; } if(!bNoUndo){ this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["PASTE HTML"]); } oNavigator = jindo.$Agent().navigator(); oSelection = oPSelection || this.oApp.getSelection(); //[SMARTEDITORSUS-888] 브라우저 별 테스트 후 아래 부분이 불필요하여 제거함 // - [SMARTEDITORSUS-387] IE9 표준모드에서 엘리먼트 뒤에 어떠한 엘리먼트도 없는 상태에서 커서가 안들어가는 현상. // if(oNavigator.ie && oNavigator.nativeVersion >= 9 && document.documentMode >= 9){ // sHTML = sHTML + unescape("%uFEFF"); // } if(oNavigator.ie && oNavigator.nativeVersion == 8 && document.documentMode == 8){ sHTML = sHTML + unescape("%uFEFF"); } oSelection.pasteHTML(sHTML); // every browser except for IE may modify the innerHTML when it is inserted if(!oNavigator.ie){ sTmpBookmark = oSelection.placeStringBookmark(); this.oApp.getWYSIWYGDocument().body.innerHTML = this.oApp.getWYSIWYGDocument().body.innerHTML; oSelection.moveToBookmark(sTmpBookmark); oSelection.collapseToEnd(); oSelection.select(); oSelection.removeStringBookmark(sTmpBookmark); // [SMARTEDITORSUS-56] 사진을 연속으로 첨부할 경우 연이어 삽입되지 않는 현상으로 이슈를 발견하게 되었습니다. // 그러나 이는 비단 '다수의 사진을 첨부할 경우'에만 발생하는 문제는 아니었고, // 원인 확인 결과 컨텐츠 삽입 후 기존 Bookmark 삭제 시 갱신된 Selection 이 제대로 반영되지 않는 점이 있었습니다. // 이에, Selection 을 갱신하는 코드를 추가하였습니다. oSelection = this.oApp.getSelection(); //[SMARTEDITORSUS-831] 비IE 계열 브라우저에서 스크롤바가 생기게 문자입력 후 엔터 클릭하지 않은 상태에서 //이미지 하나 삽입 시 이미지에 포커싱이 놓이지 않습니다. //원인 : parameter로 넘겨 받은 oPSelecion에 변경된 값을 복사해 주지 않아서 발생 //해결 : parameter로 넘겨 받은 oPSelecion에 변경된 값을 복사해준다 // call by reference로 넘겨 받았으므로 직접 객체 안의 인자 값을 바꿔주는 setRange 함수 사용 if(!!oPSelection){ oPSelection.setRange(oSelection); } }else{ // [SMARTEDITORSUS-428] [IE9.0] IE9에서 포스트 쓰기에 접근하여 맨위에 임의의 글감 첨부 후 엔터를 클릭 시 글감이 사라짐 // PASTE_HTML 후에 IFRAME 부분이 선택된 상태여서 Enter 시 내용이 제거되어 발생한 문제 oSelection.collapseToEnd(); oSelection.select(); this._oIERange = null; this._bIERangeReset = false; } // [SMARTEDITORSUS-639] 사진 첨부 후 이미지 뒤의 공백으로 인해 스크롤이 생기는 문제 if(sHTML.indexOf("<img") > -1){ oStartContainer = oSelection.startContainer; if(oStartContainer.nodeType === 1 && oStartContainer.tagName === "P"){ aImgChild = jindo.$Element(oStartContainer).child(function(v){ return (v.$value().nodeType === 1 && v.$value().tagName === "IMG"); }, 1); if(aImgChild.length > 0){ elLastImg = aImgChild[aImgChild.length - 1].$value(); elChild = elLastImg.nextSibling; while(elChild){ elNextChild = elChild.nextSibling; if (elChild.nodeType === 3 && (elChild.nodeValue === "&nbsp;" || elChild.nodeValue === unescape("%u00A0"))) { oStartContainer.removeChild(elChild); } elChild = elNextChild; } } } } if(!bNoUndo){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["PASTE HTML"]); } }, /** * [SMARTEDITORSUS-344]사진/동영상/지도 연속첨부시 포커싱 개선이슈로 추가되 함수. */ $ON_FOCUS_N_CURSOR : function (bEndCursor, sId){ var el, oSelection; if(sId && ( el = jindo.$(sId, this.getDocument()) )){ // ID가 지정된 경우, 무조건 해당 부분으로 커서 이동 clearTimeout(this._nTimerFocus); // 연속 삽입될 경우, 미완료 타이머는 취소한다. this._nTimerFocus = setTimeout(jindo.$Fn(function(el){ this._scrollIntoView(el); this.oApp.exec("FOCUS"); }, this).bind(el), 300); return; } oSelection = this.oApp.getSelection(); if(!oSelection.collapsed){ // select 영역이 있는 경우 if(bEndCursor){ oSelection.collapseToEnd(); } else { oSelection.collapseToStart(); } oSelection.select(); }else if(bEndCursor){ // select 영역이 없는 상태에서 bEndCursor 이면 body 맨 뒤로 이동시킨다. this.oApp.exec("FOCUS"); el = this.getDocument().body; oSelection.selectNode(el); oSelection.collapseToEnd(); oSelection.select(); this._scrollIntoView(el); }else{ // select 영역이 없는 상태라면 focus만 준다. this.oApp.exec("FOCUS"); } }, /* * 엘리먼트의 top, bottom 값을 반환 */ _getElementVerticalPosition : function(el){ var nTop = 0, elParent = el, htPos = {nTop : 0, nBottom : 0}; if(!el){ return htPos; } while(elParent) { nTop += elParent.offsetTop; elParent = elParent.offsetParent; } htPos.nTop = nTop; htPos.nBottom = nTop + jindo.$Element(el).height(); return htPos; }, /* * Window에서 현재 보여지는 영역의 top, bottom 값을 반환 */ _getVisibleVerticalPosition : function(){ var oWindow, oDocument, nVisibleHeight, htPos = {nTop : 0, nBottom : 0}; oWindow = this.getWindow(); oDocument = this.getDocument(); nVisibleHeight = oWindow.innerHeight ? oWindow.innerHeight : oDocument.documentElement.clientHeight || oDocument.body.clientHeight; htPos.nTop = oWindow.pageYOffset || oDocument.documentElement.scrollTop; htPos.nBottom = htPos.nTop + nVisibleHeight; return htPos; }, /* * 엘리먼트가 WYSIWYG Window의 Visible 부분에서 완전히 보이는 상태인지 확인 (일부만 보이면 false) */ _isElementVisible : function(htElementPos, htVisiblePos){ return (htElementPos.nTop >= htVisiblePos.nTop && htElementPos.nBottom <= htVisiblePos.nBottom); }, /* * [SMARTEDITORSUS-824] [SMARTEDITORSUS-828] 자동 스크롤 처리 */ _scrollIntoView : function(el){ var htElementPos = this._getElementVerticalPosition(el), htVisiblePos = this._getVisibleVerticalPosition(), nScroll = 0; if(this._isElementVisible(htElementPos, htVisiblePos)){ return; } if((nScroll = htElementPos.nBottom - htVisiblePos.nBottom) > 0){ this.getWindow().scrollTo(0, htVisiblePos.nTop + nScroll); // Scroll Down return; } this.getWindow().scrollTo(0, htElementPos.nTop); // Scroll Up }, $BEFORE_MSG_EDITING_AREA_RESIZE_STARTED : function(){ // FF에서 Height조정 시에 본문의 _fitElementInEditingArea()함수 부분에서 selection이 깨지는 현상을 잡기 위해서 // StringBookmark를 사용해서 위치를 저장해둠. (step1) if(!jindo.$Agent().navigator().ie){ var oSelection = null; oSelection = this.oApp.getSelection(); this.sBM = oSelection.placeStringBookmark(); } }, $AFTER_MSG_EDITING_AREA_RESIZE_ENDED : function(FnMouseDown, FnMouseMove, FnMouseUp){ if(this.oApp.getEditingMode() !== this.sMode){ return; } this.oApp.exec("REFRESH_WYSIWYG", []); // bts.nhncorp.com/nhnbts/browse/COM-1042 // $BEFORE_MSG_EDITING_AREA_RESIZE_STARTED에서 저장한 StringBookmark를 셋팅해주고 삭제함.(step2) if(!jindo.$Agent().navigator().ie){ var oSelection = this.oApp.getEmptySelection(); oSelection.moveToBookmark(this.sBM); oSelection.select(); oSelection.removeStringBookmark(this.sBM); } }, $ON_CLEAR_IE_BACKUP_SELECTION : function(){ this._oIERange = null; }, $ON_RESTORE_IE_SELECTION : function(){ if(this._oIERange){ // changing the visibility of the iframe can cause an exception try{ this._oIERange.select(); this._oPrevIERange = this._oIERange; this._oIERange = null; }catch(e){} } }, /** * EVENT_EDITING_AREA_PASTE 의 ON 메시지 핸들러 * 위지윅 모드에서 에디터 본문의 paste 이벤트에 대한 메시지를 처리한다. * paste 시에 내용이 붙여진 본문의 내용을 바로 가져올 수 없어 delay 를 준다. */ $ON_EVENT_EDITING_AREA_PASTE : function(oEvent){ this.oApp.delayedExec('EVENT_EDITING_AREA_PASTE_DELAY', [oEvent], 0); }, $ON_EVENT_EDITING_AREA_PASTE_DELAY : function(weEvent) { this._replaceBlankToNbsp(weEvent.element); }, // [SMARTEDITORSUS-855] IE에서 특정 블로그 글을 복사하여 붙여넣기 했을 때 개행이 제거되는 문제 _replaceBlankToNbsp : function(el){ var oNavigator = this.oApp.oNavigator; if(!oNavigator.ie){ return; } if(oNavigator.nativeVersion !== 9 || document.documentMode !== 7) { // IE9 호환모드에서만 발생 return; } if(el.nodeType !== 1){ return; } if(el.tagName === "BR"){ return; } var aEl = jindo.$$("p:empty()", this.oApp.getWYSIWYGDocument().body, { oneTimeOffCache:true }); jindo.$A(aEl).forEach(function(value, index, array) { value.innerHTML = "&nbsp;"; }); }, _pageUp : function(we){ var nEditorHeight = this._getEditorHeight(), htPos = jindo.$Document(this.oApp.getWYSIWYGDocument()).scrollPosition(), nNewTop; if(htPos.top <= nEditorHeight){ nNewTop = 0; }else{ nNewTop = htPos.top - nEditorHeight; } this.oApp.getWYSIWYGWindow().scrollTo(0, nNewTop); we.stop(); }, _pageDown : function(we){ var nEditorHeight = this._getEditorHeight(), htPos = jindo.$Document(this.oApp.getWYSIWYGDocument()).scrollPosition(), nBodyHeight = this._getBodyHeight(), nNewTop; if(htPos.top+nEditorHeight >= nBodyHeight){ nNewTop = nBodyHeight - nEditorHeight; }else{ nNewTop = htPos.top + nEditorHeight; } this.oApp.getWYSIWYGWindow().scrollTo(0, nNewTop); we.stop(); }, _getEditorHeight : function(){ return this.oApp.elEditingAreaContainer.offsetHeight - this.nTopBottomMargin; }, _getBodyHeight : function(){ return parseInt(this.getDocument().body.scrollHeight, 10); }, initIframe : function(){ try { if (!this.iframe.contentWindow.document || !this.iframe.contentWindow.document.body || this.iframe.contentWindow.document.location.href === 'about:blank'){ throw new Error('Access denied'); } var sCSSBaseURI = (!!nhn.husky.SE2M_Configuration.SE2M_CSSLoader && nhn.husky.SE2M_Configuration.SE2M_CSSLoader.sCSSBaseURI) ? nhn.husky.SE2M_Configuration.SE2M_CSSLoader.sCSSBaseURI : ""; if(!!nhn.husky.SE2M_Configuration.SE_EditingAreaManager.sCSSBaseURI){ sCSSBaseURI = nhn.husky.SE2M_Configuration.SE_EditingAreaManager.sCSSBaseURI; } // add link tag if (sCSSBaseURI){ var doc = this.getDocument(); var headNode = doc.getElementsByTagName("head")[0]; var linkNode = doc.createElement('link'); linkNode.type = 'text/css'; linkNode.rel = 'stylesheet'; linkNode.href = sCSSBaseURI + '/smart_editor2_in.css'; headNode.appendChild(linkNode); } this._enableWYSIWYG(); this.status = nhn.husky.PLUGIN_STATUS.READY; } catch(e) { if(this._nIFrameReadyCount-- > 0){ setTimeout(jindo.$Fn(this.initIframe, this).bind(), 100); }else{ throw("iframe for WYSIWYG editing mode can't be initialized. Please check if the iframe document exists and is also accessable(cross-domain issues). "); } } }, getIR : function(){ var sContent = this.iframe.contentWindow.document.body.innerHTML, sIR; if(this.oApp.applyConverter){ sIR = this.oApp.applyConverter(this.sMode+"_TO_IR", sContent, this.oApp.getWYSIWYGDocument()); }else{ sIR = sContent; } return sIR; }, setIR : function(sIR){ // [SMARTEDITORSUS-875] HTML 모드의 beautify에서 추가된 공백을 다시 제거 //sIR = sIR.replace(/(>)([\n\r\t\s]*)([^<]?)/g, "$1$3").replace(/([\n\r\t\s]*)(<)/g, "$2") // --[SMARTEDITORSUS-875] var sContent, oNavigator = this.oApp.oNavigator, bUnderIE11 = oNavigator.ie && document.documentMode < 11, // IE11미만 sCursorHolder = bUnderIE11 ? "" : "<br>"; if(this.oApp.applyConverter){ sContent = this.oApp.applyConverter("IR_TO_"+this.sMode, sIR, this.oApp.getWYSIWYGDocument()); }else{ sContent = sIR; } // [SMARTEDITORSUS-1279] [IE9/10] pre 태그 아래에 \n이 포함되면 개행이 되지 않는 이슈 /*if(oNavigator.ie && oNavigator.nativeVersion >= 9 && document.documentMode >= 9){ // [SMARTEDITORSUS-704] \r\n이 있는 경우 IE9 표준모드에서 정렬 시 브라우저가 <p>를 추가하는 문제 sContent = sContent.replace(/[\r\n]/g,""); }*/ this.iframe.contentWindow.document.body.innerHTML = sContent; // 편집내용이 없는 경우 if((this.iframe.contentWindow.document.body.innerHTML).replace(/[\r\n\t\s]*/,"") === ""){ if(this.oApp.sLineBreaker !== "BR"){ sCursorHolder = "<p>" + sCursorHolder + "</p>"; } this.iframe.contentWindow.document.body.innerHTML = sCursorHolder; } // [COM-1142] IE의 경우 <p>&nbsp;</p> 를 <p></p> 로 변환 // [SMARTEDITORSUS-1623] IE11은 <p></p>로 변환하면 라인이 붙어버리기 때문에 IE10만 적용하도록 수정 if(bUnderIE11 && this.oApp.getEditingMode() === this.sMode){ var pNodes = this.oApp.getWYSIWYGDocument().body.getElementsByTagName("P"); for(var i=0, nMax = pNodes.length; i < nMax; i++){ if(pNodes[i].childNodes.length === 1 && pNodes[i].innerHTML === "&nbsp;"){ pNodes[i].innerHTML = ''; } } } }, getRawContents : function(){ return this.iframe.contentWindow.document.body.innerHTML; }, getRawHTMLContents : function(){ return this.getRawContents(); }, setRawHTMLContents : function(sContents){ this.iframe.contentWindow.document.body.innerHTML = sContents; }, getWindow : function(){ return this.iframe.contentWindow; }, getDocument : function(){ return this.iframe.contentWindow.document; }, focus : function(){ //this.getWindow().focus(); this.getDocument().body.focus(); this.oApp.exec("RESTORE_IE_SELECTION", []); }, _recordUndo : function(oKeyInfo){ /** * 229: Korean/Eng * 16: shift * 33,34: page up/down * 35,36: end/home * 37,38,39,40: left, up, right, down * 32: space * 46: delete * 8: bksp */ if(oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40){ // record snapshot this.oApp.saveSnapShot(); return; } if(oKeyInfo.alt || oKeyInfo.ctrl || oKeyInfo.keyCode === 16){ return; } if(this.oApp.getLastKey() === oKeyInfo.keyCode){ return; } this.oApp.setLastKey(oKeyInfo.keyCode); // && oKeyInfo.keyCode != 32 // 속도 문제로 인하여 Space 는 제외함 if(!oKeyInfo.enter && oKeyInfo.keyCode !== 46 && oKeyInfo.keyCode !== 8){ return; } this.oApp.exec("RECORD_UNDO_ACTION", ["KEYPRESS(" + oKeyInfo.keyCode + ")", {bMustBlockContainer:true}]); }, _enableWYSIWYG : function(){ //if (this.iframe.contentWindow.document.body.hasOwnProperty("contentEditable")){ if (this.iframe.contentWindow.document.body.contentEditable !== null) { this.iframe.contentWindow.document.body.contentEditable = true; } else { this.iframe.contentWindow.document.designMode = "on"; } this.bWYSIWYGEnabled = true; if(jindo.$Agent().navigator().firefox){ setTimeout(jindo.$Fn(function(){ //enableInlineTableEditing : Enables or disables the table row and column insertion and deletion controls. this.iframe.contentWindow.document.execCommand('enableInlineTableEditing', false, false); }, this).bind(), 0); } }, _disableWYSIWYG : function(){ //if (this.iframe.contentWindow.document.body.hasOwnProperty("contentEditable")){ if (this.iframe.contentWindow.document.body.contentEditable !== null){ this.iframe.contentWindow.document.body.contentEditable = false; } else { this.iframe.contentWindow.document.designMode = "off"; } this.bWYSIWYGEnabled = false; }, isWYSIWYGEnabled : function(){ return this.bWYSIWYGEnabled; } }); //} //{ /** * @pluginDesc WYSIWYG 영역에 붙여넣어지는 외부 컨텐츠를 정제하는 플러그인 */ nhn.husky.SE_PasteHandler = jindo.$Class({ name : "SE_PasteHandler", $init : function(sParagraphContainer){ // 문단 단위 this.sParagraphContainer = sParagraphContainer || "P"; /** * 본문에 붙여넣어진 컨텐츠 중, * 이 플러그인에서 정제한 컨텐츠로 치환할 대상 태그 이름의 목록 * */ this.aConversionTarget = ["TABLE"]; this.htBrowser = jindo.$Agent().navigator(); }, $ON_MSG_APP_READY : function(){ if(!this.htBrowser.safari || (this.htBrowser.safari && this.htBrowser.version >= 6)){ this.elBody = this.oApp.getWYSIWYGDocument().body; this.wfnPasteHandler = jindo.$Fn(this._handlePaste, this); this.wfnPasteHandler.attach(this.elBody, "paste"); // 붙여넣기 작업 공간 생성을 위한 할당 this.elEditingAreaContainer = jindo.$$.getSingle("DIV.husky_seditor_editing_area_container", null, {oneTimeOffCache : true}); /** * [SMARTEDITORSUS-1676] * [IE 10-] IE 11은 beforepaste 이벤트 핸들러를 등록하면 * beforepaste 핸들러가 두 번 호출되는 문제가 있음 * */ if(this.htBrowser.ie && this.htBrowser.nativeVersion <= 10 && this.htBrowser.version <= 10){ this.wfnBeforePasteHandler = jindo.$Fn(this._handleBeforePaste, this); this.wfnBeforePasteHandler.attach(this.elBody, "beforePaste"); } // --[SMARTEDITORSUS-1676] } }, /** * [SMARTEDITORSUS-1676] * [IE 10-] 컨텐츠를 붙여넣는 것은 브라우저 고유의 권한인데, * 붙여넣기 전 선택한 영역이 없을 때 * HuskyRange 북마크를 paste 이벤트에서 삽입하면 * 붙여넣어질 때 이 북마크가 잠식되는 현상이 있다. * * 따라서 beforepaste 이벤트에 HuskyRange 북마크를 삽입한다. * */ _handleBeforePaste : function(){ var oSelection = this.oApp.getSelection(); // 우선 선택된 영역이 있다면 선택된 영역 안의 컨텐츠를 지움 if(!oSelection.collapsed){ oSelection.deleteContents(); } this._sBM_IE = oSelection.placeStringBookmark(); var elEndBookmark = oSelection.getStringBookmark(this._sBM_IE, true); /** * 붙여넣을 때 레이아웃 상에서 공간을 차지하고 있어야 * 컨텐츠가 의도한 위치에 붙여넣어지는데, * * HuskyRange에서 북마크 용도로 삽입하는 빈 <span>으로는 이를 충족할 수 없다. * * 시작 북마크의 뒤와, 끝 북마크의 앞에 * zero-width space 문자인 \u200b를 담고 있는 * 텍스트 노드를 삽입해 둔다. * */ var emptyTextNode = document.createTextNode(""); this.zwspStart = emptyTextNode.cloneNode(true); this.zwspStart.nodeValue = "\u200b"; this.zwspEnd = this.zwspStart.cloneNode(true); elEndBookmark.parentNode.insertBefore(this.zwspEnd, elEndBookmark); elEndBookmark.parentNode.insertBefore(this.zwspStart, this.zwspEnd); /** * oSelection.select()로 목표 위치에 커서를 위치시킨다. * * <시작 북마크 /><\u200b>[목표 커서 위치]<\u200b><끝 북마크 /> * */ oSelection.setEndBefore(this.zwspEnd); oSelection.collapseToEnd(); oSelection.select(); }, _handlePaste : function(we){ if(this.htBrowser.chrome || (this.htBrowser.safari && this.htBrowser.version >= 6)){ /** * [Chrome, Safari6+] clipboard에서 넘어온 style 정의를 저장해 둔 뒤, * 특정 열린 태그에 style을 적용해야 할 경우 활용한다. * * MS Excel 2010 기준으로 * <td>에 담긴 class 명을 획득한 뒤, * 저장해 둔 style에서 매칭하는 값이 있으면 * style을 해당 태그에 적용한다. * * [IE] Text 형태로만 값을 가져올 수 있기 때문에 style 정의 저장 불가 * */ var sClipboardData = we._event.clipboardData.getData("text/html"); var elTmp = document.createElement("DIV"); elTmp.innerHTML = sClipboardData; var elStyle = jindo.$$.getSingle("style", elTmp, {oneTimeOffCache : true}); if(elStyle){ var sStyleFromClipboard = elStyle.innerHTML; // style="" 내부에 삽입되는 경우, 조화를 이루어야 하기 때문에 쌍따옴표를 따옴표로 치환 sStyleFromClipboard = sStyleFromClipboard.replace(/"/g, "'"); this._sStyleFromClipboard = sStyleFromClipboard; } } this._preparePaste(); // 브라우저의 고유 붙여넣기 동작으로 컨텐츠가 본문 영역에 붙여넣어진다. setTimeout(jindo.$Fn(function(){ // [SMARTEDITORSUS-1676] /** * 컨텐츠가 붙여넣어지는 과정에서 * 컨텐츠의 앞 부분 텍스트 일부는 * 앞쪽 zero-width space 텍스트 노드에 병합되는 경우가 있다. * * 따라서 이 텍스트 노드 전체를 들어내는 것은 어렵고, * 시작 부분에 남아 있는 zero-width space 문자만 제거할 수밖에 없다. * */ var rxZwspStart = new RegExp("^[\u200b]"); if(!!this.zwspStart && !!this.zwspStart.nodeValue){ this.zwspStart.nodeValue = this.zwspStart.nodeValue.replace(rxZwspStart, ""); /** * 제거 후 빈 값이라면, 인위적으로 삽입해 준 뒤쪽 zwsp 텍스트 노드를 유지할 필요가 없다. * * [Chrome, Safari 6+] 두 번째 조건식이 필요하다. * 붙여넣어지는 컨텐츠가 line-height 속성을 가진 span 태그인 경우, * this.zwspEnd.parentNode가 사라지는 문제가 있다. * 이와는 직접적으로 관련되어 있지 않으나, * Husky 끝 북마크에 이 line-height 속성이 붙는 문제도 있다. * */ if(this.zwspStart.nodeValue == "" && !!this.zwspStart.paretNode){ this.zwspStart.parentNode.removeChild(this.zwspStart); } } /** * 뒤쪽 zero-width space가 포함된 텍스트 노드 마지막의 * zero-width space 문자를 제거한다. * */ var rxZwspEnd = new RegExp("[\u200b]$"); if(!!this.zwspEnd && !!this.zwspEnd.nodeValue){ this.zwspEnd.nodeValue = this.zwspEnd.nodeValue.replace(rxZwspEnd, ""); /** * 제거 후 빈 값이라면, 인위적으로 삽입해 준 뒤쪽 zwsp 텍스트 노드를 유지할 필요가 없다. * * [Chrome, Safari 6+] 두 번째 조건식이 필요하다. * 붙여넣어지는 컨텐츠가 line-height 속성을 가진 span 태그인 경우, * this.zwspEnd.parentNode가 사라지는 문제가 있다. * 이와는 직접적으로 관련되어 있지 않으나, * Husky 끝 북마크에 이 line-height 속성이 붙는 문제도 있다. * */ if(this.zwspEnd.nodeValue == "" && !!this.zwspEnd.parentNode){ this.zwspEnd.parentNode.removeChild(this.zwspEnd); } } // [SMARTEDITORSUS-1661] try{ this._processPaste(); }catch(e){ // [SMARTEDITORSUS-1673] [SMARTEDITORSUS-1661]의 복원 기능을 제거 // JEagleEye 객체가 존재하면 오류 전송(BLOG) if(typeof(JEagleEyeClient) != "undefined"){ var line = e.lineNumber; if(!line){ line = 0; } var el = "hp_SE_PasteHandler.js/_handlePaste"; if(el){ var tmp = "http://blog.naver.com/"; tmp += el; el = tmp; } JEagleEyeClient.sendError(e, el, line); } // --[SMARTEDITORSUS-1661][SMARTEDITORSUS-1673] } // 북마크 제거 // [SMARTEDITORSUS-1687] var oSelection = this.oApp.getSelection(); this._moveToStringBookmark(oSelection); oSelection.collapseToEnd(); oSelection.select(); // --[SMARTEDITORSUS-1687] this._removeStringBookmark(oSelection); }, this).bind(), 0); }, /** * 붙여넣어지는 외부 프로그램의 컨텐츠를 조작하기 위한 준비를 한다. * */ _preparePaste : function(){ this._saveOriginalContents(); }, /** * 본문 영역의 원문을 저장해 둔다. * */ _saveOriginalContents : function(){ var oSelection = this.oApp.getSelection(); // 우선 선택된 영역이 있다면 내부 컨텐츠를 지움 if(!oSelection.isCollapsed){ oSelection.deleteContents(); } // [SMARTEDITORSUS-1676] if(!this._sBM_IE){ // [Non-IE 10-] IE 10-은 beforepaste 단계에서 Husky 북마크를 이미 삽입했다. this._sBM = oSelection.placeStringBookmark(); var elEndBookmark = oSelection.getStringBookmark(this._sBM, true); var elStartBookmark = oSelection.getStringBookmark(this._sBM); /** * 붙여넣을 때 레이아웃 상에서 공간을 차지하고 있어야 * 컨텐츠가 의도한 위치에 붙여넣어지는데, * * HuskyRange에서 북마크 용도로 삽입하는 빈 <span>으로는 이를 충족할 수 없다. * * 시작 북마크의 뒤와, 끝 북마크의 앞에 * zero-width space 문자인 \u200b를 담고 있는 * 텍스트 노드를 삽입해 둔다. * */ var emptyTextNode = document.createTextNode(""); this.zwspStart = emptyTextNode.cloneNode(true); this.zwspStart.nodeValue = "\u200b"; this.zwspEnd = this.zwspStart.cloneNode(true); elEndBookmark.parentNode.insertBefore(this.zwspEnd, elEndBookmark); elEndBookmark.parentNode.insertBefore(this.zwspStart, this.zwspEnd); /** * oSelection.select()로 목표 위치에 커서를 위치시킨다. * * <시작 북마크 /><\u200b>[목표 커서 위치]<\u200b><끝 북마크 /> * */ oSelection.setEndBefore(this.zwspEnd); oSelection.collapseToEnd(); oSelection.select(); /** * [IE 11]텍스트 편집기의 tab이 붙여넣어지는 컨텐츠의 가장 마지막에 들어가는 경우, * \u200b를 zwspEnd 노드에서 찾을 수 없는 문제가 있어서 * 사전에 제거해 준다. * */ if(this.htBrowser.ie && this.htBrowser.nativeVersion == 11 && this.htBrowser.version == 11){ //this.zwspEnd.nodeValue = ""; } } // --[SMARTEDITORSUS-1676] }, /** * 외부 프로그램의 컨텐츠가 원문에 붙여넣어지는 과정을 진행한다. * */ _processPaste : function(){ this._savePastedContents(); // [SMARTEDITORSUS-1673] try{ if(!!this.elPasteHelper){ this._clearPasteHelper(); this._showPasteHelper(); }else{ // 붙여넣기 작업 공간 생성(최초 1회) this._createPasteHelper(); } // 작업 공간에 붙여넣기 this._loadToPasteHelper(); // 붙여넣기 작업 공간에 붙여넣은 컨텐츠를 떠서 본문의 해당 영역 교체 this._loadToBody(); this._hidePasteHelper(); }catch(e){ this._hidePasteHelper(); throw e; } this._hidePasteHelper(); // --[SMARTEDITORSUS-1673] }, /** * 본문 영역에 외부 프로그램의 컨텐츠가 붙여넣어지면 이를 저장하고, * SmartEditor에 맞게 필터링한다. * */ _savePastedContents : function(){ // [SMARTEDITORSUS-1673] /** * 삽입된 북마크를 기준으로 하여 * 붙여넣어진 컨텐츠를 복사해 두고, * 이후 이를 활용하여 별도의 공간에서 작업 * */ var oSelection = this.oApp.getSelection(); this._moveToStringBookmark(oSelection); oSelection.select(); this.oSelectionClone = oSelection.cloneContents(); // 컨텐츠 복사가 끝났으므로 선택 해제 oSelection.collapseToEnd(); oSelection.select(); var sTarget = this._outerHTML(this.oSelectionClone); // --[SMARTEDITORSUS-1673] this._isPastedContentsEmpty = true; // 붙여넣어진 내용이 없는지 확인 if(sTarget != ""){ this._isPastedContentsEmpty = false; /** * [FireFox, Safari6+] clipboard에서 style 정의를 저장할 수는 없지만, * 본문에 붙여넣어진 뒤 획득하여 저장 가능 * * iWork Pages의 경우, 이전 시점에서 들어온 스타일 정보가 이미 존재할 수도 있기 때문에 * 기존 변수에 값을 더해넣는 방식 사용 * * @XXX 27.0 업데이트 이후 style 정보가 넘어오지 않아 값을 저장할 수 없음 * */ if(this.htBrowser.firefox || (this.htBrowser.safari && this.htBrowser.version >= 6)){ var aStyleFromClipboard = sTarget.match(/<style>([^<>]+)<\/style>/i); if(aStyleFromClipboard){ var sStyleFromClipboard = aStyleFromClipboard[1]; // style="" 내부에 삽입되는 경우, 조화를 이루어야 하기 때문에 쌍따옴표를 따옴표로 치환 sStyleFromClipboard = sStyleFromClipboard.replace(/"/g, "'"); if(this._sStyleFromClipboard){ this._sStyleFromClipboard += sStyleFromClipboard; }else{ this._sStyleFromClipboard = sStyleFromClipboard; } } } // 붙여넣어진 컨텐츠를 정제 this._sTarget = this._filterPastedContents(sTarget); } }, /** * [SMARTEDITORSUS-1673] 원문에 삽입해 두었던 북마크로 이동. * * 붙여넣기 이벤트 발생 시점에 원문에 삽입해 둔 북마크이다. * */ _moveToStringBookmark : function(oSelection){ if(!!this._sBM_IE){ // [IE 10-] beforepaste 단계에서 붙여넣어진 북마크를 selection에 사용 oSelection.moveToStringBookmark(this._sBM_IE); }else{ // paste 이벤트에서 붙여넣어진 북마크를 selection에 사용 oSelection.moveToStringBookmark(this._sBM); } }, /** * [SMARTEDITORSUS-1673] X-Browsing 비호환 프로퍼티인 outerHTML fix * */ _outerHTML : function(el){ var sOuterHTML = ""; if(el.outerHTML){ sOuterHTML = el.outerHTML; }else{ var elTmp = document.createElement("DIV"); elTmp.appendChild(el.cloneNode(true)); sOuterHTML = elTmp.innerHTML; } return sOuterHTML; }, /** * SmartEditor에 맞는 필터링을 거친 컨텐츠를 반환한다. * @param {String} 필터링 대상이 될 HTML * */ _filterPastedContents : function(sOriginalContent){ // 문단 교체와 관련된 변수 this._isPastedMultiParagraph = false; // 붙여넣어지는 컨텐츠가 여러 문단으로 구성되어 있는지 확인 this._aGoesPreviousParagraph = []; // 문단의 분리가 있는 경우, 원래의 북마크가 있는 문단으로 넘어갈 inline 요소들의 집합 var bParagraphChangeStart = false, bParagraphChangeEnd = false, nParagraphHierarchy = 0, // 몇 중으로 열려 있는지 확인 nParagraphChangeCount = 0, // 문단 교체 횟수 bParagraphIsOpen = false; // 현재 문단이 열려 있는지 확인 var sMatch, // 판별식과 일치하는 부분 sResult, // 판별식과 일치하는 부분이 필터링을 거쳐 최종적으로 반환되는 형태 aResult = [], // 최종적으로 반환되는 정제된 컨텐츠들이 담긴 배열 nPreviousIndex = -1, // 직전 작업 부분이 결과 배열에서 차지하는 index sTagName, // 판별식과 일치하는 부분의 태그명 sPreviousContent = "", // 직전 삽입된 컨텐츠 aMultiParagraphIndicator = ["BLOCKQUOTE", "DD", "DIV", "DL", "FORM", "H1", "H2", "H3", "H4", "H5", "H6", "HR", "OL", "P", "TABLE", "UL", "IFRAME"], // white list로 여러 문단으로 처리해야 하는 경우를 구별 (https://developer.mozilla.org/ko/docs/HTML/Block-level_elements) rxMultiParagraphIndicator = new RegExp("^(" + aMultiParagraphIndicator.join("|") + ")$", "i"), // 현재 작업이 테이블 내부에서 이루어지고 있는지 확인. tr, td에 style이 명시되어 있지 않은 경우 사용 isInTableContext = false, nTdIndex = 0, // tr, td의 style 캐싱 중에 현재 몇 번째 td인지 확인을 위함 nTdLength = 0, // 캐싱 시점에 총 td의 수를 구함 aColumnWidth = [], // col의 width를 저장하는 배열 nRowHeight = 0; // tr의 height 저장용 // [SMARTEDITORSUS-1671] 다중 테이블의 col 캐싱 var nTableDepth = 0; var aaColumnWidth = []; // 이차원 배열 // --[SMARTEDITORSUS-1671] // 패턴 var rxOpeningTag = /^<[^?\/\s>]+(([\s]{0})|([\s]+[^>]+))>/, // 열린 태그 rxTagName = /^<[\/]?([^\s]+)(([\s]{0})|([\s]+[^>]+))>/, // 태그명 rxClosingTag = /^<\/[A-Za-z]+>/, // 닫힌 태그 rxOpeningAndClosingTag = /^<[^>]+\/>/, // 자체로 열고 닫는 태그 rxCommentTag = /^<!--[^<>]+-->/, // 주석이나 커스텀 태그 rxOpeningCommentTag = /^<!--[^->]+>/, // 열린 주석 태그 rxClosingCommentTag = /^<![^->]+-->/, // 닫힌 주석 태그 rxWhiteSpace = /^[\n\r\t\s]+/, // 공백 rxNonTag = /^[^<\n]+/, // 태그 아닌 요소 rxExceptedOpeningTag = /^<[^<>]+>/, // 어느 조건도 통과하지 않은, 열린 예외 태그들 rxExceptedClosingTag = /^<\/[^<>]+>/, // 어느 조건도 통과하지 않은, 닫힌 예외 태그들 // MS 프로그램의 테이블에서 특히 사용하는 패턴 rxMsoStyle = /(mso-[^:]+[\s]*:[\s]*)([^;"]*)([;]?)/gi, // Mso-로 시작하는 스타일이 있는지 검사 // [SMARTEDITORSUS-1673] rxStyle = /(style[\s]*=[\s]*)(["'])([^"']*)(["'])/i, // style 속성 획득 rxClass = /class[\s]*=[\s]*(?:(?:["']([^"']*)["'])|([^\s>]+))/i, // --[SMARTEDITORSUS-1673] rxTableClassAdd = /(^<table)/gi, bColgroupAppeared, // [IE 8~11] MS Excel에서 열린 채 삽입되는 colgroup 태그를 처리하기 위해, 부득이하게 수동으로 </colgroup>을 추가하기 위한 flag. <table> 단위로 사용 rxApplied; // 결과 문자열 작업시 적용하는 패턴 /** * depth를 활용한 white-list, black-list * * -depth 는 열린 태그일 때 +1, 닫힌 태그일 때 -1 * -허용/제외 시작 depth를 기준으로 처리 * */ var bInit = true, // 첫 번째 작업인 경우 보정에 사용 nDepth = 0, // 현재 코드의 depth // 작업 대상을 기준으로, 직전 대상 판단 기준 wasSibling = true, // 같은 depth였는지 확인 wasJustOpened = true, // 작업 태그가 닫힌 태그일 때, 직전 작업 대상이 열린 태그라면 depth를 유지해 주기 위한 flag wasClosed = true, // 닫힌 태그였는지 확인 // Open-only 감지 aOnlyOpeningTag = ["BR", "IMG", "COL", "HR"], // 열고 닫히는 형태가 아닌 태그들로, depth 불변. rxOnlyOpeningTag = new RegExp("^(" + aOnlyOpeningTag.join("|") + ")$", "i"), bDepthChange, // depth 변경이 없는 태그인지 판별하는 용도 /** * white-list 요소에 태그를 넣어놨다면 white-list 태그 이하의 요소만을 포함시키고, * black-list 요소에 태그를 넣어놨다면 black-list 태그가 포함된 경우 이하의 모든 요소를 제외한다. * white-list가 우선순위를 가지며, white-list가 없을 경우에만 black-list가 적용된다. * */ // black-list aExcludedTag = ["SCRIPT", "STYLE"], // black-list 목록 rxExcludedTag = (aExcludedTag.length > 0) ? new RegExp("^(" + aExcludedTag.join("|") + ")$", "i") : null, bExclusionOpen = false, // 제외되기 시작하는 태그. 하위 요소는 모두 제외된다. bExclusionClose = false, // 제외가 끝나는 태그. 하위 요소는 모두 제외된다. bExclusionOpenAndClose = false, // 열리고 닫히는 태그로, 자신만 제외된다. nExclusiononStartDepth = 0, // 제외가 시작된 depth // whilte-list flag aAllowedTag = [], // white-list 목록 rxAllowedTag = (aAllowedTag.length > 0) ? new RegExp("^(" + aAllowedTag.join("|") + ")$", "i") : null, bInclusionOpen = false, // 허용되기 시작하는 태그. 하위 요소는 모두 포함된다. bInclusionClose = false, // 허용이 끝나는 태그. 하위 요소는 모두 포함된다. bInclusionOpenAndClose = false, // 열리고 닫히는 태그로, 자신만 포함된다. nInclusionStartDepth = 0; /** * 원본 String의 앞에서부터 읽어 나가며 * 패턴과 일치하는 부분을 하나씩 처리하고, * 작업이 끝난 대상은 * 결과 배열로 보냄과 동시에 * 원래의 String에서 제거한다. * 더 이상 처리할 String이 없을 때 종료. * */ while(sOriginalContent != ""){ sResult = "", sMatch = ""; // white/black-list 처리에 활용 bDepthChange = true; /** * 원본 String의 가장 앞 부분은 아래의 패턴 분기 중 하나와 일치하며, * sMatch, sResult, rxApplied의 3가지 변수로 작업한다. * * sMatch : 패턴과 일치하는 부분을 우선 획득. 작업 대상이다. * sResult : sMatch에서 정제가 이루어진 결과물. 이들의 집합이자, 반환값과 연결된 aResult에 저장된다. * rxApplied : 원본 String에서 작업이 끝난 부분을 지울 때 재활용 * */ if(rxOpeningAndClosingTag.test(sOriginalContent)){ // <tagName /> sMatch = sOriginalContent.match(rxOpeningAndClosingTag)[0]; // white/black-list 처리부 if(!wasSibling){ // 직전 태그가 형제가 아닌, 열려 있는 부모 태그인 경우. nDepth++; wasSibling = true; } wasJustOpened = false; // white/black-list 처리부 sResult = sMatch; rxApplied = rxOpeningAndClosingTag; }else if(rxClosingCommentTag.test(sOriginalContent)){ // <! text--> sMatch = sOriginalContent.match(rxClosingCommentTag)[0]; // white/black-list 처리부 if(wasJustOpened){ wasJustOpened = false; }else{ nDepth--; } // 제외 대상인 경우, 닫히는 태그의 depth가 최초로 제외되기 시작한 태그의 depth와 같아야 비로소 제외 종료 if(bExclusionOpen){ if(nExclusiononStartDepth == nDepth){ bExclusionClose = true; } } if(bInclusionOpen){ if(nInclusionStartDepth == nDepth){ bInclusionClose = true; } } wasSibling = true; wasClosed = true; // --white/black-list 처리부 sResult = sMatch; rxApplied = rxClosingCommentTag; }else if(rxOpeningCommentTag.test(sOriginalContent)){ // <!-- text> sMatch = sOriginalContent.match(rxOpeningCommentTag)[0]; // white/black-list 처리부 if(!wasClosed || wasJustOpened){ if(!wasSibling){ nDepth++; } } // 열린 조건부 주석은 white/black list와 무관하게 제외 대상 if(/^<!--\[if/.test(sMatch)){ if(!bExclusionOpen){ bExclusionOpen = true; // 최초로 제외되기 시작한 태그의 depth를 기록해 둔다. if(nExclusiononStartDepth < nDepth){ nExclusiononStartDepth = nDepth; } } } wasSibling = false; wasJustOpened = true; // --white/black-list 처리부 sResult = sMatch; rxApplied = rxOpeningCommentTag; }else if(rxCommentTag.test(sOriginalContent)){ // <!-- text --> /* 순서도치. rxOpeningTag 수정으로 beautify와는 달리 comment를 포괄하게 되어 버리기 때문 */ sMatch = sOriginalContent.match(rxCommentTag)[0]; // white/black-list 처리부 /** * <!--[if supportLists]-->, <!--[if supportFields]--> 등 렌더링에 활용되는 조건부 주석이 있기 때문에 제거하지 못한다. * * 따라서 depth 처리만 이루어진다. * */ if(!wasSibling){ nDepth++; wasSibling = true; } wasJustOpened = false; //-- white/black-list 처리부 sResult = sMatch; rxApplied = rxCommentTag; }else if(rxOpeningTag.test(sOriginalContent)){ // <tagName> sMatch = sOriginalContent.match(rxOpeningTag)[0]; // white/black-list 처리부 bDepthChange = true; sTagName = sMatch.replace(rxTagName, "$1"); if(rxOnlyOpeningTag.test(sTagName)){ bDepthChange = false; } if(bDepthChange){ // br, img 태그가 아닌 열린 태그 if(!wasClosed || wasJustOpened){ nDepth++; } wasSibling = false; wasJustOpened = true; }else{ // Open-only elements if(!wasSibling){ nDepth++; wasSibling = true; } wasJustOpened = false; } // 제외 대상인 태그 목록의 이름과 일치하면 제외시킨다. if(!!rxAllowedTag){ var isInWhiteList = false; if(rxAllowedTag.test(sTagName)){ // white-list isInWhiteList = true; } if(isInWhiteList){ if(!bInclusionOpen){ bInclusionOpen = true; if(nInclusionStartDepth < nDepth){ nInclusionStartDepth = nDepth; } } }else{ // 제외처리 계속 if(!bExclusionOpen){ bExclusionOpen = true; if(nExclusiononStartDepth < nDepth){ nExclusiononStartDepth = nDepth; } } } }else if(!!rxExcludedTag){ if(rxExcludedTag.test(sTagName)){ // black-list if(!bExclusionOpen){ bExclusionOpen = true; if(nExclusiononStartDepth < nDepth){ nExclusiononStartDepth = nDepth; } } } } // --white/black-list 처리부 // class attribute의 값 획득 var sClassAttr = ""; if(rxClass.test(sMatch)){ // [SMARTEDITORSUS-1673] sClassAttr = sMatch.match(rxClass)[1] || sMatch.match(rxClass)[2]; // --[SMARTEDITORSUS-1673] } // 실질적으로 스타일이나 클래스 조작이 이루어지는 쪽은 열린 태그 부분 // &quot; 를 ' 로 치환 sMatch = sMatch.replace(/&quot;/gi, "'"); // mso- 로 시작하는 style 제거 sMatch = sMatch.replace(rxMsoStyle, ""); var _widthAttribute = "", _heightAttribute = "", _widthStyle = "", _heightStyle = "", _nWidth = "", _nHeight = "", _bWidthStyleReplaceNeed = false, _bHeightStyleReplaceNeed = false, // width, style 이 attribute로 존재한다면, 이를 style로 변환해 줘야 할 필요가 있음 // [SMARTEDITORSUS-1671] rxWidthAttribute = /([^\w-])(width[\s]*=[\s]*)(["']?)([A-Za-z0-9.]+[%]?)(["']?)/i, rxHeightAttribute = /([^\w-])(height[\s]*=[\s]*)(["']?)([A-Za-z0-9.]+[%]?)(["']?)/i, rxWidthStyle = /(["';\s])(width[\s]*:[\s]*)([A-Za-z0-9.]+[%]?)([;]?)/i, rxHeightStyle = /(["';\s])(height[\s]*:[\s]*)([A-Za-z0-9.]+[%]?)([;]?)/i; // --[SMARTEDITORSUS-1671] /** * 모든 열린 태그 공통처리사항. * * width, height가 attribute에 할당되어 있거나, 그 단위가 px가 아닌 pt인 경우에 * px 단위로 style 안으로 바꿔넣는 보정이 이루어진다. * __se_tbl 클래스를 가진 SmartEditor의 표는 * width, height의 리사이징이 발생할 때 * 실시간 변화가 적용되는 style에 그 결과값을 px로 저장하기 때문이다. * @see hp_SE2M_TableEditor.js * */ /** * [Chrome, FireFox, Safari6+] 저장해 둔 style 정의로부터, * class 명으로 적용해야 할 style이 있는 경우 추가해 준다. * */ if(this.htBrowser.chrome || this.htBrowser.firefox || (this.htBrowser.safari && this.htBrowser.version >= 6)){ var aClass = []; if(sClassAttr && !/mso/i.test(sClassAttr)){ // MsoTableGrid 클래스가 포함된 경우(MS Word)는 제외 : style 정의를 불러와서 적용하면 오히려 레이아웃 비정상 aClass = sClassAttr.split(" "); } if(aClass && aClass.length > 0){ for(var i = 0, len = aClass.length; i < len; i++){ var sClass = aClass[i]; var sRx = sClass + "[\\n\\r\\t\\s]*{([^}]*)}"; var rxClassForStyle = new RegExp(sRx); var sMatchedStyle = ""; if(rxClassForStyle.test(this._sStyleFromClipboard)){ sMatchedStyle = this._sStyleFromClipboard.match(rxClassForStyle)[1]; } if(sMatchedStyle){ // 위에서 매치되는 style을 태그 안에 추가해 준다. if(!!rxStyle.test(sMatch)){ sMatch = sMatch.replace(rxStyle, "$1$2" + sMatchedStyle + " $3$4"); }else{ // style마저 없다면 새로 만들어 준다. sMatch = sMatch.replace(/(>)/g, " style=\"" + sMatchedStyle + "\"$1"); } } } } } // width attribute가 존재한다면 if(rxWidthAttribute.test(sMatch)){ _widthAttribute = sMatch.match(rxWidthAttribute)[4]; // [SMARTEDITORSUS-1671] if(/pt/.test(_widthAttribute)){ _nWidth = parseFloat(_widthAttribute, 10) * 96 / 72 + "px"; // pt를 px로 변환 }else if(/px/.test(_widthAttribute)){ // 변환을 거칠 필요 없음 _nWidth = _widthAttribute; }else if(/%/.test(_widthAttribute)){ // % _nWidth = _widthAttribute; }else if(!/\d/.test(_widthAttribute)){ // auto, inherit, initial _nWidth = _widthAttribute; }else if(!/px/.test(_widthAttribute)){ // 숫자만 있는 경우 _nWidth = _widthAttribute + "px"; } // --[SMARTEDITORSUS-1671] sMatch = sMatch.replace(rxWidthAttribute, "$1"); // style로 변환해 줄 필요가 있다. _bWidthStyleReplaceNeed = true; }else{ _bWidthStyleReplaceNeed = false; } // width style이 존재한다면 if(rxWidthStyle.test(sMatch)){ _widthStyle = sMatch.match(rxWidthStyle)[3]; // [SMARTEDITORSUS-1671] _bWidthStyleReplaceNeed = true; if(/pt/.test(_widthStyle)){ _nWidth = parseFloat(_widthStyle, 10) * 96 / 72 + "px"; // pt를 px로 변환 }else if(/px/.test(_widthStyle)){ // 변환을 거칠 필요 없음 _bWidthStyleReplaceNeed = false; }else if(/%/.test(_widthStyle)){ // % _nWidth = _widthStyle; }else if(!/\d/.test(_widthStyle)){ // auto, inherit, initial _nWidth = _widthStyle; }else if(!/px/.test(_widthStyle)){ // 숫자만 있는 경우 _nWidth = _widthStyle + "px"; } if(_bWidthStyleReplaceNeed){ sMatch = sMatch.replace(rxWidthStyle, "$1$2" + _nWidth + ";"); } // --[SMARTEDITORSUS-1671] }else{ if(_bWidthStyleReplaceNeed){ // [SMARTEDITORSUS-1671] if(_nWidth){ // attribute에서 style용으로 변환한 값을 사용 if(!!rxStyle.test(sMatch)){ sMatch = sMatch.replace(rxStyle, "$1$2width:" + _nWidth + "; $3$4"); }else{ // style마저 없다면 새로 만들어 준다. sMatch = sMatch.replace(/(>)/g, " style=\"width:" + _nWidth + ";\"$1"); } } // --[SMARTEDITORSUS-1671] } } // height attribute가 존재한다면 if(rxHeightAttribute.test(sMatch)){ _heightAttribute = sMatch.match(rxHeightAttribute)[4]; // [SMARTEDITORSUS-1671] if(/pt/.test(_heightAttribute)){ _nHeight = parseFloat(_heightAttribute, 10) * 96 / 72 + "px"; // pt를 px로 변환 }else if(/px/.test(_heightAttribute)){ // 변환을 거칠 필요 없음 _nHeight = _heightAttribute; }else if(/%/.test(_heightAttribute)){ // % _nHeight = _heightAttribute; }else if(!/\d/.test(_heightAttribute)){ // auto, inherit, initial _nHeight = _heightAttribute; }else if(!/px/.test(_heightAttribute)){ // 숫자만 있는 경우 _nHeight = _heightAttribute + "px"; } // --[SMARTEDITORSUS-1671] sMatch = sMatch.replace(rxHeightAttribute, "$1"); // style로 변환해 줄 필요가 있다. _bHeightStyleReplaceNeed = true; }else{ _bHeightStyleReplaceNeed = false; } // height style이 존재한다면 if(rxHeightStyle.test(sMatch)){ _heightStyle = sMatch.match(rxHeightStyle)[3]; // [SMARTEDITORSUS-1671] _bHeightStyleReplaceNeed = true; if(/pt/.test(_heightStyle)){ _nHeight = parseFloat(_heightStyle, 10) * 96 / 72 + "px"; // pt를 px로 변환 }else if(/px/.test(_heightStyle)){ // 변환을 거칠 필요 없음 _bHeightStyleReplaceNeed = false; }else if(/%/.test(_heightStyle)){ // % _nHeight = _heightStyle; }else if(!/\d/.test(_heightStyle)){ // auto, inherit, initial _nWidth = _heightStyle; }else if(!/px/.test(_heightStyle)){ // 숫자만 있는 경우 _nHeight = _heightStyle + "px"; } if(_bHeightStyleReplaceNeed){ sMatch = sMatch.replace(rxHeightStyle, "$1$2" + _nHeight + ";"); } // --[SMARTEDITORSUS-1671] }else{ if(_bHeightStyleReplaceNeed){ // [SMARTEDITORSUS-1671] if(_nHeight){ // attribute에서 style용으로 변환한 값을 사용 if(!!rxStyle.test(sMatch)){ sMatch = sMatch.replace(rxStyle, "$1$2height:" + _nHeight + "; $3$4"); }else{ // style마저 없다면 새로 만들어 준다. sMatch = sMatch.replace(/(>)/g, " style=\"height:" + _nHeight + ";\"$1"); } } // --[SMARTEDITORSUS-1671] } } /** * 각 태그에 맞는 처리가 추가수행되는 부분. * * 태그명을 확인한 뒤 분기처리 * */ sTagName = sMatch.replace(rxTagName, "$1"); if(/^TABLE$/i.test(sTagName)){ /** * [SMARTEDITORSUS-1673] 외부에서 붙여넣은 테이블에 대하여 __se_tbl_ext 클래스 부여 * */ if(sClassAttr){ if(!/__se_tbl/g.test(sClassAttr)){ var rxClass_rest = /(class[\s]*=[\s]*["'])([^"']*)(["'])/i; var rxSingleClass_underIE8 = /(class[\s]*=[\s]*)([^"'\s>]+)/i; if(rxClass_rest.test(sMatch)){ // class="className [className2...]" sMatch = sMatch.replace(rxClass_rest, "$1$2 __se_tbl_ext$3"); }else if(rxSingleClass_underIE8.test(sMatch)){ // [IE8-] class=className sMatch = sMatch.replace(rxSingleClass_underIE8, "$1\"$2 __se_tbl_ext\""); } //sMatch = sMatch.replace(rxTableClassModify, "$1$2 __se_tbl$3"); } }else{ sMatch = sMatch.replace(rxTableClassAdd, "$1 class=\"__se_tbl_ext\""); } // --[SMARTEDITORSUS-1673] // </table> 태그가 등장하기 전까지 작업은 table 맥락에서 이루어진다. isInTableContext = true; // <colgroup> 작업용 flag 초기화 bColgroupAppeared = false; // [SMARTEDITORSUS-1671] 테이블을 다중으로 관리 nTableDepth++; // --[SMARTEDITORSUS-1671] } /** * 모든 셀이 동일한 너비와 높이가 아닌 경우, * <colgroup> 이하 <col>에 같은 열에 해당하는 셀의 너비가 정의되어 있으며, * 같은 행에 해당하는 셀의 높이는 <tr>에 정의되어 있다. * 이를 저장해 두고 각 <td>의 너비와 높이에 적용하는 데 사용한다. * * @XXX [SMARTEDITORSUS-1613] [NON-IE] * MS Excel 2010 기준으로, 1회 이상 병합된 표가 삽입될 때는 * class, width, height를 제외한 정보는 거의 넘어오지 않는다. * */ else if(/^COL$/i.test(sTagName)){ // <col>에 포함된 width style 정보 저장 _widthStyle = sMatch.match(rxWidthStyle)[3]; // span 갯수를 세서 row 수인 nTdLength 업데이트 var _nSpan = 0; if(/span[\s]*=[\s]*"([\d]+)"/.test(sMatch)){ _nSpan = sMatch.match(/span[\s]*=[\s]*"([\d]+)"/)[1]; } // [SMARTEDITORSUS-1671] 다중 테이블의 col 캐싱 if(!!aaColumnWidth[nTableDepth] && typeof(aaColumnWidth[nTableDepth].length) === "number"){ aColumnWidth = aaColumnWidth[nTableDepth]; }else{ aColumnWidth = []; } if(_nSpan){ _nSpan = parseInt(_nSpan, 10); for(var i = 0; i < _nSpan; i++){ aColumnWidth.push(_widthStyle); nTdLength++; } }else{ nTdLength++; aColumnWidth.push(_widthStyle); } aaColumnWidth[nTableDepth] = aColumnWidth; // --[SMARTEDITORSUS-1671] }else if(/^TR$/i.test(sTagName)){ // height 값 적용 if(!(rxHeightStyle.test(sMatch))){ nRowHeight = null; }else{ // 존재하면 td에 적용하기 위해 저장 _heightStyle = sMatch.match(rxHeightStyle)[3]; nRowHeight = _heightStyle; } }else if(/^(TD|TH)$/i.test(sTagName)){ /** * border 처리 * * MS Excel 2010 기준으로, * 0.5pt 두께로 넘어온 border는 100% 배율에서 표현되지 않기에 * 일괄 1px로 변환한다. * * 통상 0.84px 이상이면 100% 배율에서 표현된다. * */ var rxBorderWidth_pointFive_first = /(:[\s]*)(.5pt|0.5pt)/gi; var rxBorderWidth_pointFive_rest = /([^:\d])(.5pt|0.5pt)/gi; sMatch = sMatch.replace(rxBorderWidth_pointFive_first, "$11px").replace(rxBorderWidth_pointFive_rest, "$11px"); // 공통 처리 부분에서 스타일 치환 로직을 거쳤다면, 스타일이 적용되어 있어야 함 if(!(rxWidthStyle.test(sMatch))){ // 스타일 값이 없을 때, colgroup에서 저장한 값이 있으면 이를 적용함 // [SMARTEDITORSUS-1671] aColumnWidth = aaColumnWidth[nTableDepth]; if(!!aColumnWidth && aColumnWidth.length > 0){ // 저장한 값 있음 var nColumnWidth = aColumnWidth[nTdIndex]; if(nColumnWidth){ if(!!rxStyle.test(sMatch)){ sMatch = sMatch.replace(rxStyle, "$1$2width:" + aColumnWidth[nTdIndex] + "; $3$4"); }else{ // style마저 없다면 새로 만들어 준다. sMatch = sMatch.replace(/([^\s])([\s]*>|>)/, "$1 style=\"width:" + aColumnWidth[nTdIndex] + ";\"$2"); } } } // --[SMARTEDITORSUS-1671] } if(!(rxHeightStyle.test(sMatch))){ // 스타일 값이 없을 때, td에서 저장한 값이 있으면 이를 적용함 // [SMARTEDITORSUS-1671] if(!!nRowHeight){ if(!!rxStyle.test(sMatch)){ sMatch = sMatch.replace(rxStyle, "$1$2height:" + nRowHeight + "; $3$4"); }else{ // style마저 없다면 새로 만들어 준다. sMatch = sMatch.replace(/([^\s])([\s]*>|>)/g, "$1 style=\"height:" + nRowHeight + ";\"$2"); } } // --[SMARTEDITORSUS-1671] } // 적용할 때마다 nTdIndex 증가 nTdIndex++; }else if(/^COLGROUP$/i.test(sTagName)){ // <colgroup> 작업용 flag 업데이트 bColgroupAppeared = true; }else if(/^TBODY$/i.test(sTagName)){ // [IE 8~11] MS Excel, MS PowerPoint에서 열린 채 삽입되는 <colgroup> 처리를 위해, 부득이하게 수동으로 </colgroup> 추가 if(bColgroupAppeared){ sResult = "</colgroup>"; } } // 문단 교체가 발생하는지를 기록하는 flag if(rxMultiParagraphIndicator.test(sTagName)){ this._isPastedMultiParagraph = true; // 붙여넣어진 컨텐츠가 여러 문단으로 구성되어 있는지 확인 bParagraphChangeStart = true; // 새로운 문단이 열렸음을 표시 } sResult += sMatch; rxApplied = rxOpeningTag; }else if(rxWhiteSpace.test(sOriginalContent)){ // 공백문자는 일단 그대로 통과시킴. 차후 처리 방안이 있을지 논의 필요 sMatch = sOriginalContent.match(rxWhiteSpace)[0]; sResult = sMatch; rxApplied = rxWhiteSpace; }else if(rxNonTag.test(sOriginalContent)){ // 태그 아님 sMatch = sOriginalContent.match(rxNonTag)[0]; // white/black-list 처리부 if(!wasSibling){ // 직전 태그가 형제가 아닌, 열려 있는 부모 태그인 경우. nDepth++; wasSibling = true; } wasJustOpened = false; // white/black-list 처리부 sResult = sMatch; rxApplied = rxNonTag; }else if(rxClosingTag.test(sOriginalContent)){ // </tagName> sMatch = sOriginalContent.match(rxClosingTag)[0]; // white/black-list 처리부 if(wasJustOpened){ // 태그가 열리자마자 컨텐츠 없이 닫힘 태그가 이어질 경우 depth 변경 없음 wasJustOpened = false; }else{ nDepth--; } if(bExclusionOpen){ if(nExclusiononStartDepth == nDepth){ bExclusionClose = true; } } if(bInclusionOpen){ if(nInclusionStartDepth == nDepth){ bInclusionClose = true; } } wasSibling = true; wasClosed = true; // white/black-list 처리부 // <td> 내에 아무런 컨텐츠도 없다면 커서가 닿을 수 없기 때문에 처리해 주는 부분 if(rxOpeningTag.test(sPreviousContent)){ if(isInTableContext){ sTagName = sPreviousContent.replace(rxTagName, "$1"); // 직전 태그가 Open-only element가 아닐 경우에만 적용 var bOpenOnly = false; if(rxOnlyOpeningTag.test(sTagName)){ bOpenOnly = true; } if(!bOpenOnly){ if(!(/husky_bookmark/g.test(sPreviousContent))){ // 이 시점에서 바로 전 태그가 열린 태그였다면, &nbsp;를 넣어줘야 커서 위치 가능 sResult = "&nbsp"; } } } } // 태그별 분기처리 sTagName = sMatch.replace(rxTagName, "$1"); /** * 모든 셀이 동일한 너비와 높이가 아닌 경우, * 각 <td>의 너비와 높이에 적용하는 데 사용했던 * 저장값들을 초기화한다. * */ if(/^TABLE$/i.test(sTagName)){ // [SMARTEDITORSUS-1671] 다중 테이블의 col 캐싱 aaColumnWidth[nTableDepth] = null; nTableDepth--; // --[SMARTEDITORSUS-1671] isInTableContext = false; nTdLength = 0; nTdIndex = 0; }else if(/^TR$/i.test(sTagName)){ nTdIndex = 0; } if(rxMultiParagraphIndicator.test(sTagName)){ // p, div, table, iframe bParagraphChangeEnd = true; // 새로운 문단이 막 닫혔음을 표시 } // 빈 <td>였다면 &npsp;가 추가되어 있기 때문에 연산자가 다른 경우와는 다름 sResult += sMatch; rxApplied = rxClosingTag; } // 지금까지의 조건에 부합하지 않는 모든 태그는 예외 태그로 처리한다. MS Word의 <o:p> 등이 해당. else if(rxExceptedClosingTag.test(sOriginalContent)){ // </*unknown*> : similar to rxClosingCommentTag case sMatch = sOriginalContent.match(rxExceptedClosingTag)[0]; // white/black-list 처리부 if(wasJustOpened){ wasJustOpened = false; }else{ nDepth--; } wasSibling = true; wasClosed = true; // white/black-list 처리부 sResult = sMatch; rxApplied = rxExceptedClosingTag; }else if(rxExceptedOpeningTag.test(sOriginalContent)){ // <*unknown*> : similar to rxOpeningCommentTag case sMatch = sOriginalContent.match(rxExceptedOpeningTag)[0]; // white/black-list 처리부 if(!wasClosed || wasJustOpened){ if(!wasSibling){ nDepth++; } } wasSibling = false; wasJustOpened = true; // white/black-list 처리부 sResult = sMatch; rxApplied = rxExceptedOpeningTag; }else{ // unreachable point throw new Error("Unknown Node : If the content isn't invalid, please let us know."); } // sResult로 작업 // 최초 작업 시 열린 태그가 오는 경우 depth를 1에서 0으로 보정. if(bInit){ if(wasJustOpened){ nDepth = 0; } } // 직전 값 비교에 사용하기 위해 정보 갱신 if(sResult != ""){ sPreviousContent = sResult; // 현재 sResult는, 다음 작업 때 직전 값을 참조해야 할 필요가 있는 경우 사용된다. nPreviousIndex++; // 원본 String의 맨 앞부터 첫 문단 교체가 일어나기까지의 모든 inline 요소들을 저장해 두고 활용 var sGoesPreviousParagraph = ""; if(!this._isPastedMultiParagraph){ // 원본 String의 맨 앞부터 첫 문단 교체가 일어나기까지의 모든 inline 요소들을 저장해 두고 활용 sGoesPreviousParagraph = sResult; } if(!bParagraphChangeStart){ // 문맥 교체가 아직 시작되지 않았음 // text_content -> <p>text_content if(!bParagraphIsOpen){ if(nParagraphHierarchy == 0){ // 최상위 depth sResult = "<" + this.sParagraphContainer + ">" + sResult; bParagraphIsOpen = true; } } }else{ // 문맥 교체가 시작됨 // <p>text_content + <table> -> <p>text_content + </p> <table> if(bParagraphIsOpen){ // 문맥이 열림 sResult = "</" + this.sParagraphContainer + ">" + sResult; bParagraphIsOpen = false; } nParagraphChangeCount++; nParagraphHierarchy++; } // 문맥 교체가 끝났다면 문단 교체 flag 초기화 if(bParagraphChangeEnd){ bParagraphChangeStart = false; bParagraphChangeEnd = false; nParagraphHierarchy--; } // 2회차 돌입을 위한 bInit 업데이트 if(bInit){ bInit = false; } if(bExclusionOpen && !bInclusionOpen){ // 열리거나 닫히는 태그가 제외대상에만 포함되었다면, 이 부분을 통해 하위요소는 모두 결과에서 제외된다. if(bExclusionClose){ bExclusionOpen = false; bExclusionClose = false; // depth 초기화 nExclusiononStartDepth = 0; } }else{ // white/black-list에 부합하는 요소만 삽입된다. // whilte-list flag 초기화 if(bInclusionOpen){ if(bInclusionClose){ bInclusionOpen = false; bInclusionClose = false; bInclusionOpenAndClose = false; // depth 초기화 nInclusionStartDepth = 0; } } if(!this._isPastedMultiParagraph){ this._aGoesPreviousParagraph.push(sGoesPreviousParagraph); } // 최종적으로 반환되는 정체된 컨텐츠들이 담긴 배열 aResult.push(sResult); } // --white/black-list 처리와 결합 } // 정제가 끝난 컨텐츠는 원래 컨텐츠에서 제거 sOriginalContent = sOriginalContent.replace(rxApplied, ""); }; // --while // 최종 결과 한 번도 문단 교체가 없었다면 앞에 달린 문맥 교체 태그를 제거하고, inline으로 삽입 준비 if(nParagraphChangeCount == 0){ var rxParagraphContainer = new RegExp("^<" + this.sParagraphContainer + ">"); aResult[0] = aResult[0].replace(rxParagraphContainer, ""); } return aResult.join(""); }, /** * [SMARTEDITORSUS-1673] 붙여넣기 작업 공간(div.husky_seditor_paste_helper)을 생성 * */ _createPasteHelper : function(){ if(!this.elPasteHelper){ this.elPasteHelper = document.createElement("DIV"); this.elPasteHelper.className = "husky_seditor_paste_helper"; this.elPasteHelper.style.width = "0px"; this.elPasteHelper.style.height = "0px"; this.elPasteHelper.style.overflow = "auto"; this.elPasteHelper.contentEditable = "true"; this.elPasteHelper.style.position = "absolute"; this.elPasteHelper.style.top = "-9999px"; this.elPasteHelper.style.left = "-9999px"; this.elEditingAreaContainer.appendChild(this.elPasteHelper); } }, _showPasteHelper : function(){ if(!!this.elPasteHelper && this.elPasteHelper.style.display == "none"){ this.elPasteHelper.style.display = "block"; } }, _hidePasteHelper : function(){ if(!!this.elPasteHelper && this.elPasteHelper.style.display != "none"){ this.elPasteHelper.style.display = "none"; } }, /** * [SMARTEDITORSUS-1673] 붙여넣기 작업 공간의 내용을 비우고, * 새로운 컨텐츠 작업을 준비한다. * */ _clearPasteHelper : function(){ if(!!this.elPasteHelper){ this.elPasteHelper.innerHTML = ""; } }, /** * [SMARTEDITORSUS-1673] 붙여넣어진 컨텐츠가 가공되고 나면, 이를 붙여넣기 작업 공간에 붙여넣는다. * */ _loadToPasteHelper : function(){ // 붙여넣을 컨텐츠가 여러 문단일 경우 저장하는 배열 var aParagraph = []; // [SMARTEDITORSUS-874] [FireFox] br이 있는 inline의 경우 여러 문단으로 재구성 var bConsecutiveBR_firefox = false; if(!this._isPastedMultiParagraph){ // 붙여넣어지는 컨텐츠가 한 단락 내에 들어갈 수 있는 inline 요소만으로 구성 if(this.htBrowser.firefox){ if(/<br>/i.test(this._aGoesPreviousParagraph.join(""))){ // br이 있어 문단 분리가 가능한 경우 // 여기서 flag 업데이트 뒤 아래서 처리 bConsecutiveBR_firefox = true; /** * this._aGoesPreviousParagraph 에 모든 내용이 들어가 있고, * aParagraph에는 아무 값도 들어가 있지 않을 것이다. * * 이를 조작하여 * this._aGoesPreviousParagraph에는 첫 <br><br> 앞의 컨텐츠만 남기고 * aParagraph에는 나머지 컨텐츠를 <p> 생성 없이 inline 단위로 재편성한다. * -<br>처리 기준 * --단일 <br>은 linebreaker로 간주 * --2회차 연속하는 <br>부터 문단 분리 * * ex 1) inline1이 최초 컨텐츠인 경우 * this._aGoesPreviousParagraph : * [inline1, <br>, <br>, inline2, <br>, inline3, <br>] * aParagraph : * [] * * - 작업 후 * this._aGoesPreviousParagraph : * [inline1] * aParagraph : * [<br>, inline2, inline3] * * ex 2) <br>이 최초 컨텐츠인 경우 * this._aGoesPreviousParagraph : * [<br>, <br>, inline1, <br>, inline2, <br>] * aParagraph : * [] * * - 작업 후 * this._aGoesPreviousParagraph : * [] * aParagraph : * [<br>, inline1, inline2] * * clone 북마크에 밀어넣어 기존 문단의 스타일이 적용되도록 함 * */ // this._aGoesPreviousParagraph 재구성 _aGoesPreviousParagraph = this._aGoesPreviousParagraph; this._aGoesPreviousParagraph = []; // this._sTarget 재구성 var _aTmpParagraph = []; // 현재 inline 작업중인 index var _nInlineIndex = -1; // 직전 요소 var _sPreviousContent = ""; // 현재 작업 중인 요소가 <br>인지 감별 var _isPreviousContentBR = false; // 직전 요소가 <br>인지 감별 var _isCurrentContentBR = false; // for문으로 순회 for(var i = 0, len = _aGoesPreviousParagraph.length; i < len; i++){ var _sCurrentContent = _aGoesPreviousParagraph[i]; _isCurrentContentBR = /<br>/i.test(_sCurrentContent); if(i == 0){ if(_isCurrentContentBR){ // <br>이면 linebraker로 간주하여 this._aGoesPreviousParagraph에 포함시키지 않음 }else{ // <br>이 아니면 this._aGoesPreviousParagraph의 첫 요소로 추가하여 스타일 적용 this._aGoesPreviousParagraph.push(_sCurrentContent); } }else{ _isPreviousContentBR = /<br>/i.test(_sPreviousContent); if(_isPreviousContentBR){ // 문단화하여 this.__aTmpParagraph에 추가 _aTmpParagraph.push(_sCurrentContent); _nInlineIndex++; }else{ if(_isCurrentContentBR){ // 현재 요소가 <br>이면 linebreaker로 간주해서 버림 }else{ // 현재 요소가 <br>이 아니면 _aTmpParagraph에 inline 작업 _aTmpParagraph[_nInlineIndex] += _sCurrentContent; } } } // 현재 작업 요소를 비교를 위해 직전 요소 값으로 저장 _sPreviousContent = _sCurrentContent; } /** * aParagraph 구성 * aParagraph[index]에는 inline 요소끼리 함께 뭉쳐서 Element 형태로 들어가야 함 * 임시 <div>에 넣어 추가 * */ for(var i = 0, len = _aTmpParagraph.length; i < len; i++){ var elTmp = document.createElement("DIV"); elTmp.innerHTML = _aTmpParagraph[i]; aParagraph.push(elTmp); } } } }else{ // [Non-FireFox] // 본문에 붙여넣을 때는 Node 형태로 변환 var elTmp = document.createElement("DIV"); elTmp.innerHTML = this._sTarget; aParagraph = elTmp.childNodes; } // --[SMARTEDITORSUS-874] try{ if(this._aGoesPreviousParagraph.length > 0){ var sGoesPreviousParagraph = this._aGoesPreviousParagraph.join(""); var elTmp = document.createElement("DIV"); elTmp.innerHTML = sGoesPreviousParagraph; var _aGoesPreviousParagraph = elTmp.childNodes; // _aGoesPreviousParagraph 삽입 for(var i = 0, len = _aGoesPreviousParagraph.length; i < len; i++){ this.elPasteHelper.appendChild(_aGoesPreviousParagraph[i].cloneNode(true)); } /** * inline 요소들은 aParagraph[0]에 문단 태그로 감싸져 들어 있었다. * 이를 앞으로 본문에 삽입될 요소들인 aParagraph에서 제거해야 함 * */ // [FireFox] 연속된 <br> 처리가 들어간 경우 aParagraph은 보정할 필요가 없다. if(!bConsecutiveBR_firefox){ // aParagraph의 0번 인덱스 제거 if(aParagraph.length > 0){ if(!!aParagraph.splice){ aParagraph.splice(0, 1); }else{ // [IE8-] var waParagraph = jindo.$A(aParagraph); waParagraph.splice(0, 1); aParagraph = waParagraph.$value(); } } } } // aParagraph 삽입 if(aParagraph.length > 0){ for(var i = 0, len = aParagraph.length; i < len; i++){ this.elPasteHelper.appendChild(aParagraph[i].cloneNode(true)); } } }catch(e){ throw e; } return; }, /** * [SMARTEDITORSUS-1673] 붙여넣기 작업 공간에 붙여넣은 컨텐츠 중, * 본문 영역에 붙여넣을 컨텐츠를 선별하여 * 브라우저 고유의 붙여넣기 기능으로 본문 영역에 붙여넣은 기존 컨텐츠와 교체한다. * */ _loadToBody : function(){ var oSelection = this.oApp.getSelection(); // 본문 영역에 붙여넣기 try{ /** * As-Is 컨텐츠 * * 본문 영역에 붙여넣어진 컨텐츠 중 가공된 컨텐츠로 치환될 대상 목록을 획득 * */ this._moveToStringBookmark(oSelection); oSelection.select(); var aSelectedNode_original = oSelection.getNodes(); var aConversionIndex_original = this._markMatchedElementIndex(aSelectedNode_original, this.aConversionTarget); /** * To-Be 컨텐츠 * * 붙여넣기 작업 공간에 붙여넣어진 컨텐츠를 selection으로 잡아서 * 선택된 부분의 모든 node를 획득할 필요가 있다. * * 기존의 this.oApp.getSelection()은 * iframe#se2_iframe 의 window를 기준으로 한 selection을 사용한다. * 따라서 해당 엘리먼트 하위에 속한 요소들만 selection 으로 획득할 수 있다. * * 붙여넣기 작업 공간으로 사용되는 div.husky_seditor_paste_helper 는 * iframe#se2_iframe의 형제이기 때문에 * this.oApp.getSelection()으로는 helper 안의 컨텐츠를 선택하지 못한다. * * 따라서 iframe#se2_iframe과 div.husky_seditor_paste_helper를 아우르는 * 부모 window를 기준으로 한 selection을 생성하여 * div.husky_seditor_paste_helper 내부의 컨텐츠를 선택해야 한다. * */ var oSelection_parent = this.oApp.getSelection(this.oApp.getWYSIWYGWindow().parent); oSelection_parent.setStartBefore(this.elPasteHelper.firstChild); oSelection_parent.setEndAfter(this.elPasteHelper.lastChild); oSelection_parent.select(); var aSelectedNode_filtered = oSelection_parent.getNodes(); var aConversionIndex_filtered = this._markMatchedElementIndex(aSelectedNode_filtered, this.aConversionTarget); // As-Is 컨텐츠를 To-Be 컨텐츠로 교체 if(aConversionIndex_original.length > 0 && aConversionIndex_original.length == aConversionIndex_filtered.length){ for(var i = 0, len = aConversionIndex_original.length; i < len; i++){ var nConversionIndex_original = aConversionIndex_original[i]; var nConversionIndex_filtered = aConversionIndex_filtered[i]; var elConversion_as_is = aSelectedNode_original[nConversionIndex_original]; var elConversion_to_be = aSelectedNode_filtered[nConversionIndex_filtered]; elConversion_as_is.parentNode.replaceChild(elConversion_to_be.cloneNode(true), elConversion_as_is); } } // 붙여넣어진 컨텐츠의 마지막으로 커서를 위치 this._moveToStringBookmark(oSelection); oSelection.collapseToEnd(); oSelection.select(); }catch(e){ /** * processPaste()에서 조작된 컨텐츠가 본문에 이미 삽입된 경우 * oSelectionClone을 기반으로 브라우저 고유 기능으로 붙여넣었던 컨텐츠를 복원한다. * */ // 삽입된 컨텐츠 제거 this._moveToStringBookmark(oSelection); oSelection.select(); oSelection.deleteContents(); // oSelectionClone 복원 var elEndBookmark = this._getStringBookmark(oSelection, true); elEndBookmark.parentNode.insertBefore(this.oSelectionClone.cloneNode(true), elEndBookmark); // 커서 원위치 this._moveToStringBookmark(oSelection); oSelection.collapseToEnd(); oSelection.select(); } }, /** * [SMARTEDITORSUS-1673] NodeList의 요소 중 * 주어진 태그명과 일치하는 요소가 * NodeList에서 위치하는 index를 기록해 둔다. * */ _markMatchedElementIndex : function(aNodeList, aTagName){ var aMatchedElementIndex = []; var sPattern = aTagName.join("|"); var rxTagName = new RegExp("^(" + sPattern + ")$", "i"); // ex) new RegExp("^(p|table|div)$", "i") for(var i = 0, len = aNodeList.length; i < len; i++){ var elNode = aNodeList[i]; if(rxTagName.test(elNode.nodeName)){ aMatchedElementIndex.push(i); } } return aMatchedElementIndex; }, /** * [SMARTEDITORSUS-1673] 원문에 삽입해 둔 북마크를 획득. * * 붙여넣기 이벤트 발생 시점에 원문에 삽입해 둔 북마크이다. * */ _getStringBookmark : function(oSelection, bGetEndBookmark){ var elBookmark; if(!!this._sBM_IE){ // [IE 10-] beforepaste 단계에서 붙여넣어진 북마크를 selection에 사용 elBookmark = oSelection.getStringBookmark(this._sBM_IE, bGetEndBookmark); }else{ // paste 이벤트에서 붙여넣어진 북마크를 selection에 사용 elBookmark = oSelection.getStringBookmark(this._sBM, bGetEndBookmark); } return elBookmark; }, /** * [SMARTEDITORSUS-1673] 원문에 삽입해 두었던 북마크를 삭제. * * 붙여넣기 이벤트 발생 시점에 원문에 삽입해 둔 북마크이다. * */ _removeStringBookmark : function(oSelection){ if(!!this._sBM_IE){ // [IE 10-] beforepaste 단계에서 붙여넣어진 북마크를 selection에 사용 if(oSelection.getStringBookmark(this._sBM_IE)){ oSelection.removeStringBookmark(this._sBM_IE); } }else{ // paste 이벤트에서 붙여넣어진 북마크를 selection에 사용 if(oSelection.getStringBookmark(this._sBM)){ oSelection.removeStringBookmark(this._sBM); } } } }); //} /** * @pluginDesc Enter키 입력시에 현재 줄을 P 태그로 감거나 <br> 태그를 삽입한다. */ nhn.husky.SE_WYSIWYGEnterKey = jindo.$Class({ name : "SE_WYSIWYGEnterKey", $init : function(sLineBreaker){ if(sLineBreaker == "BR"){ this.sLineBreaker = "BR"; }else{ this.sLineBreaker = "P"; } this.htBrowser = jindo.$Agent().navigator(); // [SMARTEDITORSUS-227] IE 인 경우에도 에디터 Enter 처리 로직을 사용하도록 수정 if(this.htBrowser.opera && this.sLineBreaker == "P"){ this.$ON_MSG_APP_READY = function(){}; } /** * [SMARTEDITORSUS-230] 밑줄+색상변경 후, 엔터치면 스크립트 오류 * [SMARTEDITORSUS-180] [IE9] 배경색 적용 후, 엔터키 2회이상 입력시 커서위치가 다음 라인으로 이동하지 않음 * 오류 현상 : IE9 에서 엔터 후 생성된 P 태그가 "빈 SPAN 태그만 가지는 경우" P 태그 영역이 보이지 않거나 포커스가 위로 올라가 보임 * 해결 방법 : 커서 홀더로 IE 이외에서는 <br> 을 사용 * - IE 에서는 렌더링 시 <br> 부분에서 비정상적인 P 태그가 생성되어 [SMARTEDITORSUS-230] 오류 발생 * unescape("%uFEFF") (BOM) 을 추가 * - IE9 표준모드에서 [SMARTEDITORSUS-180] 의 문제가 발생함 * (unescape("%u2028") (Line separator) 를 사용하면 P 가 보여지나 사이드이펙트가 우려되어 사용하지 않음) * IE 브라우저에서 Enter 처리 시, &nbsp; 를 넣어주므로 해당 방식을 그대로 사용하도록 수정함 */ if(this.htBrowser.ie){ this._addCursorHolder = this._addCursorHolderSpace; //[SMARTEDITORSUS-1652] 글자크기 지정후 엔터를 치면 빈SPAN으로 감싸지는데 IE에서 빈SPAN은 높이값을 갖지 않아 커서가 올라가 보이게 됨 // 따라서, IE의 경우 브라우저모드와 상관없이 다음라인의 SPAN에 무조건 ExtraCursorHolder 를 넣어주도록 코멘트처리함 // if(this.htBrowser.nativeVersion < 9 || document.documentMode < 9){ // this._addExtraCursorHolder = function(){}; // } }else{ this._addExtraCursorHolder = function(){}; this._addBlankText = function(){}; } }, $ON_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["sLineBreaker", this.sLineBreaker]); this.oSelection = this.oApp.getEmptySelection(); this.tmpTextNode = this.oSelection._document.createTextNode(unescape("%u00A0")); // 공백(&nbsp;) 추가 시 사용할 노드 jindo.$Fn(this._onKeyDown, this).attach(this.oApp.getWYSIWYGDocument(), "keydown"); }, _onKeyDown : function(oEvent){ var oKeyInfo = oEvent.key(); if(oKeyInfo.shift){ return; } if(oKeyInfo.enter){ if(this.sLineBreaker == "BR"){ this._insertBR(oEvent); }else{ this._wrapBlock(oEvent); } } }, /** * [SMARTEDITORSUS-950] 에디터 적용 페이지의 Compatible meta IE=edge 설정 시 줄간격 벌어짐 이슈 (<BR>) */ $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER", ["IR_TO_DB", jindo.$Fn(this.onIrToDB, this).bind()]); }, /** * IR_TO_DB 변환기 처리 * Chrome, FireFox인 경우에만 아래와 같은 처리를 합니다. * : 저장 시 본문 영역에서 P 아래의 모든 하위 태그 중 가장 마지막 childNode가 BR인 경우를 탐색하여 이를 &nbsp;로 변경해 줍니다. */ onIrToDB : function(sHTML){ var sContents = sHTML, rxRegEx = /<br(\s[^>]*)?\/?>((?:<\/span>)?<\/p>)/gi, rxRegExWhitespace = /(<p[^>]*>)(?:[\s^>]*)(<\/p>)/gi; sContents = sContents.replace(rxRegEx, "&nbsp;$2"); sContents = sContents.replace(rxRegExWhitespace, "$1&nbsp;$2"); return sContents; }, // [IE] Selection 내의 노드를 가져와 빈 노드에 unescape("%uFEFF") (BOM) 을 추가 _addBlankText : function(oSelection){ var oNodes = oSelection.getNodes(), i, nLen, oNode, oNodeChild, tmpTextNode; for(i=0, nLen=oNodes.length; i<nLen; i++){ oNode = oNodes[i]; if(oNode.nodeType !== 1 || oNode.tagName !== "SPAN"){ continue; } if(oNode.id.indexOf(oSelection.HUSKY_BOOMARK_START_ID_PREFIX) > -1 || oNode.id.indexOf(oSelection.HUSKY_BOOMARK_END_ID_PREFIX) > -1){ continue; } oNodeChild = oNode.firstChild; if(!oNodeChild || (oNodeChild.nodeType == 3 && nhn.husky.SE2M_Utils.isBlankTextNode(oNodeChild)) || (oNodeChild.nodeType == 1 && oNode.childNodes.length == 1 && (oNodeChild.id.indexOf(oSelection.HUSKY_BOOMARK_START_ID_PREFIX) > -1 || oNodeChild.id.indexOf(oSelection.HUSKY_BOOMARK_END_ID_PREFIX) > -1))){ tmpTextNode = oSelection._document.createTextNode(unescape("%uFEFF")); oNode.appendChild(tmpTextNode); } } }, // [IE 이외] 빈 노드 내에 커서를 표시하기 위한 처리 _addCursorHolder : function(elWrapper){ var elStyleOnlyNode = elWrapper; if(elWrapper.innerHTML == "" || (elStyleOnlyNode = this._getStyleOnlyNode(elWrapper))){ elStyleOnlyNode.innerHTML = "<br>"; } if(!elStyleOnlyNode){ elStyleOnlyNode = this._getStyleNode(elWrapper); } return elStyleOnlyNode; }, // [IE] 빈 노드 내에 커서를 표시하기 위한 처리 (_addSpace 사용) _addCursorHolderSpace : function(elWrapper){ var elNode; this._addSpace(elWrapper); elNode = this._getStyleNode(elWrapper); if(elNode.innerHTML == "" && elNode.nodeName.toLowerCase() != "param"){ try{ elNode.innerHTML = unescape("%uFEFF"); }catch(e) { } } return elNode; }, /** * [SMARTEDITORSUS-1513] 시작노드와 끝노드 사이에 첫번째 BR을 찾는다. BR이 없는 경우 끝노드를 반환한다. * @param {Node} oStart 검사할 시작노드 * @param {Node} oEnd 검사할 끝노드 * @return {Node} 첫번째 BR 혹은 끝노드를 반환한다. */ _getBlockEndNode : function(oStart, oEnd){ if(!oStart){ return oEnd; }else if(oStart.nodeName === "BR"){ return oStart; }else if(oStart === oEnd){ return oEnd; }else{ return this._getBlockEndNode(oStart.nextSibling, oEnd); } }, _wrapBlock : function(oEvent, sWrapperTagName){ var oSelection = this.oApp.getSelection(), sBM = oSelection.placeStringBookmark(), oLineInfo = oSelection.getLineInfo(), oStart = oLineInfo.oStart, oEnd = oLineInfo.oEnd, oSWrapper, oEWrapper, elStyleOnlyNode; // line broke by sibling // or // the parent line breaker is just a block container if(!oStart.bParentBreak || oSelection.rxBlockContainer.test(oStart.oLineBreaker.tagName)){ oEvent.stop(); // 선택된 내용은 삭제 oSelection.deleteContents(); if(!!oStart.oNode.parentNode && oStart.oNode.parentNode.nodeType !== 11){ // LineBreaker 로 감싸서 분리 oSWrapper = this.oApp.getWYSIWYGDocument().createElement(this.sLineBreaker); oSelection.moveToBookmark(sBM); //oSelection.moveToStringBookmark(sBM, true); oSelection.setStartBefore(oStart.oNode); this._addBlankText(oSelection); oSelection.surroundContents(oSWrapper); oSelection.collapseToEnd(); oEWrapper = this.oApp.getWYSIWYGDocument().createElement(this.sLineBreaker); // [SMARTEDITORSUS-1513] oStart.oNode와 oEnd.oNode 사이에 BR이 있는 경우, 다음 엔터시 스타일이 비정상으로 복사되기 때문에 중간에 BR이 있으면 BR까지만 잘라서 세팅한다. oSelection.setEndAfter(this._getBlockEndNode(oStart.oNode, oEnd.oNode)); this._addBlankText(oSelection); oSelection.surroundContents(oEWrapper); oSelection.moveToStringBookmark(sBM, true); // [SMARTEDITORSUS-180] 포커스 리셋 oSelection.collapseToEnd(); // [SMARTEDITORSUS-180] 포커스 리셋 oSelection.removeStringBookmark(sBM); oSelection.select(); // P로 분리했기 때문에 BR이 들어있으면 제거한다. if(oEWrapper.lastChild !== null && oEWrapper.lastChild.tagName == "BR"){ oEWrapper.removeChild(oEWrapper.lastChild); } // Cursor Holder 추가 // insert a cursor holder(br) if there's an empty-styling-only-tag surrounding current cursor elStyleOnlyNode = this._addCursorHolder(oEWrapper); if(oEWrapper.nextSibling && oEWrapper.nextSibling.tagName == "BR"){ oEWrapper.parentNode.removeChild(oEWrapper.nextSibling); } oSelection.selectNodeContents(elStyleOnlyNode); oSelection.collapseToStart(); oSelection.select(); this.oApp.exec("CHECK_STYLE_CHANGE", []); sBM = oSelection.placeStringBookmark(); setTimeout(jindo.$Fn(function(sBM){ var elBookmark = oSelection.getStringBookmark(sBM); if(!elBookmark){return;} oSelection.moveToStringBookmark(sBM); oSelection.select(); oSelection.removeStringBookmark(sBM); }, this).bind(sBM), 0); return; } } var elBookmark; // 아래는 기본적으로 브라우저 기본 기능에 맡겨서 처리함 if(this.htBrowser.firefox){ elBookmark = oSelection.getStringBookmark(sBM, true); if(elBookmark && elBookmark.nextSibling && elBookmark.nextSibling.tagName == "IFRAME"){ setTimeout(jindo.$Fn(function(sBM){ var elBookmark = oSelection.getStringBookmark(sBM); if(!elBookmark){return;} oSelection.moveToStringBookmark(sBM); oSelection.select(); oSelection.removeStringBookmark(sBM); }, this).bind(sBM), 0); }else{ oSelection.removeStringBookmark(sBM); } }else if(this.htBrowser.ie){ elBookmark = oSelection.getStringBookmark(sBM, true); var elParentNode = elBookmark.parentNode, bAddUnderline = false, bAddLineThrough = false; if(!elBookmark || !elParentNode){// || elBookmark.nextSibling){ oSelection.removeStringBookmark(sBM); return; } oSelection.removeStringBookmark(sBM); // [SMARTEDITORSUS-1575] 이슈 처리에 따라 아래 부분은 불필요해졌음 (일단 코멘트처리) // // -- [SMARTEDITORSUS-1452] // var bAddCursorHolder = (elParentNode.tagName === "DIV" && elParentNode.parentNode.tagName === "LI"); // if (elParentNode.innerHTML !== "" && elParentNode.innerHTML !== unescape("%uFEFF")) { // if (bAddCursorHolder) { // // setTimeout(jindo.$Fn(function() { // var oSelection = this.oApp.getSelection(); // oSelection.fixCommonAncestorContainer(); // var elLowerNode = oSelection.commonAncestorContainer; // elLowerNode = oSelection._getVeryFirstRealChild(elLowerNode); // // if (elLowerNode && (elLowerNode.innerHTML === "" || elLowerNode.innerHTML === unescape("%uFEFF"))) { // elLowerNode.innerHTML = unescape("%uFEFF"); // } // }, this).bind(elParentNode), 0); // } // } else { // if (bAddCursorHolder) { // var oSelection = this.oApp.getSelection(); // oSelection.fixCommonAncestorContainer(); // var elLowerNode = oSelection.commonAncestorContainer; // elLowerNode = oSelection._getVeryFirstRealChild(elLowerNode); // jindo.$Element(elLowerNode).leave(); // // setTimeout(jindo.$Fn(function() { // var oSelection = this.oApp.getSelection(); // oSelection.fixCommonAncestorContainer(); // var elLowerNode = oSelection.commonAncestorContainer; // elLowerNode = oSelection._getVeryFirstRealChild(elLowerNode); // // if (elLowerNode && (elLowerNode.innerHTML === "" || elLowerNode.innerHTML === unescape("%uFEFF"))) { // elLowerNode.innerHTML = unescape("%uFEFF"); // } // }, this).bind(elParentNode), 0); // } // } // // -- [SMARTEDITORSUS-1452] bAddUnderline = (elParentNode.tagName === "U" || nhn.husky.SE2M_Utils.findAncestorByTagName("U", elParentNode) !== null); bAddLineThrough = (elParentNode.tagName === "S" || elParentNode.tagName === "STRIKE" || (nhn.husky.SE2M_Utils.findAncestorByTagName("S", elParentNode) !== null && nhn.husky.SE2M_Utils.findAncestorByTagName("STRIKE", elParentNode) !== null)); // [SMARTEDITORSUS-26] Enter 후에 밑줄/취소선이 복사되지 않는 문제를 처리 (브라우저 Enter 처리 후 실행되도록 setTimeout 사용) if(bAddUnderline || bAddLineThrough){ setTimeout(jindo.$Fn(this._addTextDecorationTag, this).bind(bAddUnderline, bAddLineThrough), 0); return; } // [SMARTEDITORSUS-180] 빈 SPAN 태그에 의해 엔터 후 엔터가 되지 않은 것으로 보이는 문제 (브라우저 Enter 처리 후 실행되도록 setTimeout 사용) setTimeout(jindo.$Fn(this._addExtraCursorHolder, this).bind(elParentNode), 0); }else{ oSelection.removeStringBookmark(sBM); } }, // [IE9 standard mode] 엔터 후의 상/하단 P 태그를 확인하여 BOM, 공백(&nbsp;) 추가 _addExtraCursorHolder : function(elUpperNode){ var oNodeChild, oPrevChild, elHtml; elUpperNode = this._getStyleOnlyNode(elUpperNode); // 엔터 후의 상단 SPAN 노드에 BOM 추가 //if(!!elUpperNode && /^(B|EM|I|LABEL|SPAN|STRONG|SUB|SUP|U|STRIKE)$/.test(elUpperNode.tagName) === false){ if(!!elUpperNode && elUpperNode.tagName === "SPAN"){ // SPAN 인 경우에만 발생함 oNodeChild = elUpperNode.lastChild; while(!!oNodeChild){ // 빈 Text 제거 oPrevChild = oNodeChild.previousSibling; if(oNodeChild.nodeType !== 3){ oNodeChild = oPrevChild; continue; } if(nhn.husky.SE2M_Utils.isBlankTextNode(oNodeChild)){ oNodeChild.parentNode.removeChild(oNodeChild); } oNodeChild = oPrevChild; } elHtml = elUpperNode.innerHTML; if(elHtml.replace("\u200B","").replace("\uFEFF","") === ""){ elUpperNode.innerHTML = "\u200B"; } } // 엔터 후에 비어있는 하단 SPAN 노드에 BOM 추가 var oSelection = this.oApp.getSelection(), sBM, elLowerNode, elParent; if(!oSelection.collapsed){ return; } oSelection.fixCommonAncestorContainer(); elLowerNode = oSelection.commonAncestorContainer; if(!elLowerNode){ return; } elLowerNode = oSelection._getVeryFirstRealChild(elLowerNode); if(elLowerNode.nodeType === 3){ elLowerNode = elLowerNode.parentNode; } if(!elLowerNode || elLowerNode.tagName !== "SPAN"){ return; } elHtml = elLowerNode.innerHTML; if(elHtml.replace("\u200B","").replace("\uFEFF","") === ""){ elLowerNode.innerHTML = "\u200B"; } // 백스페이스시 커서가 움직이지 않도록 커서를 커서홀더 앞쪽으로 옮긴다. oSelection.selectNodeContents(elLowerNode); oSelection.collapseToStart(); oSelection.select(); }, // [IE] P 태그 가장 뒤 자식노드로 공백(&nbsp;)을 값으로 하는 텍스트 노드를 추가 _addSpace : function(elNode){ var tmpTextNode, elChild, elNextChild, bHasNBSP, aImgChild, elLastImg; if(!elNode){ return; } if(elNode.nodeType === 3){ return elNode.parentNode; } if(elNode.tagName !== "P"){ return elNode; } aImgChild = jindo.$Element(elNode).child(function(v){ return (v.$value().nodeType === 1 && v.$value().tagName === "IMG"); }, 1); if(aImgChild.length > 0){ elLastImg = aImgChild[aImgChild.length - 1].$value(); elChild = elLastImg.nextSibling; while(elChild){ elNextChild = elChild.nextSibling; if (elChild.nodeType === 3 && (elChild.nodeValue === "&nbsp;" || elChild.nodeValue === unescape("%u00A0") || elChild.nodeValue === "\u200B")) { elNode.removeChild(elChild); } elChild = elNextChild; } return elNode; } elChild = elNode.firstChild; elNextChild = elChild; bHasNBSP = false; while(elChild){ // &nbsp;를 붙일꺼니까 P 바로 아래의 "%uFEFF"는 제거함 elNextChild = elChild.nextSibling; if(elChild.nodeType === 3){ if(elChild.nodeValue === unescape("%uFEFF")){ elNode.removeChild(elChild); } if(!bHasNBSP && (elChild.nodeValue === "&nbsp;" || elChild.nodeValue === unescape("%u00A0") || elChild.nodeValue === "\u200B")){ bHasNBSP = true; } } elChild = elNextChild; } if(!bHasNBSP){ tmpTextNode = this.tmpTextNode.cloneNode(); elNode.appendChild(tmpTextNode); } return elNode; // [SMARTEDITORSUS-418] return 엘리먼트 추가 }, // [IE] 엔터 후에 취소선/밑줄 태그를 임의로 추가 (취소선/밑줄에 색상을 표시하기 위함) _addTextDecorationTag : function(bAddUnderline, bAddLineThrough){ var oTargetNode, oNewNode, oSelection = this.oApp.getSelection(); if(!oSelection.collapsed){ return; } oTargetNode = oSelection.startContainer; while(oTargetNode){ if(oTargetNode.nodeType === 3){ oTargetNode = nhn.DOMFix.parentNode(oTargetNode); break; } if(!oTargetNode.childNodes || oTargetNode.childNodes.length === 0){ // oTargetNode.innerHTML = "\u200B"; break; } oTargetNode = oTargetNode.firstChild; } if(!oTargetNode){ return; } if(oTargetNode.tagName === "U" || oTargetNode.tagName === "S" || oTargetNode.tagName === "STRIKE"){ return; } if(bAddUnderline){ oNewNode = oSelection._document.createElement("U"); oTargetNode.appendChild(oNewNode); oTargetNode = oNewNode; } if(bAddLineThrough){ oNewNode = oSelection._document.createElement("STRIKE"); oTargetNode.appendChild(oNewNode); } oNewNode.innerHTML = "\u200B"; oSelection.selectNodeContents(oNewNode); oSelection.collapseToEnd(); // End 로 해야 새로 생성된 노드 안으로 Selection 이 들어감 oSelection.select(); }, // returns inner-most styling node // -> returns span3 from <span1><span2><span3>aaa</span></span></span> _getStyleNode : function(elNode){ while(elNode.firstChild && this.oSelection._isBlankTextNode(elNode.firstChild)){ elNode.removeChild(elNode.firstChild); } var elFirstChild = elNode.firstChild; if(!elFirstChild){ return elNode; } if(elFirstChild.nodeType === 3 || (elFirstChild.nodeType === 1 && (elFirstChild.tagName == "IMG" || elFirstChild.tagName == "BR" || elFirstChild.tagName == "HR" || elFirstChild.tagName == "IFRAME"))){ return elNode; } return this._getStyleNode(elNode.firstChild); }, // returns inner-most styling only node if there's any. // -> returns span3 from <span1><span2><span3></span></span></span> _getStyleOnlyNode : function(elNode){ if(!elNode){ return null; } // the final styling node must allow appending children // -> this doesn't seem to work for FF if(!elNode.insertBefore){ return null; } if(elNode.tagName == "IMG" || elNode.tagName == "BR" || elNode.tagName == "HR" || elNode.tagName == "IFRAME"){ return null; } while(elNode.firstChild && this.oSelection._isBlankTextNode(elNode.firstChild)){ elNode.removeChild(elNode.firstChild); } if(elNode.childNodes.length>1){ return null; } if(!elNode.firstChild){ return elNode; } // [SMARTEDITORSUS-227] TEXT_NODE 가 return 되는 문제를 수정함. IE 에서 TEXT_NODE 의 innrHTML 에 접근하면 오류 발생 if(elNode.firstChild.nodeType === 3){ return nhn.husky.SE2M_Utils.isBlankTextNode(elNode.firstChild) ? elNode : null; //return (elNode.firstChild.textContents === null || elNode.firstChild.textContents === "") ? elNode : null; } return this._getStyleOnlyNode(elNode.firstChild); }, _insertBR : function(oEvent){ oEvent.stop(); var oSelection = this.oApp.getSelection(); var elBR = this.oApp.getWYSIWYGDocument().createElement("BR"); oSelection.insertNode(elBR); oSelection.selectNode(elBR); oSelection.collapseToEnd(); if(!this.htBrowser.ie){ var oLineInfo = oSelection.getLineInfo(); var oEnd = oLineInfo.oEnd; // line break by Parent // <div> 1234<br></div>인경우, FF에서는 다음 라인으로 커서 이동이 안 일어남. // 그래서 <div> 1234<br><br type='_moz'/></div> 이와 같이 생성해주어야 에디터 상에 2줄로 되어 보임. if(oEnd.bParentBreak){ while(oEnd.oNode && oEnd.oNode.nodeType == 3 && oEnd.oNode.nodeValue == ""){ oEnd.oNode = oEnd.oNode.previousSibling; } var nTmp = 1; if(oEnd.oNode == elBR || oEnd.oNode.nextSibling == elBR){ nTmp = 0; } if(nTmp === 0){ oSelection.pasteHTML("<br type='_moz'/>"); oSelection.collapseToEnd(); } } } // the text cursor won't move to the next line without this oSelection.insertNode(this.oApp.getWYSIWYGDocument().createTextNode("")); oSelection.select(); } }); //} /** * ColorPicker Component * @author gony */ nhn.ColorPicker = jindo.$Class({ elem : null, huePanel : null, canvasType : "Canvas", _hsvColor : null, $init : function(oElement, oOptions) { this.elem = jindo.$Element(oElement).empty(); this.huePanel = null; this.cursor = jindo.$Element("<div>").css("overflow", "hidden"); this.canvasType = jindo.$(oElement).filters?"Filter":jindo.$("<canvas>").getContext?"Canvas":null; if(!this.canvasType) { return false; } this.option({ huePanel : null, huePanelType : "horizontal" }); this.option(oOptions); if (this.option("huePanel")) { this.huePanel = jindo.$Element(this.option("huePanel")).empty(); } // rgb this._hsvColor = this._hsv(0,100,100); // #FF0000 // event binding for(var name in this) { if (/^_on[A-Z][a-z]+[A-Z][a-z]+$/.test(name)) { this[name+"Fn"] = jindo.$Fn(this[name], this); } } this._onDownColorFn.attach(this.elem, "mousedown"); if (this.huePanel) { this._onDownHueFn.attach(this.huePanel, "mousedown"); } // paint this.paint(); }, rgb : function(rgb) { this.hsv(this._rgb2hsv(rgb.r, rgb.g, rgb.b)); }, hsv : function(hsv) { if (typeof hsv == "undefined") { return this._hsvColor; } var rgb = null; var w = this.elem.width(); var h = this.elem.height(); var cw = this.cursor.width(); var ch = this.cursor.height(); var x = 0, y = 0; if (this.huePanel) { rgb = this._hsv2rgb(hsv.h, 100, 100); this.elem.css("background", "#"+this._rgb2hex(rgb.r, rgb.g, rgb.b)); x = hsv.s/100 * w; y = (100-hsv.v)/100 * h; } else { var hw = w / 2; if (hsv.v > hsv.s) { hsv.v = 100; x = hsv.s/100 * hw; } else { hsv.s = 100; x = (100-hsv.v)/100 * hw + hw; } y = hsv.h/360 * h; } x = Math.max(Math.min(x-1,w-cw), 1); y = Math.max(Math.min(y-1,h-ch), 1); this.cursor.css({left:x+"px",top:y+"px"}); this._hsvColor = hsv; rgb = this._hsv2rgb(hsv.h, hsv.s, hsv.v); this.fireEvent("colorchange", {type:"colorchange", element:this, currentElement:this, rgbColor:rgb, hexColor:"#"+this._rgb2hex(rgb.r, rgb.g, rgb.b), hsvColor:hsv} ); }, paint : function() { if (this.huePanel) { // paint color panel this["_paintColWith"+this.canvasType](); // paint hue panel this["_paintHueWith"+this.canvasType](); } else { // paint color panel this["_paintOneWith"+this.canvasType](); } // draw cursor this.cursor.appendTo(this.elem); this.cursor.css({position:"absolute",top:"1px",left:"1px",background:"white",border:"1px solid black"}).width(3).height(3); this.hsv(this._hsvColor); }, _paintColWithFilter : function() { // white : left to right jindo.$Element("<div>").css({ position : "absolute", top : 0, left : 0, width : "100%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=1,StartColorStr='#FFFFFFFF',EndColorStr='#00FFFFFF')" }).appendTo(this.elem); // black : down to up jindo.$Element("<div>").css({ position : "absolute", top : 0, left : 0, width : "100%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#00000000',EndColorStr='#FF000000')" }).appendTo(this.elem); }, _paintColWithCanvas : function() { var cvs = jindo.$Element("<canvas>").css({width:"100%",height:"100%"}); cvs.appendTo(this.elem.empty()); var ctx = cvs.attr("width", cvs.width()).attr("height", cvs.height()).$value().getContext("2d"); var lin = null; var w = cvs.width(); var h = cvs.height(); // white : left to right lin = ctx.createLinearGradient(0,0,w,0); lin.addColorStop(0, "rgba(255,255,255,1)"); lin.addColorStop(1, "rgba(255,255,255,0)"); ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); // black : down to top lin = ctx.createLinearGradient(0,0,0,h); lin.addColorStop(0, "rgba(0,0,0,0)"); lin.addColorStop(1, "rgba(0,0,0,1)"); ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); }, _paintOneWithFilter : function() { var sp, ep, s_rgb, e_rgb, s_hex, e_hex; var h = this.elem.height(); for(var i=1; i < 7; i++) { sp = Math.floor((i-1)/6 * h); ep = Math.floor(i/6 * h); s_rgb = this._hsv2rgb((i-1)/6*360, 100, 100); e_rgb = this._hsv2rgb(i/6*360, 100, 100); s_hex = "#FF"+this._rgb2hex(s_rgb.r, s_rgb.g, s_rgb.b); e_hex = "#FF"+this._rgb2hex(e_rgb.r, e_rgb.g, e_rgb.b); jindo.$Element("<div>").css({ position : "absolute", left : 0, width : "100%", top : sp + "px", height : (ep-sp) + "px", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='"+s_hex+"',EndColorStr='"+e_hex+"')" }).appendTo(this.elem); } // white : left to right jindo.$Element("<div>").css({ position : "absolute", top : 0, left : 0, width : "50%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=1,StartColorStr='#FFFFFFFF',EndColorStr='#00FFFFFF')" }).appendTo(this.elem); // black : down to up jindo.$Element("<div>").css({ position : "absolute", top : 0, right : 0, width : "50%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=1,StartColorStr='#00000000',EndColorStr='#FF000000')" }).appendTo(this.elem); }, _paintOneWithCanvas : function() { var rgb = {r:0, g:0, b:0}; var cvs = jindo.$Element("<canvas>").css({width:"100%",height:"100%"}); cvs.appendTo(this.elem.empty()); var ctx = cvs.attr("width", cvs.width()).attr("height", cvs.height()).$value().getContext("2d"); var w = cvs.width(); var h = cvs.height(); var lin = ctx.createLinearGradient(0,0,0,h); for(var i=0; i < 7; i++) { rgb = this._hsv2rgb(i/6*360, 100, 100); lin.addColorStop(i/6, "rgb("+rgb.join(",")+")"); } ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); lin = ctx.createLinearGradient(0,0,w,0); lin.addColorStop(0, "rgba(255,255,255,1)"); lin.addColorStop(0.5, "rgba(255,255,255,0)"); lin.addColorStop(0.5, "rgba(0,0,0,0)"); lin.addColorStop(1, "rgba(0,0,0,1)"); ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); }, _paintHueWithFilter : function() { var sp, ep, s_rgb, e_rgb, s_hex, e_hex; var vert = (this.option().huePanelType == "vertical"); var w = this.huePanel.width(); var h = this.huePanel.height(); var elDiv = null; var nPanelBorderWidth = parseInt(this.huePanel.css('borderWidth'), 10); if (!!isNaN(nPanelBorderWidth)) { nPanelBorderWidth = 0; } w -= nPanelBorderWidth * 2; // borderWidth를 제외한 내측 폭을 구함 for(var i=1; i < 7; i++) { sp = Math.floor((i-1)/6 * (vert?h:w)); ep = Math.floor(i/6 * (vert?h:w)); s_rgb = this._hsv2rgb((i-1)/6*360, 100, 100); e_rgb = this._hsv2rgb(i/6*360, 100, 100); s_hex = "#FF"+this._rgb2hex(s_rgb.r, s_rgb.g, s_rgb.b); e_hex = "#FF"+this._rgb2hex(e_rgb.r, e_rgb.g, e_rgb.b); elDiv = jindo.$Element("<div>").css({ position : "absolute", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType="+(vert?0:1)+",StartColorStr='"+s_hex+"',EndColorStr='"+e_hex+"')" }); var width = (ep - sp) + 1; // IE에서 폭을 넓혀주지 않으면 확대 시 벌어짐, 그래서 1px 보정 elDiv.appendTo(this.huePanel); elDiv.css(vert?"left":"top", 0).css(vert?"width":"height", '100%'); elDiv.css(vert?"top":"left", sp + "px").css(vert?"height":"width", width + "px"); } }, _paintHueWithCanvas : function() { var opt = this.option(), rgb; var vtc = (opt.huePanelType == "vertical"); var cvs = jindo.$Element("<canvas>").css({width:"100%",height:"100%"}); cvs.appendTo(this.huePanel.empty()); var ctx = cvs.attr("width", cvs.width()).attr("height", cvs.height()).$value().getContext("2d"); var lin = ctx.createLinearGradient(0,0,vtc?0:cvs.width(),vtc?cvs.height():0); for(var i=0; i < 7; i++) { rgb = this._hsv2rgb(i/6*360, 100, 100); lin.addColorStop(i/6, "rgb("+rgb.join(",")+")"); } ctx.fillStyle = lin; ctx.fillRect(0,0,cvs.width(),cvs.height()); }, _rgb2hsv : function(r,g,b) { var h = 0, s = 0, v = Math.max(r,g,b), min = Math.min(r,g,b), delta = v - min; s = (v ? delta/v : 0); if (s) { if (r == v) { h = 60 * (g - b) / delta; } else if (g == v) { h = 120 + 60 * (b - r) / delta; } else if (b == v) { h = 240 + 60 * (r - g) / delta; } if (h < 0) { h += 360; } } h = Math.floor(h); s = Math.floor(s * 100); v = Math.floor(v / 255 * 100); return this._hsv(h,s,v); }, _hsv2rgb : function(h,s,v) { h = (h % 360) / 60; s /= 100; v /= 100; var r=0, g=0, b=0; var i = Math.floor(h); var f = h-i; var p = v*(1-s); var q = v*(1-s*f); var t = v*(1-s*(1-f)); switch (i) { case 0: r=v; g=t; b=p; break; case 1: r=q; g=v; b=p; break; case 2: r=p; g=v; b=t; break; case 3: r=p; g=q; b=v; break; case 4: r=t; g=p; b=v; break; case 5: r=v; g=p; b=q;break; case 6: break; } r = Math.floor(r*255); g = Math.floor(g*255); b = Math.floor(b*255); return this._rgb(r,g,b); }, _rgb2hex : function(r,g,b) { r = r.toString(16); if (r.length == 1) { r = '0'+r; } g = g.toString(16); if (g.length==1) { g = '0'+g; } b = b.toString(16); if (b.length==1) { b = '0'+b; } return r+g+b; }, _hex2rgb : function(hex) { var m = hex.match(/#?([0-9a-f]{6}|[0-9a-f]{3})/i); if (m[1].length == 3) { m = m[1].match(/./g).filter(function(c) { return c+c; }); } else { m = m[1].match(/../g); } return { r : Number("0x" + m[0]), g : Number("0x" + m[1]), b : Number("0x" + m[2]) }; }, _rgb : function(r,g,b) { var ret = [r,g,b]; ret.r = r; ret.g = g; ret.b = b; return ret; }, _hsv : function(h,s,v) { var ret = [h,s,v]; ret.h = h; ret.s = s; ret.v = v; return ret; }, _onDownColor : function(e) { if (!e.mouse().left) { return false; } var pos = e.pos(); this._colPagePos = [pos.pageX, pos.pageY]; this._colLayerPos = [pos.layerX, pos.layerY]; this._onUpColorFn.attach(document, "mouseup"); this._onMoveColorFn.attach(document, "mousemove"); this._onMoveColor(e); }, _onUpColor : function(e) { this._onUpColorFn.detach(document, "mouseup"); this._onMoveColorFn.detach(document, "mousemove"); }, _onMoveColor : function(e) { var hsv = this._hsvColor; var pos = e.pos(); var x = this._colLayerPos[0] + (pos.pageX - this._colPagePos[0]); var y = this._colLayerPos[1] + (pos.pageY - this._colPagePos[1]); var w = this.elem.width(); var h = this.elem.height(); x = Math.max(Math.min(x, w), 0); y = Math.max(Math.min(y, h), 0); if (this.huePanel) { hsv.s = hsv[1] = x / w * 100; hsv.v = hsv[2] = (h - y) / h * 100; } else { hsv.h = y/h*360; var hw = w/2; if (x < hw) { hsv.s = x/hw * 100; hsv.v = 100; } else { hsv.s = 100; hsv.v = (w-x)/hw * 100; } } this.hsv(hsv); e.stop(); }, _onDownHue : function(e) { if (!e.mouse().left) { return false; } var pos = e.pos(); this._huePagePos = [pos.pageX, pos.pageY]; this._hueLayerPos = [pos.layerX, pos.layerY]; this._onUpHueFn.attach(document, "mouseup"); this._onMoveHueFn.attach(document, "mousemove"); this._onMoveHue(e); }, _onUpHue : function(e) { this._onUpHueFn.detach(document, "mouseup"); this._onMoveHueFn.detach(document, "mousemove"); }, _onMoveHue : function(e) { var hsv = this._hsvColor; var pos = e.pos(); var cur = 0, len = 0; var x = this._hueLayerPos[0] + (pos.pageX - this._huePagePos[0]); var y = this._hueLayerPos[1] + (pos.pageY - this._huePagePos[1]); if (this.option().huePanelType == "vertical") { cur = y; len = this.huePanel.height(); } else { cur = x; len = this.huePanel.width(); } hsv.h = hsv[0] = (Math.min(Math.max(cur, 0), len)/len * 360)%360; this.hsv(hsv); e.stop(); } }).extend(jindo.Component); //{ /** * @fileOverview This file contains Husky plugin that takes care of Accessibility about SmartEditor2. * @name hp_SE2M_Accessibility.js */ nhn.husky.SE2M_Accessibility = jindo.$Class({ name : "SE2M_Accessibility", /* * elAppContainer : mandatory * sLocale, sEditorType : optional */ $init: function(elAppContainer, sLocale, sEditorType) { this._assignHTMLElements(elAppContainer); if(!!sLocale){ this.sLang = sLocale; } if(!!sEditorType){ this.sType = sEditorType; } }, _assignHTMLElements : function(elAppContainer){ this.elHelpPopupLayer = jindo.$$.getSingle("DIV.se2_accessibility", elAppContainer); this.welHelpPopupLayer = jindo.$Element(this.elHelpPopupLayer); //close buttons this.oCloseButton = jindo.$$.getSingle("BUTTON.se2_close", this.elHelpPopupLayer); this.oCloseButton2 = jindo.$$.getSingle("BUTTON.se2_close2", this.elHelpPopupLayer); this.nDefaultTop = 150; // [SMARTEDITORSUS-1594] 포커스 탐색에 사용하기 위해 할당 this.elAppContainer = elAppContainer; // --[SMARTEDITORSUS-1594] }, $ON_MSG_APP_READY : function(){ this.htAccessOption = nhn.husky.SE2M_Configuration.SE2M_Accessibility || {}; this.oApp.exec("REGISTER_HOTKEY", ["alt+F10", "FOCUS_TOOLBAR_AREA", []]); this.oApp.exec("REGISTER_HOTKEY", ["alt+COMMA", "FOCUS_BEFORE_ELEMENT", []]); this.oApp.exec("REGISTER_HOTKEY", ["alt+PERIOD", "FOCUS_NEXT_ELEMENT", []]); if ((this.sType == 'basic' || this.sType == 'light') && (this.sLang != 'ko_KR')) { //do nothing return; } else { this.oApp.exec("REGISTER_HOTKEY", ["alt+0", "OPEN_HELP_POPUP", []]); //[SMARTEDITORSUS-1327] IE 7/8에서 ALT+0으로 팝업 띄우고 esc클릭시 팝업창 닫히게 하려면 아래 부분 꼭 필요함. (target은 document가 되어야 함!) this.oApp.exec("REGISTER_HOTKEY", ["esc", "CLOSE_HELP_POPUP", [], document]); } //[SMARTEDITORSUS-1353] if (this.htAccessOption.sTitleElementId) { this.oApp.registerBrowserEvent(document.getElementById(this.htAccessOption.sTitleElementId), "keydown", "MOVE_TO_EDITAREA", []); } }, $ON_MOVE_TO_EDITAREA : function(weEvent) { var TAB_KEY_CODE = 9; if (weEvent.key().keyCode == TAB_KEY_CODE) { if(weEvent.key().shift) {return;} this.oApp.delayedExec("FOCUS", [], 0); } }, $LOCAL_BEFORE_FIRST : function(sMsg){ jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("CLOSE_HELP_POPUP", [this.oCloseButton]), this).attach(this.oCloseButton, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("CLOSE_HELP_POPUP", [this.oCloseButton2]), this).attach(this.oCloseButton2, "click"); //레이어의 이동 범위 설정. var elIframe = this.oApp.getWYSIWYGWindow().frameElement; this.htOffsetPos = jindo.$Element(elIframe).offset(); this.nEditorWidth = elIframe.offsetWidth; this.htInitialPos = this.welHelpPopupLayer.offset(); var htScrollXY = this.oApp.oUtils.getScrollXY(); this.nLayerWidth = 590; this.nLayerHeight = 480; this.htTopLeftCorner = {x:parseInt(this.htOffsetPos.left, 10), y:parseInt(this.htOffsetPos.top, 10)}; //[css markup] left:11 top:74로 되어 있음 }, /** * [SMARTEDITORSUS-1594] * SE2M_Configuration_General에서 포커스를 이동할 에디터 영역 이후의 엘레먼트를 지정해 두었다면, 설정값을 따른다. * 지정하지 않았거나 빈 String이라면, elAppContainer를 기준으로 자동 탐색한다. * */ $ON_FOCUS_NEXT_ELEMENT : function() { // 포커스 캐싱 this._currentNextFocusElement = null; // 새로운 포커스 이동이 발생할 때마다 캐싱 초기화 if(this.htAccessOption.sNextElementId){ this._currentNextFocusElement = document.getElementById(this.htAccessOption.sNextElementId); }else{ this._currentNextFocusElement = this._findNextFocusElement(this.elAppContainer); } if(this._currentNextFocusElement){ window.focus(); // [SMARTEDITORSUS-1360] IE7에서는 element에 대한 focus를 주기 위해 선행되어야 한다. this._currentNextFocusElement.focus(); }else if(parent && parent.nhn && parent.nhn.husky && parent.nhn.husky.EZCreator && parent.nhn.husky.EZCreator.elIFrame){ parent.focus(); if(this._currentNextFocusElement = this._findNextFocusElement(parent.nhn.husky.EZCreator.elIFrame)){ this._currentNextFocusElement.focus(); } } }, /** * [SMARTEDITORSUS-1594] DIV#smart_editor2 다음 요소에서 가장 가까운 포커스용 태그를 탐색 * */ _findNextFocusElement : function(targetElement){ var target = null; var el = targetElement.nextSibling; while(el){ if(el.nodeType !== 1){ // Element Node만을 대상으로 한다. // 대상 노드 대신 nextSibling을 찾되, 부모를 거슬러 올라갈 수도 있다. // document.body까지 거슬러 올라가게 되면 탐색 종료 el = this._switchToSiblingOrNothing(el); if(!el){ break; }else{ continue; } } // 대상 노드를 기준으로, 전위순회로 조건에 부합하는 노드 탐색 this._recursivePreorderTraversalFilter(el, this._isFocusTag); if(this._nextFocusElement){ target = this._nextFocusElement; // 탐색에 사용했던 변수 초기화 this._bStopFindingNextElement = false; this._nextFocusElement = null; break; }else{ // 대상 노드 대신 nextSibling을 찾되, 부모를 거슬러 올라갈 수도 있다. // document.body까지 거슬러 올라가게 되면 탐색 종료 el = this._switchToSiblingOrNothing(el); if(!el){ break; } } } // target이 존재하지 않으면 null 반환 return target; }, /** * [SMARTEDITORSUS-1594] 대상 노드를 기준으로 하여, nextSibling 또는 previousSibling을 찾는다. * nextSibling 또는 previousSibling이 없다면, * 부모를 거슬러 올라가면서 첫 nextSibling 또는 previousSibling을 찾는다. * document의 body까지 올라가도 nextSibling 또는 previousSibling이 나타나지 않는다면 * 탐색 대상으로 null을 반환한다. * @param {NodeElement} 대상 노드 (주의:NodeElement에 대한 null 체크 안함) * @param {Boolean} 생략하거나 false이면 nextSibling을 찾고, true이면 previousSibling을 찾는다. * */ _switchToSiblingOrNothing : function(targetElement, isPreviousOrdered){ var el = targetElement; if(isPreviousOrdered){ if(el.previousSibling){ el = el.previousSibling; }else{ // 형제가 없다면 부모를 거슬러 올라가면서 탐색 // 이 루프의 종료 조건 // 1. 부모를 거슬러 올라가다가 el이 document.body가 되는 시점 // - 더 이상 previousSibling을 탐색할 수 없음 // 2. el이 부모로 대체된 뒤 previousSibling이 존재하는 경우 while(el.nodeName.toUpperCase() != "BODY" && !el.previousSibling){ el = el.parentNode; } if(el.nodeName.toUpperCase() == "BODY"){ el = null; }else{ el = el.previousSibling; } } }else{ if(el.nextSibling){ el = el.nextSibling; }else{ // 형제가 없다면 부모를 거슬러 올라가면서 탐색 // 이 루프의 종료 조건 // 1. 부모를 거슬러 올라가다가 el이 document.body가 되는 시점 // - 더 이상 nextSibling을 탐색할 수 없음 // 2. el이 부모로 대체된 뒤 nextSibling이 존재하는 경우 while(el.nodeName.toUpperCase() != "BODY" && !el.nextSibling){ el = el.parentNode; } if(el.nodeName.toUpperCase() == "BODY"){ el = null; }else{ el = el.nextSibling; } } } return el; }, /** * [SMARTEDITORSUS-1594] 대상 노드를 기준으로 하는 트리를 전위순회를 거쳐, 필터 조건에 부합하는 첫 노드를 찾는다. * @param {NodeElement} 탐색하려는 트리의 루트 노드 * @param {Function} 필터 조건으로 사용할 함수 * @param {Boolean} 생략하거나 false이면 순수 전위순회(루트 - 좌측 - 우측 순)로 탐색하고, true이면 반대 방향의 전위순회(루트 - 우측 - 좌측)로 탐색한다. * */ _recursivePreorderTraversalFilter : function(node, filterFunction, isReversed){ var self = this; // 현재 노드를 기준으로 필터링 var _bStopFindingNextElement = filterFunction.apply(node); if(_bStopFindingNextElement){ // 최초로 포커스 태그를 찾는다면 탐색 중단용 flag 변경 self._bStopFindingNextElement = true; if(isReversed){ self._previousFocusElement = node; }else{ self._nextFocusElement = node; } return; }else{ // 필터링 조건에 부합하지 않는다면, 자식들을 기준으로 반복하게 된다. if(isReversed){ for(var len = node.childNodes.length, i = len - 1; i >= 0; i--){ self._recursivePreorderTraversalFilter(node.childNodes[i], filterFunction, true); if(!!this._bStopFindingNextElement){ break; } } }else{ for(var i=0, len = node.childNodes.length; i < len; i++){ self._recursivePreorderTraversalFilter(node.childNodes[i], filterFunction); if(!!this._bStopFindingNextElement){ break; } } } } }, /** * [SMARTEDITORSUS-1594] 필터 함수로, 이 노드가 tab 키로 포커스를 이동하는 태그에 해당하는지 확인한다. * */ _isFocusTag : function(){ var self = this; // tab 키로 포커스를 잡아주는 태그 목록 var aFocusTagViaTabKey = ["A", "BUTTON", "INPUT", "TEXTAREA"]; // 포커스 태그가 현재 노드에 존재하는지 확인하기 위한 flag var bFocusTagExists = false; for(var i = 0, len = aFocusTagViaTabKey.length; i < len; i++){ if(self.nodeType === 1 && self.nodeName && self.nodeName.toUpperCase() == aFocusTagViaTabKey[i] && !self.disabled && jindo.$Element(self).visible()){ bFocusTagExists = true; break; } } return bFocusTagExists; }, /** * [SMARTEDITORSUS-1594] * SE2M_Configuration_General에서 포커스를 이동할 에디터 영역 이전의 엘레먼트를 지정해 두었다면, 설정값을 따른다. * 지정하지 않았거나 빈 String이라면, elAppContainer를 기준으로 자동 탐색한다. * */ $ON_FOCUS_BEFORE_ELEMENT : function() { // 포커스 캐싱 this._currentPreviousFocusElement = null; // 새로운 포커스 이동이 발생할 때마다 캐싱 초기화 if(this.htAccessOption.sBeforeElementId){ this._currentPreviousFocusElement = document.getElementById(this.htAccessOption.sBeforeElementId); }else{ this._currentPreviousFocusElement = this._findPreviousFocusElement(this.elAppContainer); // 삽입될 대상 } if(this._currentPreviousFocusElement){ window.focus(); // [SMARTEDITORSUS-1360] IE7에서는 element에 대한 focus를 주기 위해 선행되어야 한다. this._currentPreviousFocusElement.focus(); }else if(parent && parent.nhn && parent.nhn.husky && parent.nhn.husky.EZCreator && parent.nhn.husky.EZCreator.elIFrame){ parent.focus(); if(this._currentPreviousFocusElement = this._findPreviousFocusElement(parent.nhn.husky.EZCreator.elIFrame)){ this._currentPreviousFocusElement.focus(); } } }, /** * [SMARTEDITORSUS-1594] DIV#smart_editor2 이전 요소에서 가장 가까운 포커스용 태그를 탐색 * */ _findPreviousFocusElement : function(targetElement){ var target = null; var el = targetElement.previousSibling; while(el){ if(el.nodeType !== 1){ // Element Node만을 대상으로 한다. // 대상 노드 대신 previousSibling을 찾되, 부모를 거슬러 올라갈 수도 있다. // document.body까지 거슬러 올라가게 되면 탐색 종료 el = this._switchToSiblingOrNothing(el, /*isReversed*/true); if(!el){ break; }else{ continue; } } // 대상 노드를 기준으로, 역 전위순회로 조건에 부합하는 노드 탐색 this._recursivePreorderTraversalFilter(el, this._isFocusTag, true); if(this._previousFocusElement){ target = this._previousFocusElement; // 탐색에 사용했던 변수 초기화 this._bStopFindingNextElement = false; this._previousFocusElement = null; break; }else{ // 대상 노드 대신 previousSibling을 찾되, 부모를 거슬러 올라갈 수도 있다. // document.body까지 거슬러 올라가게 되면 탐색 종료 el = this._switchToSiblingOrNothing(el, /*isReversed*/true); if(!el){ break; } } } // target이 존재하지 않으면 null 반환 return target; }, $ON_FOCUS_TOOLBAR_AREA : function(){ this.oButton = jindo.$$.getSingle("BUTTON.se2_font_family", this.elAppContainer); if(this.oButton && !this.oButton.disabled){ // [SMARTEDITORSUS-1369] IE9이하에서 disabled 요소에 포커스를 주면 오류 발생 window.focus(); this.oButton.focus(); } }, $ON_OPEN_HELP_POPUP : function() { this.oApp.exec("DISABLE_ALL_UI", [{aExceptions: ["se2_accessibility"]}]); this.oApp.exec("SHOW_EDITING_AREA_COVER"); this.oApp.exec("SELECT_UI", ["se2_accessibility"]); //아래 코드 없어야 블로그에서도 동일한 위치에 팝업 뜸.. //this.elHelpPopupLayer.style.top = this.nDefaultTop+"px"; this.nCalcX = this.htTopLeftCorner.x + this.oApp.getEditingAreaWidth() - this.nLayerWidth; this.nCalcY = this.htTopLeftCorner.y - 30; // 블로그버전이 아닌 경우 에디터영역을 벗어나는 문제가 있기 때문에 기본툴바(30px) 크기만큼 올려줌 this.oApp.exec("SHOW_DIALOG_LAYER", [this.elHelpPopupLayer, { elHandle: this.elTitle, nMinX : this.htTopLeftCorner.x + 0, nMinY : this.nDefaultTop + 77, nMaxX : this.nCalcX, nMaxY : this.nCalcY }]); // offset (nTop:Numeric, nLeft:Numeric) this.welHelpPopupLayer.offset(this.nCalcY, (this.nCalcX)/2); //[SMARTEDITORSUS-1327] IE에서 포커스 이슈로 IE에 대해서만 window.focus실행함. if(jindo.$Agent().navigator().ie) { window.focus(); } var self = this; setTimeout(function(){ try{ self.oCloseButton2.focus(); }catch(e){ } },200); }, $ON_CLOSE_HELP_POPUP : function() { this.oApp.exec("ENABLE_ALL_UI"); // 모든 UI 활성화. this.oApp.exec("DESELECT_UI", ["helpPopup"]); this.oApp.exec("HIDE_ALL_DIALOG_LAYER", []); this.oApp.exec("HIDE_EDITING_AREA_COVER"); // 편집 영역 활성화. this.oApp.exec("FOCUS"); } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of changing the background color * @name hp_SE2M_BGColor.js */ nhn.husky.SE2M_BGColor = jindo.$Class({ name : "SE2M_BGColor", rxColorPattern : /^#?[0-9a-fA-F]{6}$|^rgb\(\d+, ?\d+, ?\d+\)$/i, $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.elLastUsed = jindo.$$.getSingle("SPAN.husky_se2m_BGColor_lastUsed", elAppContainer); this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_BGColor_layer", elAppContainer); this.elBGColorList = jindo.$$.getSingle("UL.husky_se2m_bgcolor_list", elAppContainer); this.elPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_BGColor_paletteHolder", this.elDropdownLayer); //@ec] this._setLastUsedBGColor("#777777"); }, $BEFORE_MSG_APP_READY : function() { this.oApp.exec("ADD_APP_PROPERTY", ["getLastUsedBackgroundColor", jindo.$Fn(this.getLastUsedBGColor, this).bind()]); }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["BGColorA", "click", "APPLY_LAST_USED_BGCOLOR"]); this.oApp.exec("REGISTER_UI_EVENT", ["BGColorB", "click", "TOGGLE_BGCOLOR_LAYER"]); this.oApp.registerBrowserEvent(this.elBGColorList, "click", "EVENT_APPLY_BGCOLOR", []); }, //@lazyload_js APPLY_LAST_USED_BGCOLOR,TOGGLE_BGCOLOR_LAYER[ $ON_TOGGLE_BGCOLOR_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "BGCOLOR_LAYER_SHOWN", [], "BGCOLOR_LAYER_HIDDEN", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['bgcolor']); }, $ON_BGCOLOR_LAYER_SHOWN : function(){ this.oApp.exec("SELECT_UI", ["BGColorB"]); this.oApp.exec("SHOW_COLOR_PALETTE", ["APPLY_BGCOLOR", this.elPaletteHolder]); }, $ON_BGCOLOR_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["BGColorB"]); this.oApp.exec("RESET_COLOR_PALETTE", []); }, $ON_EVENT_APPLY_BGCOLOR : function(weEvent){ var elButton = weEvent.element; // Safari/Chrome/Opera may capture the event on Span while(elButton.tagName == "SPAN"){elButton = elButton.parentNode;} if(elButton.tagName != "BUTTON"){return;} var sBGColor, sFontColor; sBGColor = elButton.style.backgroundColor; sFontColor = elButton.style.color; this.oApp.exec("APPLY_BGCOLOR", [sBGColor, sFontColor]); }, $ON_APPLY_LAST_USED_BGCOLOR : function(){ this.oApp.exec("APPLY_BGCOLOR", [this.sLastUsedColor]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['bgcolor']); }, $ON_APPLY_BGCOLOR : function(sBGColor, sFontColor){ if(!this.rxColorPattern.test(sBGColor)){ alert(this.oApp.$MSG("SE_Color.invalidColorCode")); return; } this._setLastUsedBGColor(sBGColor); var oStyle = {"backgroundColor": sBGColor}; if(sFontColor){oStyle.color = sFontColor;} this.oApp.exec("SET_WYSIWYG_STYLE", [oStyle]); this.oApp.exec("HIDE_ACTIVE_LAYER"); }, //@lazyload_js] _setLastUsedBGColor : function(sBGColor){ this.sLastUsedColor = sBGColor; this.elLastUsed.style.backgroundColor = this.sLastUsedColor; }, getLastUsedBGColor : function(){ return (!!this.sLastUsedColor) ? this.sLastUsedColor : '#777777'; } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations directly related to the color palette * @name hp_SE2M_ColorPalette.js */ nhn.husky.SE2M_ColorPalette = jindo.$Class({ name : "SE2M_ColorPalette", elAppContainer : null, bUseRecentColor : false, nLimitRecentColor : 17, rxRGBColorPattern : /rgb\((\d+), ?(\d+), ?(\d+)\)/i, rxColorPattern : /^#?[0-9a-fA-F]{6}$|^rgb\(\d+, ?\d+, ?\d+\)$/i, aRecentColor : [], // 최근 사용한 색 목록, 가장 최근에 등록한 색의 index가 가장 작음 URL_COLOR_LIST : "", URL_COLOR_ADD : "", URL_COLOR_UPDATE : "", sRecentColorTemp : "<li><button type=\"button\" title=\"{RGB_CODE}\" style=\"background:{RGB_CODE}\"><span><span>{RGB_CODE}</span></span></button></li>", $init : function(elAppContainer){ this.elAppContainer = elAppContainer; }, $ON_MSG_APP_READY : function(){}, _assignHTMLElements : function(oAppContainer){ var htConfiguration = nhn.husky.SE2M_Configuration.SE2M_ColorPalette; if(htConfiguration){ this.bUseRecentColor = htConfiguration.bUseRecentColor || false; this.URL_COLOR_ADD = htConfiguration.addColorURL || "http://api.se2.naver.com/1/colortable/TextAdd.nhn"; this.URL_COLOR_UPDATE = htConfiguration.updateColorURL || "http://api.se2.naver.com/1/colortable/TextUpdate.nhn"; this.URL_COLOR_LIST = htConfiguration.colorListURL || "http://api.se2.naver.com/1/colortable/TextList.nhn"; } this.elColorPaletteLayer = jindo.$$.getSingle("DIV.husky_se2m_color_palette", oAppContainer); this.elColorPaletteLayerColorPicker = jindo.$$.getSingle("DIV.husky_se2m_color_palette_colorpicker", this.elColorPaletteLayer); this.elRecentColorForm = jindo.$$.getSingle("form", this.elColorPaletteLayerColorPicker); this.elBackgroundColor = jindo.$$.getSingle("ul.husky_se2m_bgcolor_list", oAppContainer); this.elInputColorCode = jindo.$$.getSingle("INPUT.husky_se2m_cp_colorcode", this.elColorPaletteLayerColorPicker); this.elPreview = jindo.$$.getSingle("SPAN.husky_se2m_cp_preview", this.elColorPaletteLayerColorPicker); this.elCP_ColPanel = jindo.$$.getSingle("DIV.husky_se2m_cp_colpanel", this.elColorPaletteLayerColorPicker); this.elCP_HuePanel = jindo.$$.getSingle("DIV.husky_se2m_cp_huepanel", this.elColorPaletteLayerColorPicker); this.elCP_ColPanel.style.position = "relative"; this.elCP_HuePanel.style.position = "relative"; this.elColorPaletteLayerColorPicker.style.display = "none"; this.elMoreBtn = jindo.$$.getSingle("BUTTON.husky_se2m_color_palette_more_btn", this.elColorPaletteLayer); this.welMoreBtn = jindo.$Element(this.elMoreBtn); this.elOkBtn = jindo.$$.getSingle("BUTTON.husky_se2m_color_palette_ok_btn", this.elColorPaletteLayer); if(this.bUseRecentColor){ this.elColorPaletteLayerRecent = jindo.$$.getSingle("DIV.husky_se2m_color_palette_recent", this.elColorPaletteLayer); this.elRecentColor = jindo.$$.getSingle("ul.se2_pick_color", this.elColorPaletteLayerRecent); this.elDummyNode = jindo.$$.getSingle("ul.se2_pick_color > li", this.elColorPaletteLayerRecent) || null; this.elColorPaletteLayerRecent.style.display = "none"; } }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLElements(this.elAppContainer); if(this.elDummyNode){ jindo.$Element(jindo.$$.getSingle("ul.se2_pick_color > li", this.elColorPaletteLayerRecent)).leave(); } if( this.bUseRecentColor ){ this._ajaxRecentColor(this._ajaxRecentColorCallback); } this.oApp.registerBrowserEvent(this.elColorPaletteLayer, "click", "EVENT_CLICK_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elBackgroundColor, "mouseover", "EVENT_MOUSEOVER_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elColorPaletteLayer, "mouseover", "EVENT_MOUSEOVER_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elBackgroundColor, "mouseout", "EVENT_MOUSEOUT_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elColorPaletteLayer, "mouseout", "EVENT_MOUSEOUT_COLOR_PALETTE"); }, $ON_EVENT_MOUSEOVER_COLOR_PALETTE : function(oEvent){ var elHovered = oEvent.element; while(elHovered && elHovered.tagName && elHovered.tagName.toLowerCase() != "li"){ elHovered = elHovered.parentNode; } //조건 추가-by cielo 2010.04.20 if(!elHovered || !elHovered.nodeType || elHovered.nodeType == 9){return;} if(elHovered.className == "" || (!elHovered.className) || typeof(elHovered.className) == 'undefined'){jindo.$Element(elHovered).addClass("hover");} }, $ON_EVENT_MOUSEOUT_COLOR_PALETTE : function(oEvent){ var elHovered = oEvent.element; while(elHovered && elHovered.tagName && elHovered.tagName.toLowerCase() != "li"){ elHovered = elHovered.parentNode; } if(!elHovered){return;} if(elHovered.className == "hover"){jindo.$Element(elHovered).removeClass("hover");} }, $ON_EVENT_CLICK_COLOR_PALETTE : function(oEvent){ var elClicked = oEvent.element; while(elClicked.tagName == "SPAN"){elClicked = elClicked.parentNode;} if(elClicked.tagName && elClicked.tagName == "BUTTON"){ if(elClicked == this.elMoreBtn){ this.oApp.exec("TOGGLE_COLOR_PICKER"); return; } this.oApp.exec("APPLY_COLOR", [elClicked]); } }, $ON_APPLY_COLOR : function(elButton){ var sColorCode = this.elInputColorCode.value, welColorParent = null; if(sColorCode.indexOf("#") == -1){ sColorCode = "#" + sColorCode; this.elInputColorCode.value = sColorCode; } // 입력 버튼인 경우 if(elButton == this.elOkBtn){ if(!this._verifyColorCode(sColorCode)){ this.elInputColorCode.value = ""; alert(this.oApp.$MSG("SE_Color.invalidColorCode")); this.elInputColorCode.focus(); return; } this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [sColorCode,true]); return; } // 색상 버튼인 경우 welColorParent = jindo.$Element(elButton.parentNode.parentNode.parentNode); sColorCode = elButton.title; if(welColorParent.hasClass("husky_se2m_color_palette")){ // 템플릿 색상 적용 this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [sColorCode, nhn.husky.SE2M_Configuration.SE2M_ColorPalette.bAddRecentColorFromDefault]); }else if(welColorParent.hasClass("husky_se2m_color_palette_recent")){ // 최근 색상 적용 this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [sColorCode,true]); } }, $ON_RESET_COLOR_PALETTE : function(){ this._initColor(); }, $ON_TOGGLE_COLOR_PICKER : function(){ if(this.elColorPaletteLayerColorPicker.style.display == "none"){ this.oApp.exec("SHOW_COLOR_PICKER"); }else{ this.oApp.exec("HIDE_COLOR_PICKER"); } }, $ON_SHOW_COLOR_PICKER : function(){ this.elColorPaletteLayerColorPicker.style.display = ""; this.cpp = new nhn.ColorPicker(this.elCP_ColPanel, {huePanel:this.elCP_HuePanel}); var fn = jindo.$Fn(function(oEvent) { this.elPreview.style.backgroundColor = oEvent.hexColor; this.elInputColorCode.value = oEvent.hexColor; }, this).bind(); this.cpp.attach("colorchange", fn); this.$ON_SHOW_COLOR_PICKER = this._showColorPickerMain; this.$ON_SHOW_COLOR_PICKER(); }, $ON_HIDE_COLOR_PICKER : function(){ this.elColorPaletteLayerColorPicker.style.display = "none"; this.welMoreBtn.addClass("se2_view_more"); this.welMoreBtn.removeClass("se2_view_more2"); }, $ON_SHOW_COLOR_PALETTE : function(sCallbackCmd, oLayerContainer){ this.sCallbackCmd = sCallbackCmd; this.oLayerContainer = oLayerContainer; this.oLayerContainer.insertBefore(this.elColorPaletteLayer, null); this.elColorPaletteLayer.style.display = "block"; this.oApp.delayedExec("POSITION_TOOLBAR_LAYER", [this.elColorPaletteLayer.parentNode.parentNode], 0); }, $ON_HIDE_COLOR_PALETTE : function(){ this.elColorPaletteLayer.style.display = "none"; }, $ON_COLOR_PALETTE_APPLY_COLOR : function(sColorCode , bAddRecentColor){ bAddRecentColor = (!bAddRecentColor)? false : bAddRecentColor; sColorCode = this._getHexColorCode(sColorCode); //더보기 레이어에서 적용한 색상만 최근 사용한 색에 추가한다. if( this.bUseRecentColor && !!bAddRecentColor ){ this.oApp.exec("ADD_RECENT_COLOR", [sColorCode]); } this.oApp.exec(this.sCallbackCmd, [sColorCode]); }, $ON_EVENT_MOUSEUP_COLOR_PALETTE : function(oEvent){ var elButton = oEvent.element; if(! elButton.style.backgroundColor){return;} this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [elButton.style.backgroundColor,false]); }, $ON_ADD_RECENT_COLOR : function(sRGBCode){ var bAdd = (this.aRecentColor.length === 0); this._addRecentColor(sRGBCode); if(bAdd){ this._ajaxAddColor(); }else{ this._ajaxUpdateColor(); } this._redrawRecentColorElement(); }, _verifyColorCode : function(sColorCode){ return this.rxColorPattern.test(sColorCode); }, _getHexColorCode : function(sColorCode){ if(this.rxRGBColorPattern.test(sColorCode)){ var dec2Hex = function(sDec){ var sTmp = parseInt(sDec, 10).toString(16); if(sTmp.length<2){sTmp = "0"+sTmp;} return sTmp.toUpperCase(); }; var sR = dec2Hex(RegExp.$1); var sG = dec2Hex(RegExp.$2); var sB = dec2Hex(RegExp.$3); sColorCode = "#"+sR+sG+sB; } return sColorCode; }, _addRecentColor : function(sRGBCode){ var waRecentColor = jindo.$A(this.aRecentColor); waRecentColor = waRecentColor.refuse(sRGBCode); waRecentColor.unshift(sRGBCode); if(waRecentColor.length() > this.nLimitRecentColor){ waRecentColor.length(this.nLimitRecentColor); } this.aRecentColor = waRecentColor.$value(); }, _redrawRecentColorElement : function(){ var aRecentColorHtml = [], nRecentColor = this.aRecentColor.length, i; if(nRecentColor === 0){ return; } for(i=0; i<nRecentColor; i++){ aRecentColorHtml.push(this.sRecentColorTemp.replace(/\{RGB_CODE\}/gi, this.aRecentColor[i])); } this.elRecentColor.innerHTML = aRecentColorHtml.join(""); this.elColorPaletteLayerRecent.style.display = "block"; }, _ajaxAddColor : function(){ jindo.$Ajax(this.URL_COLOR_ADD, { type : "jsonp", onload: function(){} }).request({ text_key : "colortable", text_data : this.aRecentColor.join(",") }); }, _ajaxUpdateColor : function(){ jindo.$Ajax(this.URL_COLOR_UPDATE, { type : "jsonp", onload: function(){} }).request({ text_key : "colortable", text_data : this.aRecentColor.join(",") }); }, _showColorPickerMain : function(){ this._initColor(); this.elColorPaletteLayerColorPicker.style.display = ""; this.welMoreBtn.removeClass("se2_view_more"); this.welMoreBtn.addClass("se2_view_more2"); }, _initColor : function(){ if(this.cpp){this.cpp.rgb({r:0,g:0,b:0});} this.elPreview.style.backgroundColor = '#'+'000000'; this.elInputColorCode.value = '#'+'000000'; this.oApp.exec("HIDE_COLOR_PICKER"); }, _ajaxRecentColor : function(fCallback){ jindo.$Ajax(this.URL_COLOR_LIST, { type : "jsonp", onload : jindo.$Fn(fCallback, this).bind() }).request(); }, _ajaxRecentColorCallback : function(htResponse){ var aColorList = htResponse.json()["result"], waColorList, i, nLen; if(!aColorList || !!aColorList.error){ return; } waColorList = jindo.$A(aColorList).filter(this._verifyColorCode, this); if(waColorList.length() > this.nLimitRecentColor){ waColorList.length(this.nLimitRecentColor); } aColorList = waColorList.reverse().$value(); for(i = 0, nLen = aColorList.length; i < nLen; i++){ this._addRecentColor(this._getHexColorCode(aColorList[i])); } this._redrawRecentColorElement(); } }).extend(jindo.Component); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the basic editor commands * @name hp_SE_ExecCommand.js */ nhn.husky.SE2M_ExecCommand = jindo.$Class({ name : "SE2M_ExecCommand", oEditingArea : null, oUndoOption : null, _rxTable : /^(?:TBODY|TR|TD)$/i, $init : function(oEditingArea){ this.oEditingArea = oEditingArea; this.nIndentSpacing = 40; this.rxClickCr = new RegExp('^bold|underline|italic|strikethrough|justifyleft|justifycenter|justifyright|justifyfull|insertorderedlist|insertunorderedlist|outdent|indent$', 'i'); }, $BEFORE_MSG_APP_READY : function(){ // the right document will be available only when the src is completely loaded if(this.oEditingArea && this.oEditingArea.tagName == "IFRAME"){ this.oEditingArea = this.oEditingArea.contentWindow.document; } }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_HOTKEY", ["ctrl+b", "EXECCOMMAND", ["bold", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+u", "EXECCOMMAND", ["underline", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+i", "EXECCOMMAND", ["italic", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+d", "EXECCOMMAND", ["strikethrough", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["meta+b", "EXECCOMMAND", ["bold", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["meta+u", "EXECCOMMAND", ["underline", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["meta+i", "EXECCOMMAND", ["italic", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["meta+d", "EXECCOMMAND", ["strikethrough", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["tab", "INDENT"]); this.oApp.exec("REGISTER_HOTKEY", ["shift+tab", "OUTDENT"]); //this.oApp.exec("REGISTER_HOTKEY", ["tab", "EXECCOMMAND", ["indent", false, false]]); //this.oApp.exec("REGISTER_HOTKEY", ["shift+tab", "EXECCOMMAND", ["outdent", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["bold", "click", "EXECCOMMAND", ["bold", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["underline", "click", "EXECCOMMAND", ["underline", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["italic", "click", "EXECCOMMAND", ["italic", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["lineThrough", "click", "EXECCOMMAND", ["strikethrough", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["superscript", "click", "EXECCOMMAND", ["superscript", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["subscript", "click", "EXECCOMMAND", ["subscript", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifyleft", "click", "EXECCOMMAND", ["justifyleft", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifycenter", "click", "EXECCOMMAND", ["justifycenter", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifyright", "click", "EXECCOMMAND", ["justifyright", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifyfull", "click", "EXECCOMMAND", ["justifyfull", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["orderedlist", "click", "EXECCOMMAND", ["insertorderedlist", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["unorderedlist", "click", "EXECCOMMAND", ["insertunorderedlist", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["outdent", "click", "EXECCOMMAND", ["outdent", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["indent", "click", "EXECCOMMAND", ["indent", false, false]]); // this.oApp.exec("REGISTER_UI_EVENT", ["styleRemover", "click", "EXECCOMMAND", ["RemoveFormat", false, false]]); this.oNavigator = jindo.$Agent().navigator(); if(!this.oNavigator.safari && !this.oNavigator.chrome){ this._getDocumentBR = function(){}; this._fixDocumentBR = function(){}; } if(!this.oNavigator.ie){ this._fixCorruptedBlockQuote = function(){}; if(!this.oNavigator.chrome){ this._insertBlankLine = function(){}; } } if(!this.oNavigator.firefox){ this._extendBlock = function(){}; } }, $ON_INDENT : function(){ this.oApp.delayedExec("EXECCOMMAND", ["indent", false, false], 0); }, $ON_OUTDENT : function(){ this.oApp.delayedExec("EXECCOMMAND", ["outdent", false, false], 0); }, /** * TBODY, TR, TD 사이에 있는 텍스트노드인지 판별한다. * @param oNode {Node} 검사할 노드 * @return {Boolean} TBODY, TR, TD 사이에 있는 텍스트노드인지 여부 */ _isTextBetweenTable : function(oNode){ var oTmpNode; if(oNode && oNode.nodeType === 3){ // 텍스트 노드 if((oTmpNode = oNode.previousSibling) && this._rxTable.test(oTmpNode.nodeName)){ return true; } if((oTmpNode = oNode.nextSibling) && this._rxTable.test(oTmpNode.nodeName)){ return true; } } return false; }, $BEFORE_EXECCOMMAND : function(sCommand, bUserInterface, vValue, htOptions){ var elTmp, oSelection; //본문에 전혀 클릭이 한번도 안 일어난 상태에서 크롬과 IE에서 EXECCOMMAND가 정상적으로 안 먹히는 현상. this.oApp.exec("FOCUS"); this._bOnlyCursorChanged = false; oSelection = this.oApp.getSelection(); // [SMARTEDITORSUS-1584] IE에서 테이블관련 태그 사이의 텍스트노드가 포함된 채로 execCommand 가 실행되면 // 테이블 태그들 사이에 더미 P 태그가 추가된다. // 테이블관련 태그 사이에 태그가 있으면 문법에 어긋나기 때문에 getContents 시 이 더미 P 태그들이 밖으로 빠져나가게 된다. // 때문에 execCommand 실행되기 전에 셀렉션에 테이블관련 태그 사이의 텍스트노드를 찾아내 지워준다. for(var i = 0, aNodes = oSelection.getNodes(), oNode;(oNode = aNodes[i]); i++){ if(this._isTextBetweenTable(oNode)){ // TODO: 노드를 삭제하지 않고 Selection 에서만 뺄수 있는 방법은 없을까? oNode.parentNode.removeChild(oNode); } } if(/^insertorderedlist|insertunorderedlist$/i.test(sCommand)){ this._getDocumentBR(); } if(/^justify*/i.test(sCommand)){ this._removeSpanAlign(); } if(sCommand.match(/^bold|underline|italic|strikethrough|superscript|subscript$/i)){ this.oUndoOption = {bMustBlockElement:true}; if(nhn.CurrentSelection.isCollapsed()){ this._bOnlyCursorChanged = true; } } if(sCommand == "indent" || sCommand == "outdent"){ if(!htOptions){htOptions = {};} htOptions["bDontAddUndoHistory"] = true; } if((!htOptions || !htOptions["bDontAddUndoHistory"]) && !this._bOnlyCursorChanged){ if(/^justify*/i.test(sCommand)){ this.oUndoOption = {sSaveTarget:"BODY"}; }else if(sCommand === "insertorderedlist" || sCommand === "insertunorderedlist"){ this.oUndoOption = {bMustBlockContainer:true}; } this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", [sCommand, this.oUndoOption]); } if(this.oNavigator.ie && this.oApp.getWYSIWYGDocument().selection){ if(this.oApp.getWYSIWYGDocument().selection.type === "Control"){ oSelection = this.oApp.getSelection(); oSelection.select(); } } if(sCommand == "insertorderedlist" || sCommand == "insertunorderedlist"){ this._insertBlankLine(); } }, $ON_EXECCOMMAND : function(sCommand, bUserInterface, vValue){ var bSelectedBlock = false; var htSelectedTDs = {}; var oSelection = this.oApp.getSelection(); bUserInterface = (bUserInterface == "" || bUserInterface)?bUserInterface:false; vValue = (vValue == "" || vValue)?vValue:false; this.oApp.exec("IS_SELECTED_TD_BLOCK",['bIsSelectedTd',htSelectedTDs]); bSelectedBlock = htSelectedTDs.bIsSelectedTd; if( bSelectedBlock){ if(sCommand == "indent"){ this.oApp.exec("SET_LINE_BLOCK_STYLE", [null, jindo.$Fn(this._indentMargin, this).bind()]); }else if(sCommand == "outdent"){ this.oApp.exec("SET_LINE_BLOCK_STYLE", [null, jindo.$Fn(this._outdentMargin, this).bind()]); }else{ this._setBlockExecCommand(sCommand, bUserInterface, vValue); } } else { switch(sCommand){ case "indent": case "outdent": this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", [sCommand]); // bookmark 설정 var sBookmark = oSelection.placeStringBookmark(); if(sCommand === "indent"){ this.oApp.exec("SET_LINE_STYLE", [null, jindo.$Fn(this._indentMargin, this).bind(), {bDoNotSelect : true, bDontAddUndoHistory : true}]); }else{ this.oApp.exec("SET_LINE_STYLE", [null, jindo.$Fn(this._outdentMargin, this).bind(), {bDoNotSelect : true, bDontAddUndoHistory : true}]); } oSelection.moveToStringBookmark(sBookmark); oSelection.select(); oSelection.removeStringBookmark(sBookmark); //bookmark 삭제 setTimeout(jindo.$Fn(function(sCommand){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", [sCommand]); }, this).bind(sCommand), 25); break; case "justifyleft": case "justifycenter": case "justifyright": case "justifyfull": var oSelectionClone = this._extendBlock(); // FF this.oEditingArea.execCommand(sCommand, bUserInterface, vValue); if(!!oSelectionClone){ oSelectionClone.select(); } break; default: //if(this.oNavigator.firefox){ //this.oEditingArea.execCommand("styleWithCSS", bUserInterface, false); //} // [SMARTEDITORSUS-1646] [SMARTEDITORSUS-1653] collapsed 상태이면 execCommand 가 실행되기 전에 ZWSP를 넣어준다. if(oSelection.collapsed){ // collapsed 인 경우 var sBM = oSelection.placeStringBookmark(), oBM = oSelection.getStringBookmark(sBM), oHolderNode = oBM.previousSibling; // execCommand를 실행할때마다 ZWSP가 포함된 더미 태그가 자꾸 생길 수 있기 때문에 이미 있으면 있는 걸로 사용한다. if(!oHolderNode || oHolderNode.nodeValue !== "\u200B"){ oHolderNode = this.oApp.getWYSIWYGDocument().createTextNode("\u200B"); oSelection.insertNode(oHolderNode); } oSelection.removeStringBookmark(sBM); // 미리 지워주지 않으면 더미 태그가 생길 수 있다. oSelection.selectNodeContents(oHolderNode); oSelection.select(); this.oEditingArea.execCommand(sCommand, bUserInterface, vValue); oSelection.collapseToEnd(); oSelection.select(); // [SMARTEDITORSUS-1658] 뒤쪽에 더미태그가 있으면 제거해준다. var oSingleNode = this._findSingleNode(oHolderNode); if(oSingleNode && oSelection._hasCursorHolderOnly(oSingleNode.nextSibling)){ oSingleNode.parentNode.removeChild(oSingleNode.nextSibling); } }else{ this.oEditingArea.execCommand(sCommand, bUserInterface, vValue); } } } this._countClickCr(sCommand); }, /** * [SMARTEDITORSUS-1658] 해당노드의 상위로 검색해 single child 만 갖는 최상위 노드를 찾는다. * @param {Node} oNode 확인할 노드 * @return {Node} single child 만 감싸고 있는 최상위 노드를 반환한다. 없으면 입력한 노드 반환 */ _findSingleNode : function(oNode){ if(!oNode){ return null; } if(oNode.parentNode.childNodes.length === 1){ return this._findSingleNode(oNode.parentNode); }else{ return oNode; } }, $AFTER_EXECCOMMAND : function(sCommand, bUserInterface, vValue, htOptions){ if(this.elP1 && this.elP1.parentNode){ this.elP1.parentNode.removeChild(this.elP1); } if(this.elP2 && this.elP2.parentNode){ this.elP2.parentNode.removeChild(this.elP2); } if(/^insertorderedlist|insertunorderedlist$/i.test(sCommand)){ // this._fixDocumentBR(); // Chrome/Safari this._fixCorruptedBlockQuote(sCommand === "insertorderedlist" ? "OL" : "UL"); // IE } if((/^justify*/i.test(sCommand))){ this._fixAlign(sCommand === "justifyfull" ? "justify" : sCommand.substring(7)); } if(sCommand == "indent" || sCommand == "outdent"){ if(!htOptions){htOptions = {};} htOptions["bDontAddUndoHistory"] = true; } if((!htOptions || !htOptions["bDontAddUndoHistory"]) && !this._bOnlyCursorChanged){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", [sCommand, this.oUndoOption]); } this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _removeSpanAlign : function(){ var oSelection = this.oApp.getSelection(), aNodes = oSelection.getNodes(), elNode = null; for(var i=0, nLen=aNodes.length; i<nLen; i++){ elNode = aNodes[i]; // [SMARTEDITORSUS-704] SPAN에서 적용된 Align을 제거 if(elNode.tagName && elNode.tagName === "SPAN"){ elNode.style.textAlign = ""; elNode.removeAttribute("align"); } } }, // [SMARTEDITORSUS-851] align, text-align을 fix해야 할 대상 노드를 찾음 _getAlignNode : function(elNode){ if(elNode.tagName && (elNode.tagName === "P" || elNode.tagName === "DIV")){ return elNode; } elNode = elNode.parentNode; while(elNode && elNode.tagName){ if(elNode.tagName === "P" || elNode.tagName === "DIV"){ return elNode; } elNode = elNode.parentNode; } }, _fixAlign : function(sAlign){ var oSelection = this.oApp.getSelection(), aNodes = [], elNode = null, elParentNode = null; var removeTableAlign = !this.oNavigator.ie ? function(){} : function(elNode){ if(elNode.tagName && elNode.tagName === "TABLE"){ elNode.removeAttribute("align"); return true; } return false; }; if(oSelection.collapsed){ aNodes[0] = oSelection.startContainer; // collapsed인 경우에는 getNodes의 결과는 [] }else{ aNodes = oSelection.getNodes(); } for(var i=0, nLen=aNodes.length; i<nLen; i++){ elNode = aNodes[i]; if(elNode.nodeType === 3){ elNode = elNode.parentNode; } if(elParentNode && (elNode === elParentNode || jindo.$Element(elNode).isChildOf(elParentNode))){ continue; } elParentNode = this._getAlignNode(elNode); if(elParentNode && elParentNode.align !== elParentNode.style.textAlign){ // [SMARTEDITORSUS-704] align 속성과 text-align 속성의 값을 맞춰줌 elParentNode.style.textAlign = sAlign; elParentNode.setAttribute("align", sAlign); } } }, _getDocumentBR : function(){ var i, nLen; // [COM-715] <Chrome/Safari> 요약글 삽입 > 더보기 영역에서 기호매기기, 번호매기기 설정할때마다 요약글 박스가 아래로 이동됨 // ExecCommand를 처리하기 전에 현재의 BR을 저장 this.aBRs = this.oApp.getWYSIWYGDocument().getElementsByTagName("BR"); this.aBeforeBRs = []; for(i=0, nLen=this.aBRs.length; i<nLen; i++){ this.aBeforeBRs[i] = this.aBRs[i]; } }, _fixDocumentBR : function(){ // [COM-715] ExecCommand가 처리된 후에 업데이트된 BR을 처리 전에 저장한 BR과 비교하여 생성된 BR을 제거 if(this.aBeforeBRs.length === this.aBRs.length){ // this.aBRs gets updated automatically when the document is updated return; } var waBeforeBRs = jindo.$A(this.aBeforeBRs), i, iLen = this.aBRs.length; for(i=iLen-1; i>=0; i--){ if(waBeforeBRs.indexOf(this.aBRs[i])<0){ this.aBRs[i].parentNode.removeChild(this.aBRs[i]); } } }, _setBlockExecCommand : function(sCommand, bUserInterface, vValue){ var aNodes, aChildrenNode, htSelectedTDs = {}; this.oSelection = this.oApp.getSelection(); this.oApp.exec("GET_SELECTED_TD_BLOCK",['aTdCells',htSelectedTDs]); aNodes = htSelectedTDs.aTdCells; for( var j = 0; j < aNodes.length ; j++){ this.oSelection.selectNodeContents(aNodes[j]); this.oSelection.select(); if(this.oNavigator.firefox){ this.oEditingArea.execCommand("styleWithCSS", bUserInterface, false); //styleWithCSS는 ff전용임. } aChildrenNode = this.oSelection.getNodes(); for( var k = 0; k < aChildrenNode.length ; k++ ) { if(aChildrenNode[k].tagName == "UL" || aChildrenNode[k].tagName == "OL" ){ jindo.$Element(aChildrenNode[k]).css("color",vValue); } } this.oEditingArea.execCommand(sCommand, bUserInterface, vValue); } }, _indentMargin : function(elDiv){ var elTmp = elDiv, aAppend, i, nLen, elInsertTarget, elDeleteTarget, nCurMarginLeft; while(elTmp){ if(elTmp.tagName && elTmp.tagName === "LI"){ elDiv = elTmp; break; } elTmp = elTmp.parentNode; } if(elDiv.tagName === "LI"){ //<OL> // <OL> // <LI>22</LI> // </OL> // <LI>33</LI> //</OL> //와 같은 형태라면 33을 들여쓰기 했을 때, 상단의 silbling OL과 합쳐서 아래와 같이 만들어 줌. //<OL> // <OL> // <LI>22</LI> // <LI>33</LI> // </OL> //</OL> if(elDiv.previousSibling && elDiv.previousSibling.tagName && elDiv.previousSibling.tagName === elDiv.parentNode.tagName){ // 하단에 또다른 OL이 있어 아래와 같은 형태라면, //<OL> // <OL> // <LI>22</LI> // </OL> // <LI>33</LI> // <OL> // <LI>44</LI> // </OL> //</OL> //22,33,44를 합쳐서 아래와 같이 만들어 줌. //<OL> // <OL> // <LI>22</LI> // <LI>33</LI> // <LI>44</LI> // </OL> //</OL> if(elDiv.nextSibling && elDiv.nextSibling.tagName && elDiv.nextSibling.tagName === elDiv.parentNode.tagName){ aAppend = [elDiv]; for(i=0, nLen=elDiv.nextSibling.childNodes.length; i<nLen; i++){ aAppend.push(elDiv.nextSibling.childNodes[i]); } elInsertTarget = elDiv.previousSibling; elDeleteTarget = elDiv.nextSibling; for(i=0, nLen=aAppend.length; i<nLen; i++){ elInsertTarget.insertBefore(aAppend[i], null); } elDeleteTarget.parentNode.removeChild(elDeleteTarget); }else{ elDiv.previousSibling.insertBefore(elDiv, null); } return; } //<OL> // <LI>22</LI> // <OL> // <LI>33</LI> // </OL> //</OL> //와 같은 형태라면 22을 들여쓰기 했을 때, 하단의 silbling OL과 합친다. if(elDiv.nextSibling && elDiv.nextSibling.tagName && elDiv.nextSibling.tagName === elDiv.parentNode.tagName){ elDiv.nextSibling.insertBefore(elDiv, elDiv.nextSibling.firstChild); return; } elTmp = elDiv.parentNode.cloneNode(false); elDiv.parentNode.insertBefore(elTmp, elDiv); elTmp.appendChild(elDiv); return; } nCurMarginLeft = parseInt(elDiv.style.marginLeft, 10); if(!nCurMarginLeft){ nCurMarginLeft = 0; } nCurMarginLeft += this.nIndentSpacing; elDiv.style.marginLeft = nCurMarginLeft+"px"; }, _outdentMargin : function(elDiv){ var elTmp = elDiv, elParentNode, elInsertBefore, elNewParent, elInsertParent, oDoc, nCurMarginLeft; while(elTmp){ if(elTmp.tagName && elTmp.tagName === "LI"){ elDiv = elTmp; break; } elTmp = elTmp.parentNode; } if(elDiv.tagName === "LI"){ elParentNode = elDiv.parentNode; elInsertBefore = elDiv.parentNode; // LI를 적절 위치로 이동. // 위에 다른 li/ol/ul가 있는가? if(elDiv.previousSibling && elDiv.previousSibling.tagName && elDiv.previousSibling.tagName.match(/LI|UL|OL/)){ // 위아래로 sibling li/ol/ul가 있다면 ol/ul를 2개로 나누어야됨 if(elDiv.nextSibling && elDiv.nextSibling.tagName && elDiv.nextSibling.tagName.match(/LI|UL|OL/)){ elNewParent = elParentNode.cloneNode(false); while(elDiv.nextSibling){ elNewParent.insertBefore(elDiv.nextSibling, null); } elParentNode.parentNode.insertBefore(elNewParent, elParentNode.nextSibling); elInsertBefore = elNewParent; // 현재 LI가 마지막 LI라면 부모 OL/UL 하단에 삽입 }else{ elInsertBefore = elParentNode.nextSibling; } } elParentNode.parentNode.insertBefore(elDiv, elInsertBefore); // 내어쓰기 한 LI 외에 다른 LI가 존재 하지 않을 경우 부모 노드 지워줌 if(!elParentNode.innerHTML.match(/LI/i)){ elParentNode.parentNode.removeChild(elParentNode); } // OL이나 UL 위로까지 내어쓰기가 된 상태라면 LI를 벗겨냄 if(!elDiv.parentNode.tagName.match(/OL|UL/)){ elInsertParent = elDiv.parentNode; elInsertBefore = elDiv; // 내용물을 P로 감싸기 oDoc = this.oApp.getWYSIWYGDocument(); elInsertParent = oDoc.createElement("P"); elInsertBefore = null; elDiv.parentNode.insertBefore(elInsertParent, elDiv); while(elDiv.firstChild){ elInsertParent.insertBefore(elDiv.firstChild, elInsertBefore); } elDiv.parentNode.removeChild(elDiv); } return; } nCurMarginLeft = parseInt(elDiv.style.marginLeft, 10); if(!nCurMarginLeft){ nCurMarginLeft = 0; } nCurMarginLeft -= this.nIndentSpacing; if(nCurMarginLeft < 0){ nCurMarginLeft = 0; } elDiv.style.marginLeft = nCurMarginLeft+"px"; }, // Fix IE's execcommand bug // When insertorderedlist/insertunorderedlist is executed on a blockquote, the blockquote will "suck in" directly neighboring OL, UL's if there's any. // To prevent this, insert empty P tags right before and after the blockquote and remove them after the execution. // [SMARTEDITORSUS-793] Chrome 에서 동일한 이슈 발생, Chrome 은 빈 P 태그로는 처리되지 않으 &nbsp; 추가 _insertBlankLine : function(){ var oSelection = this.oApp.getSelection(); var elNode = oSelection.commonAncestorContainer; this.elP1 = null; this.elP2 = null; while(elNode){ if(elNode.tagName == "BLOCKQUOTE"){ this.elP1 = jindo.$("<p>&nbsp;</p>", this.oApp.getWYSIWYGDocument()); elNode.parentNode.insertBefore(this.elP1, elNode); this.elP2 = jindo.$("<p>&nbsp;</p>", this.oApp.getWYSIWYGDocument()); elNode.parentNode.insertBefore(this.elP2, elNode.nextSibling); break; } elNode = elNode.parentNode; } }, // Fix IE's execcommand bug // When insertorderedlist/insertunorderedlist is executed on a blockquote with all the child nodes selected, // eg:<blockquote>[selection starts here]blah...[selection ends here]</blockquote> // , IE will change the blockquote with the list tag and create <OL><OL><LI>blah...</LI></OL></OL>. // (two OL's or two UL's depending on which command was executed) // // It can also happen when the cursor is located at bogus positions like // * below blockquote when the blockquote is the last element in the document // // [IE] 인용구 안에서 글머리 기호를 적용했을 때, 인용구 밖에 적용된 번호매기기/글머리 기호가 인용구 안으로 빨려 들어가는 문제 처리 _fixCorruptedBlockQuote : function(sTagName){ var aNodes = this.oApp.getWYSIWYGDocument().getElementsByTagName(sTagName), elCorruptedBlockQuote, elTmpParent, elNewNode, aLists, i, nLen, nPos, el, oSelection; for(i=0, nLen=aNodes.length; i<nLen; i++){ if(aNodes[i].firstChild && aNodes[i].firstChild.tagName == sTagName){ elCorruptedBlockQuote = aNodes[i]; break; } } if(!elCorruptedBlockQuote){return;} elTmpParent = elCorruptedBlockQuote.parentNode; // (1) changing outerHTML will cause loss of the reference to the node, so remember the idx position here nPos = this._getPosIdx(elCorruptedBlockQuote); el = this.oApp.getWYSIWYGDocument().createElement("DIV"); el.innerHTML = elCorruptedBlockQuote.outerHTML.replace("<"+sTagName, "<BLOCKQUOTE"); elCorruptedBlockQuote.parentNode.insertBefore(el.firstChild, elCorruptedBlockQuote); elCorruptedBlockQuote.parentNode.removeChild(elCorruptedBlockQuote); // (2) and retrieve the new node here elNewNode = elTmpParent.childNodes[nPos]; // garbage <OL></OL> or <UL></UL> will be left over after setting the outerHTML, so remove it here. aLists = elNewNode.getElementsByTagName(sTagName); for(i=0, nLen=aLists.length; i<nLen; i++){ if(aLists[i].childNodes.length<1){ aLists[i].parentNode.removeChild(aLists[i]); } } oSelection = this.oApp.getEmptySelection(); oSelection.selectNodeContents(elNewNode); oSelection.collapseToEnd(); oSelection.select(); }, _getPosIdx : function(refNode){ var idx = 0; for(var node = refNode.previousSibling; node; node = node.previousSibling){idx++;} return idx; }, _countClickCr : function(sCommand) { if (!sCommand.match(this.rxClickCr)) { return; } this.oApp.exec('MSG_NOTIFY_CLICKCR', [sCommand.replace(/^insert/i, '')]); }, _extendBlock : function(){ // [SMARTEDITORSUS-663] [FF] block단위로 확장하여 Range를 새로 지정해주는것이 원래 스펙이므로 // 해결을 위해서는 현재 선택된 부분을 Block으로 extend하여 execCommand API가 처리될 수 있도록 함 var oSelection = this.oApp.getSelection(), oStartContainer = oSelection.startContainer, oEndContainer = oSelection.endContainer, aChildImg = [], aSelectedImg = [], oSelectionClone = oSelection.cloneRange(); // <p><img><br/><img><br/><img></p> 일 때 이미지가 일부만 선택되면 발생 // - container 노드는 P 이고 container 노드의 자식노드 중 이미지가 여러개인데 선택된 이미지가 그 중 일부인 경우 if(!(oStartContainer === oEndContainer && oStartContainer.nodeType === 1 && oStartContainer.tagName === "P")){ return; } aChildImg = jindo.$A(oStartContainer.childNodes).filter(function(value, index, array){ return (value.nodeType === 1 && value.tagName === "IMG"); }).$value(); aSelectedImg = jindo.$A(oSelection.getNodes()).filter(function(value, index, array){ return (value.nodeType === 1 && value.tagName === "IMG"); }).$value(); if(aChildImg.length <= aSelectedImg.length){ return; } oSelection.selectNode(oStartContainer); oSelection.select(); return oSelectionClone; } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font color * @name hp_SE_FontColor.js */ nhn.husky.SE2M_FontColor = jindo.$Class({ name : "SE2M_FontColor", rxColorPattern : /^#?[0-9a-fA-F]{6}$|^rgb\(\d+, ?\d+, ?\d+\)$/i, $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.elLastUsed = jindo.$$.getSingle("SPAN.husky_se2m_fontColor_lastUsed", elAppContainer); this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_fontcolor_layer", elAppContainer); this.elPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_fontcolor_paletteHolder", this.elDropdownLayer); //@ec] this._setLastUsedFontColor("#000000"); }, $BEFORE_MSG_APP_READY : function() { this.oApp.exec("ADD_APP_PROPERTY", ["getLastUsedFontColor", jindo.$Fn(this.getLastUsedFontColor, this).bind()]); }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["fontColorA", "click", "APPLY_LAST_USED_FONTCOLOR"]); this.oApp.exec("REGISTER_UI_EVENT", ["fontColorB", "click", "TOGGLE_FONTCOLOR_LAYER"]); }, //@lazyload_js APPLY_LAST_USED_FONTCOLOR,TOGGLE_FONTCOLOR_LAYER[ $ON_TOGGLE_FONTCOLOR_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "FONTCOLOR_LAYER_SHOWN", [], "FONTCOLOR_LAYER_HIDDEN", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['fontcolor']); }, $ON_FONTCOLOR_LAYER_SHOWN : function(){ this.oApp.exec("SELECT_UI", ["fontColorB"]); this.oApp.exec("SHOW_COLOR_PALETTE", ["APPLY_FONTCOLOR", this.elPaletteHolder]); }, $ON_FONTCOLOR_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["fontColorB"]); this.oApp.exec("RESET_COLOR_PALETTE", []); }, $ON_APPLY_LAST_USED_FONTCOLOR : function(){ this.oApp.exec("APPLY_FONTCOLOR", [this.sLastUsedColor]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['fontcolor']); }, $ON_APPLY_FONTCOLOR : function(sFontColor){ if(!this.rxColorPattern.test(sFontColor)){ alert(this.oApp.$MSG("SE_FontColor.invalidColorCode")); return; } this._setLastUsedFontColor(sFontColor); this.oApp.exec("SET_WYSIWYG_STYLE", [{"color":sFontColor}]); // [SMARTEDITORSUS-907] 모든 브라우저에서 SET_WYSIWYG_STYLE로 색상을 설정하도록 변경 // var oAgent = jindo.$Agent().navigator(); // if( oAgent.ie || oAgent.firefox ){ // [SMARTEDITORSUS-658] Firefox 추가 // this.oApp.exec("SET_WYSIWYG_STYLE", [{"color":sFontColor}]); // } else { // var bDontAddUndoHistory = false; // if(this.oApp.getSelection().collapsed){ // bDontAddUndoHistory = true; // } // this.oApp.exec("EXECCOMMAND", ["ForeColor", false, sFontColor, { "bDontAddUndoHistory" : bDontAddUndoHistory }]); // if(bDontAddUndoHistory){ // this.oApp.exec("RECORD_UNDO_ACTION", ["FONT COLOR", {bMustBlockElement : true}]); // } // } this.oApp.exec("HIDE_ACTIVE_LAYER"); }, //@lazyload_js] _setLastUsedFontColor : function(sFontColor){ this.sLastUsedColor = sFontColor; this.elLastUsed.style.backgroundColor = this.sLastUsedColor; }, getLastUsedFontColor : function(){ return (!!this.sLastUsedColor) ? this.sLastUsedColor : '#000000'; } }); //} /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font name using Select element * @name SE2M_FontNameWithLayerUI.js * @trigger MSG_STYLE_CHANGED,SE2M_TOGGLE_FONTNAME_LAYER */ nhn.husky.SE2M_FontNameWithLayerUI = jindo.$Class({ name : "SE2M_FontNameWithLayerUI", $init : function(elAppContainer, aAdditionalFontList){ this.elLastHover = null; this._assignHTMLElements(elAppContainer); this.htBrowser = jindo.$Agent().navigator(); this.aAdditionalFontList = aAdditionalFontList || []; }, addAllFonts : function(){ var aDefaultFontList, aFontList, htMainFont, aFontInUse, i; // family name -> display name 매핑 (웹폰트는 두개가 다름) this.htFamilyName2DisplayName = {}; this.htAllFonts = {}; this.aBaseFontList = []; this.aDefaultFontList = []; this.aTempSavedFontList = []; this.htOptions = this.oApp.htOptions.SE2M_FontName; if(this.htOptions){ aDefaultFontList = this.htOptions.aDefaultFontList || []; aFontList = this.htOptions.aFontList; htMainFont = this.htOptions.htMainFont; aFontInUse = this.htOptions.aFontInUse; //add Font if(this.htBrowser.ie && aFontList){ for(i=0; i<aFontList.length; i++){ this.addFont(aFontList[i].id, aFontList[i].name, aFontList[i].size, aFontList[i].url, aFontList[i].cssUrl); } } for(i=0; i<aDefaultFontList.length; i++){ this.addFont(aDefaultFontList[i][0], aDefaultFontList[i][1], 0, "", "", 1); } //set Main Font //if(mainFontSelected=='true') { if(htMainFont && htMainFont.id) { //this.setMainFont(mainFontId, mainFontName, mainFontSize, mainFontUrl, mainFontCssUrl); this.setMainFont(htMainFont.id, htMainFont.name, htMainFont.size, htMainFont.url, htMainFont.cssUrl); } // add font in use if(this.htBrowser.ie && aFontInUse){ for(i=0; i<aFontInUse.length; i++){ this.addFontInUse(aFontInUse[i].id, aFontInUse[i].name, aFontInUse[i].size, aFontInUse[i].url, aFontInUse[i].cssUrl); } } } // [SMARTEDITORSUS-245] 서비스 적용 시 글꼴정보를 넘기지 않으면 기본 글꼴 목록이 보이지 않는 오류 if(!this.htOptions || !this.htOptions.aDefaultFontList || this.htOptions.aDefaultFontList.length === 0){ this.addFont("돋움,Dotum", "돋움", 0, "", "", 1, null, true); this.addFont("돋움체,DotumChe,AppleGothic", "돋움체", 0, "", "", 1); this.addFont("굴림,Gulim", "굴림", 0, "", "", 1, null, true); this.addFont("굴림체,GulimChe", "굴림체", 0, "", "", 1, null, true); this.addFont("바탕,Batang,AppleMyungjo", "바탕", 0, "", "", 1); this.addFont("바탕체,BatangChe", "바탕체", 0, "", "", 1, null, true); this.addFont("궁서,Gungsuh,GungSeo", "궁서", 0, "", "", 1); this.addFont('Arial', 'Arial', 0, "", "", 1, "abcd"); this.addFont('Tahoma', 'Tahoma', 0, "", "", 1, "abcd"); this.addFont('Times New Roman', 'Times New Roman', 0, "", "", 1, "abcd"); this.addFont('Verdana', 'Verdana', 0, "", "", 1, "abcd"); this.addFont('Courier New', 'Courier New', 0, "", "", 1, "abcd"); } // [SMARTEDITORSUS-1436] 글꼴 리스트에 글꼴 종류 추가하기 기능 if(!!this.aAdditionalFontList && this.aAdditionalFontList.length > 0){ for(i = 0, nLen = this.aAdditionalFontList.length; i < nLen; i++){ this.addFont(this.aAdditionalFontList[i][0], this.aAdditionalFontList[i][1], 0, "", "", 1); } } }, $ON_MSG_APP_READY : function(){ this.bDoNotRecordUndo = false; this.oApp.exec("ADD_APP_PROPERTY", ["addFont", jindo.$Fn(this.addFont, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["addFontInUse", jindo.$Fn(this.addFontInUse, this).bind()]); // 블로그등 팩토리 폰트 포함 용 this.oApp.exec("ADD_APP_PROPERTY", ["setMainFont", jindo.$Fn(this.setMainFont, this).bind()]); // 메일등 단순 폰트 지정 용 this.oApp.exec("ADD_APP_PROPERTY", ["setDefaultFont", jindo.$Fn(this.setDefaultFont, this).bind()]); this.oApp.exec("REGISTER_UI_EVENT", ["fontName", "click", "SE2M_TOGGLE_FONTNAME_LAYER"]); }, $AFTER_MSG_APP_READY : function(){ this._initFontName(); this._attachIEEvent(); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.oDropdownLayer = jindo.$$.getSingle("DIV.husky_se_fontName_layer", elAppContainer); this.elFontNameLabel = jindo.$$.getSingle("SPAN.husky_se2m_current_fontName", elAppContainer); this.elFontNameList = jindo.$$.getSingle("UL", this.oDropdownLayer); this.elInnerLayer = this.elFontNameList.parentNode; this.elFontItemTemplate = jindo.$$.getSingle("LI", this.oDropdownLayer); this.aLIFontNames = jindo.$A(jindo.$$("LI", this.oDropdownLayer)).filter(function(v,i,a){return (v.firstChild !== null);})._array; this.elSeparator = jindo.$$.getSingle("LI.husky_seditor_font_separator", this.oDropdownLayer); this.elNanumgothic = jindo.$$.getSingle("LI.husky_seditor_font_nanumgothic", this.oDropdownLayer); this.elNanummyeongjo = jindo.$$.getSingle("LI.husky_seditor_font_nanummyeongjo", this.oDropdownLayer); this.elNanumgothiccoding = jindo.$$.getSingle("LI.husky_seditor_font_nanumgothiccoding", this.oDropdownLayer); //@ec] this.sDefaultText = this.elFontNameLabel.innerHTML; }, //$LOCAL_BEFORE_FIRST : function(){ _initFontName : function(){ this._addNanumFont(); this.addAllFonts(); this.oApp.registerBrowserEvent(this.oDropdownLayer, "mouseover", "EVENT_FONTNAME_LAYER_MOUSEOVER", []); this.oApp.registerBrowserEvent(this.oDropdownLayer, "click", "EVENT_FONTNAME_LAYER_CLICKED", []); }, _addNanumFont : function(){ var bUseSeparator = false; var nanum_gothic = unescape("%uB098%uB214%uACE0%uB515"); var nanum_myungjo = unescape("%uB098%uB214%uBA85%uC870"); var nanum_gothic_coding = unescape("%uB098%uB214%uACE0%uB515%uCF54%uB529"); if(jindo.$Agent().os().mac){ nanum_gothic = "NanumGothic"; nanum_myungjo = "NanumMyeongjo"; nanum_gothic_coding = "NanumGothicCoding"; } if(!!this.elNanumgothic){ if(IsInstalledFont(nanum_gothic)){ bUseSeparator = true; this.elNanumgothic.style.display = "block"; }else{ this.elNanumgothic.style.display = "none"; } } if(!!this.elNanummyeongjo){ if(IsInstalledFont(nanum_myungjo)){ bUseSeparator = true; this.elNanummyeongjo.style.display = "block"; }else{ this.elNanummyeongjo.style.display = "none"; } } if(!!this.elNanumgothicCoding){ if(IsInstalledFont(nanum_gothic_coding)){ bUseSeparator = true; this.elNanumgothiccoding.style.display = "block"; }else{ this.elNanumgothiccoding.style.display = "none"; } } if(!!this.elSeparator){ this.elSeparator.style.display = bUseSeparator ? "block" : "none"; } }, _attachIEEvent : function(){ if(!this.htBrowser.ie){ return; } if(this.htBrowser.nativeVersion < 9){ // [SMARTEDITORSUS-187] [< IE9] 최초 paste 시점에 웹폰트 파일을 로드 this._wfOnPasteWYSIWYGBody = jindo.$Fn(this._onPasteWYSIWYGBody, this); this._wfOnPasteWYSIWYGBody.attach(this.oApp.getWYSIWYGDocument().body, "paste"); return; } if(document.documentMode < 9){ // [SMARTEDITORSUS-169] [>= IE9] 최초 포커스 시점에 웹폰트 로드 this._wfOnFocusWYSIWYGBody = jindo.$Fn(this._onFocusWYSIWYGBody, this); this._wfOnFocusWYSIWYGBody.attach(this.oApp.getWYSIWYGDocument().body, "focus"); return; } // documentMode === 9 // http://blogs.msdn.com/b/ie/archive/2010/08/17/ie9-opacity-and-alpha.aspx // opacity:0.0; this.welEditingAreaCover = jindo.$Element('<DIV style="width:100%; height:100%; position:absolute; top:0px; left:0px; z-index:1000;"></DIV>'); this.oApp.welEditingAreaContainer.prepend(this.welEditingAreaCover); jindo.$Fn(this._onMouseupCover, this).attach(this.welEditingAreaCover.$value(), "mouseup"); }, _onFocusWYSIWYGBody : function(e){ this._wfOnFocusWYSIWYGBody.detach(this.oApp.getWYSIWYGDocument().body, "focus"); this._loadAllBaseFont(); }, _onPasteWYSIWYGBody : function(e){ this._wfOnPasteWYSIWYGBody.detach(this.oApp.getWYSIWYGDocument().body, "paste"); this._loadAllBaseFont(); }, _onMouseupCover : function(e){ e.stop(); // [SMARTEDITORSUS-1632] 문서 모드가 9 이상일 때, 경우에 따라 this.welEditingAreaContainer가 없을 때 스크립트 오류 발생 if(this.welEditingAreaCover){ this.welEditingAreaCover.leave(); } //this.welEditingAreaCover.leave(); // --[SMARTEDITORSUS-1632] var oMouse = e.mouse(), elBody = this.oApp.getWYSIWYGDocument().body, welBody = jindo.$Element(elBody), oSelection = this.oApp.getEmptySelection(); // [SMARTEDITORSUS-363] 강제로 Selection 을 주도록 처리함 oSelection.selectNode(elBody); oSelection.collapseToStart(); oSelection.select(); welBody.fireEvent("mousedown", {left : oMouse.left, middle : oMouse.middle, right : oMouse.right}); welBody.fireEvent("mouseup", {left : oMouse.left, middle : oMouse.middle, right : oMouse.right}); }, $ON_EVENT_TOOLBAR_MOUSEDOWN : function(){ if(this.htBrowser.nativeVersion < 9 || document.documentMode < 9){ return; } // [SMARTEDITORSUS-1632] 문서 모드가 9 이상일 때, 경우에 따라 this.welEditingAreaContainer가 없을 때 스크립트 오류 발생 if(this.welEditingAreaCover){ this.welEditingAreaCover.leave(); } //this.welEditingAreaCover.leave(); // --[SMARTEDITORSUS-1632] }, _loadAllBaseFont : function(){ var i, nFontLen; if(!this.htBrowser.ie){ return; } if(this.htBrowser.nativeVersion < 9){ for(i=0, nFontLen=this.aBaseFontList.length; i<nFontLen; i++){ this.aBaseFontList[i].loadCSS(this.oApp.getWYSIWYGDocument()); } }else if(document.documentMode < 9){ for(i=0, nFontLen=this.aBaseFontList.length; i<nFontLen; i++){ this.aBaseFontList[i].loadCSSToMenu(); } } this._loadAllBaseFont = function(){}; }, _addFontToMenu: function(sDisplayName, sFontFamily, sSampleText){ var elItem = document.createElement("LI"); elItem.innerHTML = this.elFontItemTemplate.innerHTML.replace("@DisplayName@", sDisplayName).replace("FontFamily", sFontFamily).replace("@SampleText@", sSampleText); this.elFontNameList.insertBefore(elItem, this.elFontItemTemplate); this.aLIFontNames[this.aLIFontNames.length] = elItem; if(this.aLIFontNames.length > 20){ this.oDropdownLayer.style.overflowX = 'hidden'; this.oDropdownLayer.style.overflowY = 'auto'; this.oDropdownLayer.style.height = '400px'; this.oDropdownLayer.style.width = '204px'; // [SMARTEDITORSUS-155] 스크롤을 포함하여 206px 이 되도록 처리 } }, $ON_EVENT_FONTNAME_LAYER_MOUSEOVER : function(wev){ var elTmp = this._findLI(wev.element); if(!elTmp){ return; } this._clearLastHover(); elTmp.className = "hover"; this.elLastHover = elTmp; }, $ON_EVENT_FONTNAME_LAYER_CLICKED : function(wev){ var elTmp = this._findLI(wev.element); if(!elTmp){ return; } var sFontFamily = this._getFontFamilyFromLI(elTmp); // [SMARTEDITORSUS-169] 웹폰트의 경우 fontFamily 에 ' 을 붙여주는 처리를 함 var htFontInfo = this.htAllFonts[sFontFamily.replace(/\"/g, nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS)]; var nDefaultFontSize; if(htFontInfo){ nDefaultFontSize = htFontInfo.defaultSize+"pt"; }else{ nDefaultFontSize = 0; } this.oApp.exec("SET_FONTFAMILY", [sFontFamily, nDefaultFontSize]); }, _findLI : function(elTmp){ while(elTmp.tagName != "LI"){ if(!elTmp || elTmp === this.oDropdownLayer){ return null; } elTmp = elTmp.parentNode; } if(/husky_seditor_font_separator/.test(elTmp.className)){ return null; } return elTmp; }, _clearLastHover : function(){ if(this.elLastHover){ this.elLastHover.className = ""; } }, $ON_SE2M_TOGGLE_FONTNAME_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oDropdownLayer, null, "MSG_FONTNAME_LAYER_OPENED", [], "MSG_FONTNAME_LAYER_CLOSED", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['font']); }, $ON_MSG_FONTNAME_LAYER_OPENED : function(){ this.oApp.exec("SELECT_UI", ["fontName"]); }, $ON_MSG_FONTNAME_LAYER_CLOSED : function(){ this._clearLastHover(); this.oApp.exec("DESELECT_UI", ["fontName"]); }, $ON_MSG_STYLE_CHANGED : function(sAttributeName, sAttributeValue){ if(sAttributeName == "fontFamily"){ sAttributeValue = sAttributeValue.replace(/["']/g, ""); var elLi = this._getMatchingLI(sAttributeValue); this._clearFontNameSelection(); if(elLi){ this.elFontNameLabel.innerHTML = this._getFontNameLabelFromLI(elLi); jindo.$Element(elLi).addClass("active"); }else{ //var sDisplayName = this.htFamilyName2DisplayName[sAttributeValue] || sAttributeValue; var sDisplayName = this.sDefaultText; this.elFontNameLabel.innerHTML = sDisplayName; } } }, $BEFORE_RECORD_UNDO_BEFORE_ACTION : function(){ return !this.bDoNotRecordUndo; }, $BEFORE_RECORD_UNDO_AFTER_ACTION : function(){ return !this.bDoNotRecordUndo; }, $BEFORE_RECORD_UNDO_ACTION : function(){ return !this.bDoNotRecordUndo; }, $ON_SET_FONTFAMILY : function(sFontFamily, sDefaultSize){ if(!sFontFamily){return;} // [SMARTEDITORSUS-169] 웹폰트의 경우 fontFamily 에 ' 을 붙여주는 처리를 함 var oFontInfo = this.htAllFonts[sFontFamily.replace(/\"/g, nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS)]; if(!!oFontInfo){ oFontInfo.loadCSS(this.oApp.getWYSIWYGDocument()); } // fontFamily와 fontSize 두개의 액션을 하나로 묶어서 undo history 저장 this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["SET FONTFAMILY", {bMustBlockElement:true}]); this.bDoNotRecordUndo = true; if(parseInt(sDefaultSize, 10) > 0){ this.oApp.exec("SET_WYSIWYG_STYLE", [{"fontSize":sDefaultSize}]); } this.oApp.exec("SET_WYSIWYG_STYLE", [{"fontFamily":sFontFamily}]); this.bDoNotRecordUndo = false; this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["SET FONTFAMILY", {bMustBlockElement:true}]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _getMatchingLI : function(sFontName){ sFontName = sFontName.toLowerCase(); var elLi, aFontFamily; for(var i=0; i<this.aLIFontNames.length; i++){ elLi = this.aLIFontNames[i]; aFontFamily = this._getFontFamilyFromLI(elLi).toLowerCase().split(","); for(var h=0; h < aFontFamily.length;h++){ if( !!aFontFamily[h] && jindo.$S(aFontFamily[h].replace(/['"]/ig, "")).trim().$value() == sFontName){ return elLi; } } } return null; }, _getFontFamilyFromLI : function(elLi){ //return elLi.childNodes[1].innerHTML.toLowerCase(); // <li><button type="button"><span>돋음</span>(</span><em style="font-family:'돋음',Dotum,'굴림',Gulim,Helvetica,Sans-serif;">돋음</em><span>)</span></span></button></li> return (elLi.getElementsByTagName("EM")[0]).style.fontFamily; }, _getFontNameLabelFromLI : function(elLi){ return elLi.firstChild.firstChild.firstChild.nodeValue; }, _clearFontNameSelection : function(elLi){ for(var i=0; i<this.aLIFontNames.length; i++){ jindo.$Element(this.aLIFontNames[i]).removeClass("active"); } }, /** * Add the font to the list * @param fontId {String} value of font-family in style * @param fontName {String} name of font list in editor * @param defaultSize * @param fontURL * @param fontCSSURL * @param fontType fontType == null, custom font (sent from the server) * fontType == 1, default font * fontType == 2, tempSavedFont * @param sSampleText {String} sample text of font list in editor * @param bCheck {Boolean} */ addFont : function (fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType, sSampleText, bCheck) { // custom font feature only available in IE if(!this.htBrowser.ie && fontCSSURL){ return null; } // OS에 해당 폰트가 존재하는지 여부를 확인한다. if(bCheck && !IsInstalledFont(fontId)){ return null; } fontId = fontId.toLowerCase(); var newFont = new fontProperty(fontId, fontName, defaultSize, fontURL, fontCSSURL); var sFontFamily; var sDisplayName; if(defaultSize>0){ sFontFamily = fontId+"_"+defaultSize; sDisplayName = fontName+"_"+defaultSize; }else{ sFontFamily = fontId; sDisplayName = fontName; } if(!fontType){ sFontFamily = nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS + sFontFamily + nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS; } if(this.htAllFonts[sFontFamily]){ return this.htAllFonts[sFontFamily]; } this.htAllFonts[sFontFamily] = newFont; /* // do not add again, if the font is already in the list for(var i=0; i<this._allFontList.length; i++){ if(newFont.fontFamily == this._allFontList[i].fontFamily){ return this._allFontList[i]; } } this._allFontList[this._allFontList.length] = newFont; */ // [SMARTEDITORSUS-169] [IE9] 웹폰트A 선택>웹폰트B 선택>웹폰트 A를 다시 선택하면 웹폰트 A가 적용되지 않는 문제가 발생 // // [원인] // - IE9의 웹폰트 로드/언로드 시점 // 웹폰트 로드 시점: StyleSheet 의 @font-face 구문이 해석된 이후, DOM Tree 상에서 해당 웹폰트가 최초로 사용된 시점 // 웹폰트 언로드 시점: StyleSheet 의 @font-face 구문이 해석된 이후, DOM Tree 상에서 해당 웬폰트가 더이상 사용되지 않는 시점 // - 메뉴 리스트에 적용되는 스타일은 @font-face 이전에 처리되는 것이어서 언로드에 영향을 미치지 않음 // // 스마트에디터의 경우, 웹폰트를 선택할 때마다 SPAN 이 새로 추가되는 것이 아닌 선택된 SPAN 의 fontFamily 를 변경하여 처리하므로 // fontFamily 변경 후 DOM Tree 상에서 더이상 사용되지 않는 것으로 브라우저 판단하여 언로드 해버림. // [해결] // 언로드가 발생하지 않도록 메뉴 리스트에 스타일을 적용하는 것을 @font-face 이후로 하도록 처리하여 DOM Tree 상에 항상 적용될 수 있도록 함 // // [SMARTEDITORSUS-969] [IE10] 웹폰트를 사용하여 글을 등록하고, 수정모드로 들어갔을 때 웹폰트가 적용되지 않는 문제 // - IE10에서도 웹폰트 언로드가 발생하지 않도록 조건을 수정함 // -> 기존 : nativeVersion === 9 && documentMode === 9 // -> 수정 : nativeVersion >= 9 && documentMode >= 9 if(this.htBrowser.ie && this.htBrowser.nativeVersion >= 9 && document.documentMode >= 9) { newFont.loadCSSToMenu(); } this.htFamilyName2DisplayName[sFontFamily] = fontName; sSampleText = sSampleText || this.oApp.$MSG('SE2M_FontNameWithLayerUI.sSampleText'); this._addFontToMenu(sDisplayName, sFontFamily, sSampleText); if(!fontType){ this.aBaseFontList[this.aBaseFontList.length] = newFont; }else{ if(fontType == 1){ this.aDefaultFontList[this.aDefaultFontList.length] = newFont; }else{ this.aTempSavedFontList[this.aTempSavedFontList.length] = newFont; } } return newFont; }, // Add the font AND load it right away addFontInUse : function (fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType) { var newFont = this.addFont(fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType); if(!newFont){ return null; } newFont.loadCSS(this.oApp.getWYSIWYGDocument()); return newFont; }, // Add the font AND load it right away AND THEN set it as the default font setMainFont : function (fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType) { var newFont = this.addFontInUse(fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType); if(!newFont){ return null; } this.setDefaultFont(newFont.fontFamily, defaultSize); return newFont; }, setDefaultFont : function(sFontFamily, nFontSize){ var elBody = this.oApp.getWYSIWYGDocument().body; elBody.style.fontFamily = sFontFamily; if(nFontSize>0){elBody.style.fontSize = nFontSize + 'pt';} } }); nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS = "'"; // [SMARTEDITORSUS-169] 웹폰트의 경우 fontFamily 에 ' 을 붙여주는 처리를 함 // property function for all fonts - including the default fonts and the custom fonts // non-custom fonts will have the defaultSize of 0 and empty string for fontURL/fontCSSURL function fontProperty(fontId, fontName, defaultSize, fontURL, fontCSSURL){ this.fontId = fontId; this.fontName = fontName; this.defaultSize = defaultSize; this.fontURL = fontURL; this.fontCSSURL = fontCSSURL; this.displayName = fontName; this.isLoaded = true; this.fontFamily = this.fontId; // it is custom font if(this.fontCSSURL != ""){ this.displayName += '' + defaultSize; this.fontFamily += '_' + defaultSize; // custom fonts requires css loading this.isLoaded = false; // load the css that loads the custom font this.loadCSS = function(doc){ // if the font is loaded already, return if(this.isLoaded){ return; } this._importCSS(doc); this.isLoaded = true; }; // [SMARTEDITORSUS-169] [IE9] // addImport 후에 처음 적용된 DOM-Tree 가 iframe 내부인 경우 (setMainFont || addFontInUse 에서 호출된 경우) // 해당 폰트에 대한 언로드 문제가 계속 발생하여 IE9에서 addFont 에서 호출하는 loadCSS 의 경우에는 isLoaded를 true 로 변경하지 않음. this.loadCSSToMenu = function(){ this._importCSS(document); }; this._importCSS = function(doc){ var nStyleSheet = doc.styleSheets.length; var oStyleSheet = doc.styleSheets[nStyleSheet - 1]; if(nStyleSheet === 0 || oStyleSheet.imports.length == 30){ // imports limit oStyleSheet = doc.createStyleSheet(); } oStyleSheet.addImport(this.fontCSSURL); }; }else{ this.loadCSS = function(){}; this.loadCSSToMenu = function(){}; } this.toStruct = function(){ return {fontId:this.fontId, fontName:this.fontName, defaultSize:this.defaultSize, fontURL:this.fontURL, fontCSSURL:this.fontCSSURL}; }; } //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font size using Select element * @name SE2M_FontSizeWithLayerUI.js */ nhn.husky.SE2M_FontSizeWithLayerUI = jindo.$Class({ name : "SE2M_FontSizeWithLayerUI", $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ //@ec this.oDropdownLayer = jindo.$$.getSingle("DIV.husky_se_fontSize_layer", elAppContainer); //@ec[ this.elFontSizeLabel = jindo.$$.getSingle("SPAN.husky_se2m_current_fontSize", elAppContainer); this.aLIFontSizes = jindo.$A(jindo.$$("LI", this.oDropdownLayer)).filter(function(v,i,a){return (v.firstChild != null);})._array; //@ec] this.sDefaultText = this.elFontSizeLabel.innerHTML; }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["fontSize", "click", "SE2M_TOGGLE_FONTSIZE_LAYER"]); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aLIFontSizes]); for(var i=0; i<this.aLIFontSizes.length; i++){ this.oApp.registerBrowserEvent(this.aLIFontSizes[i], "click", "SET_FONTSIZE", [this._getFontSizeFromLI(this.aLIFontSizes[i])]); } }, $ON_SE2M_TOGGLE_FONTSIZE_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oDropdownLayer, null, "SELECT_UI", ["fontSize"], "DESELECT_UI", ["fontSize"]]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['size']); }, _rxPX : /px$/i, _rxPT : /pt$/i, $ON_MSG_STYLE_CHANGED : function(sAttributeName, sAttributeValue){ if(sAttributeName == "fontSize"){ // [SMARTEDITORSUS-1600] if(this._rxPX.test(sAttributeValue)){ // as-is /* if(sAttributeValue.match(/px$/)){ var num = parseFloat(sAttributeValue.replace("px", "")).toFixed(0); if(this.mapPX2PT[num]){ sAttributeValue = this.mapPX2PT[num] + "pt"; }else{ if(sAttributeValue > 0){ sAttributeValue = num + "px"; }else{ sAttributeValue = this.sDefaultText; } }*/ /** * Chrome의 경우, * jindo.$Element().css()에서 대상 Element에 구하고자 하는 style 값이 명시되어 있지 않다면, * 실제 수행되는 메서드는 window.getComputedStyle()이다. * * 이 메서드를 거치면 px 단위로 값을 가져오게 되는데, * WYSIWYGDocument.body에 pt 단위로 값이 설정되어 있었다면 * px : pt = 72 : 96 의 비례에 의해 * 변환된 px 값을 획득하게 되며, * * 아래 parseFloat()의 특성 상 * 소수점 16자리부터는 버려질 수 있으며, * * 이 경우 발생할 수 있는 오차는 * pt 기준으로 3.75E-16 pt이다. * * 0.5pt 크기로 구간을 설정하였기 때문에 * 이 오차는 설정에 지장을 주지 않는다. * * 위의 기존 방식은 계산을 거치지 않을 뿐 아니라, * 소수점 첫째 자리부터 무조건 반올림하기 때문에 * 결과에 따라 0.375 pt의 오차가 발생할 수 있었다. * */ var num = parseFloat(sAttributeValue.replace(this._rxPX, "")); if(num > 0){ // px : pt = 72 : 96 sAttributeValue = num * 72 / 96 + "pt"; }else{ sAttributeValue = this.sDefaultText; } // --[SMARTEDITORSUS-1600] } // [SMARTEDITORSUS-1600] // 산술 계산을 통해 일차적으로 pt로 변환된 값을 0.5pt 구간을 적용하여 보정하되, 보다 가까운 쪽으로 설정한다. if(this._rxPT.test(sAttributeValue)){ var num = parseFloat(sAttributeValue.replace(this._rxPT, "")); var integerPart = Math.floor(num); // 정수 부분 var decimalPart = num - integerPart; // 소수 부분 // 보정 기준은 소수 부분이며, 반올림 단위는 0.25pt if(decimalPart >= 0 && decimalPart < 0.25){ num = integerPart + 0; }else if(decimalPart >= 0.25 && decimalPart < 0.75){ num = integerPart + 0.5; }else{ num = integerPart + 1; } // 보정된 pt sAttributeValue = num + "pt"; } // --[SMARTEDITORSUS-1600] if(!sAttributeValue){ sAttributeValue = this.sDefaultText; } var elLi = this._getMatchingLI(sAttributeValue); this._clearFontSizeSelection(); if(elLi){ this.elFontSizeLabel.innerHTML = sAttributeValue; jindo.$Element(elLi).addClass("active"); }else{ this.elFontSizeLabel.innerHTML = sAttributeValue; } } }, $ON_SET_FONTSIZE : function(sFontSize){ if(!sFontSize){return;} this.oApp.exec("SET_WYSIWYG_STYLE", [{"fontSize":sFontSize}]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _getMatchingLI : function(sFontSize){ var elLi; sFontSize = sFontSize.toLowerCase(); for(var i=0; i<this.aLIFontSizes.length; i++){ elLi = this.aLIFontSizes[i]; if(this._getFontSizeFromLI(elLi).toLowerCase() == sFontSize){return elLi;} } return null; }, _getFontSizeFromLI : function(elLi){ return elLi.firstChild.firstChild.style.fontSize; }, _clearFontSizeSelection : function(elLi){ for(var i=0; i<this.aLIFontSizes.length; i++){ jindo.$Element(this.aLIFontSizes[i]).removeClass("active"); } } }); //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to hyperlink * @name hp_SE_Hyperlink.js */ nhn.husky.SE2M_Hyperlink = jindo.$Class({ name : "SE2M_Hyperlink", sATagMarker : "HTTP://HUSKY_TMP.MARKER/", _assignHTMLElements : function(elAppContainer){ this.oHyperlinkButton = jindo.$$.getSingle("li.husky_seditor_ui_hyperlink", elAppContainer); this.oHyperlinkLayer = jindo.$$.getSingle("div.se2_layer", this.oHyperlinkButton); this.oLinkInput = jindo.$$.getSingle("INPUT[type=text]", this.oHyperlinkLayer); this.oBtnConfirm = jindo.$$.getSingle("button.se2_apply", this.oHyperlinkLayer); this.oBtnCancel = jindo.$$.getSingle("button.se2_cancel", this.oHyperlinkLayer); //this.oCbNewWin = jindo.$$.getSingle("INPUT[type=checkbox]", this.oHyperlinkLayer) || null; }, _generateAutoLink : function(sAll, sBreaker, sURL, sWWWURL, sHTTPURL) { sBreaker = sBreaker || ""; var sResult; if (sWWWURL){ sResult = '<a href="http://'+sWWWURL+'">'+sURL+'</a>'; } else { sResult = '<a href="'+sHTTPURL+'">'+sURL+'</a>'; } return sBreaker+sResult; }, /** * [SMARTEDITORSUS-1405] 자동링크 비활성화 옵션을 체크해서 처리한다. * $ON_REGISTER_CONVERTERS 메시지가 SE_EditingAreaManager.$ON_MSG_APP_READY 에서 수행되므로 먼저 처리한다. */ $BEFORE_MSG_APP_READY : function(){ var htOptions = nhn.husky.SE2M_Configuration.SE2M_Hyperlink; if(htOptions && htOptions.bAutolink === false){ // 자동링크 컨버터 비활성화 this.$ON_REGISTER_CONVERTERS = null; // UI enable/disable 처리 제외 this.$ON_DISABLE_MESSAGE = null; this.$ON_ENABLE_MESSAGE = null; // 브라우저의 자동링크기능 비활성화 try{ this.oApp.getWYSIWYGDocument().execCommand("AutoUrlDetect", false, false); } catch(e){} } }, $ON_MSG_APP_READY : function(){ this.bLayerShown = false; this.oApp.exec("REGISTER_UI_EVENT", ["hyperlink", "click", "TOGGLE_HYPERLINK_LAYER"]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+k", "TOGGLE_HYPERLINK_LAYER", []]); }, $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER_DOM", ["IR_TO_DB", jindo.$Fn(this.irToDb, this).bind()]); }, $LOCAL_BEFORE_FIRST : function(sMsg){ if(!!sMsg.match(/(REGISTER_CONVERTERS)/)){ this.oApp.acceptLocalBeforeFirstAgain(this, true); return true; } this._assignHTMLElements(this.oApp.htOptions.elAppContainer); this.sRXATagMarker = this.sATagMarker.replace(/\//g, "\\/").replace(/\./g, "\\."); this.oApp.registerBrowserEvent(this.oBtnConfirm, "click", "APPLY_HYPERLINK"); this.oApp.registerBrowserEvent(this.oBtnCancel, "click", "HIDE_ACTIVE_LAYER"); this.oApp.registerBrowserEvent(this.oLinkInput, "keydown", "EVENT_HYPERLINK_KEYDOWN"); }, //@lazyload_js TOGGLE_HYPERLINK_LAYER,APPLY_HYPERLINK[ $ON_TOGGLE_HYPERLINK_LAYER : function(){ if(!this.bLayerShown){ this.oApp.exec("IE_FOCUS", []); this.oSelection = this.oApp.getSelection(); } // hotkey may close the layer right away so delay here this.oApp.delayedExec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oHyperlinkLayer, null, "MSG_HYPERLINK_LAYER_SHOWN", [], "MSG_HYPERLINK_LAYER_HIDDEN", [""]], 0); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['hyperlink']); }, $ON_MSG_HYPERLINK_LAYER_SHOWN : function(){ this.bLayerShown = true; var oAnchor = this.oSelection.findAncestorByTagName("A"); if (!oAnchor) { oAnchor = this._getSelectedNode(); } //this.oCbNewWin.checked = false; if(oAnchor && !this.oSelection.collapsed){ this.oSelection.selectNode(oAnchor); this.oSelection.select(); var sTarget = oAnchor.target; //if(sTarget && sTarget == "_blank"){this.oCbNewWin.checked = true;} // href속성에 문제가 있을 경우, 예: href="http://na&nbsp;&nbsp; ver.com", IE에서 oAnchor.href 접근 시에 알수 없는 오류를 발생시킴 try{ var sHref = oAnchor.getAttribute("href"); this.oLinkInput.value = sHref && sHref.indexOf("#") == -1 ? sHref : "http://"; }catch(e){ this.oLinkInput.value = "http://"; } this.bModify = true; }else{ this.oLinkInput.value = "http://"; this.bModify = false; } this.oApp.delayedExec("SELECT_UI", ["hyperlink"], 0); this.oLinkInput.focus(); this.oLinkInput.value = this.oLinkInput.value; this.oLinkInput.select(); }, $ON_MSG_HYPERLINK_LAYER_HIDDEN : function(){ this.bLayerShown = false; this.oApp.exec("DESELECT_UI", ["hyperlink"]); }, _validateTarget : function() { var oNavigator = jindo.$Agent().navigator(), bReturn = true; if(oNavigator.ie) { jindo.$A(this.oSelection.getNodes(true)).forEach(function(elNode, index, array){ if(!!elNode && elNode.nodeType == 1 && elNode.tagName.toLowerCase() == "iframe" && elNode.getAttribute('s_type').toLowerCase() == "db") { bReturn = false; jindo.$A.Break(); } jindo.$A.Continue(); }, this); } return bReturn; }, $ON_APPLY_HYPERLINK : function(){ // [SMARTEDITORSUS-1451] 글감에 링크를 적용하지 않도록 처리 if(!this._validateTarget()){ alert(this.oApp.$MSG("SE_Hyperlink.invalidTarget")); return; } var sURL = this.oLinkInput.value; if(!/^((http|https|ftp|mailto):(?:\/\/)?)/.test(sURL)){ sURL = "http://"+sURL; } sURL = sURL.replace(/\s+$/, ""); var oAgent = jindo.$Agent().navigator(); var sBlank = ""; this.oApp.exec("IE_FOCUS", []); if(oAgent.ie){sBlank = "<span style=\"text-decoration:none;\">&nbsp;</span>";} if(this._validateURL(sURL)){ //if(this.oCbNewWin.checked){ // if(false){ // sTarget = "_blank"; // }else{ sTarget = "_self"; //} this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["HYPERLINK", {sSaveTarget:(this.bModify ? "A" : null)}]); var sBM; if(this.oSelection.collapsed){ var str = "<a href='" + sURL + "' target="+sTarget+">" + sURL + "</a>" + sBlank; this.oSelection.pasteHTML(str); sBM = this.oSelection.placeStringBookmark(); }else{ // 브라우저에서 제공하는 execcommand에 createLink로는 타겟을 지정할 수가 없다. // 그렇기 때문에, 더미 URL을 createLink에 넘겨서 링크를 먼저 걸고, 이후에 loop을 돌면서 더미 URL을 가진 A태그를 찾아서 정상 URL 및 타겟을 세팅 해 준다. sBM = this.oSelection.placeStringBookmark(); this.oSelection.select(); // [SMARTEDITORSUS-61] TD 안에 있는 텍스트를 전체 선택하여 URL 변경하면 수정되지 않음 (only IE8) // SE_EditingArea_WYSIWYG 에서는 IE인 경우, beforedeactivate 이벤트가 발생하면 현재의 Range를 저장하고, RESTORE_IE_SELECTION 메시지가 발생하면 저장된 Range를 적용한다. // IE8 또는 IE7 호환모드이고 TD 안의 텍스트 전체를 선택한 경우 Bookmark 생성 후의 select()를 처리할 때 // HuskyRange 에서 호출되는 this._oSelection.empty(); 에서 beforedeactivate 가 발생하여 empty 처리된 selection 이 저장되는 문제가 있어 링크가 적용되지 않음. // 올바른 selection 이 저장되어 EXECCOMMAND에서 링크가 적용될 수 있도록 함 if(oAgent.ie && (oAgent.version === 8 || oAgent.nativeVersion === 8)){ // nativeVersion 으로 IE7 호환모드인 경우 확인 this.oApp.exec("IE_FOCUS", []); this.oSelection.moveToBookmark(sBM); this.oSelection.select(); } // createLink 이후에 이번에 생성된 A 태그를 찾을 수 있도록 nSession을 포함하는 더미 링크를 만든다. var nSession = Math.ceil(Math.random()*10000); if(sURL == ""){ // unlink this.oApp.exec("EXECCOMMAND", ["unlink"]); }else{ // createLink if(this._isExceptional()){ this.oApp.exec("EXECCOMMAND", ["unlink", false, "", {bDontAddUndoHistory: true}]); var sTempUrl = "<a href='" + sURL + "' target="+sTarget+">"; jindo.$A(this.oSelection.getNodes(true)).forEach(function(value, index, array){ var oEmptySelection = this.oApp.getEmptySelection(); if(value.nodeType === 3){ oEmptySelection.selectNode(value); oEmptySelection.pasteHTML(sTempUrl + value.nodeValue + "</a>"); }else if(value.nodeType === 1 && value.tagName === "IMG"){ oEmptySelection.selectNode(value); oEmptySelection.pasteHTML(sTempUrl + jindo.$Element(value).outerHTML() + "</a>"); } }, this); }else{ this.oApp.exec("EXECCOMMAND", ["createLink", false, this.sATagMarker+nSession+encodeURIComponent(sURL), {bDontAddUndoHistory: true}]); } } var oDoc = this.oApp.getWYSIWYGDocument(); var aATags = oDoc.body.getElementsByTagName("A"); var nLen = aATags.length; var rxMarker = new RegExp(this.sRXATagMarker+nSession, "gi"); var elATag; for(var i=0; i<nLen; i++){ elATag = aATags[i]; var sHref = ""; try{ sHref = elATag.getAttribute("href"); }catch(e){} if (sHref && sHref.match(rxMarker)) { var sNewHref = sHref.replace(rxMarker, ""); var sDecodeHref = decodeURIComponent(sNewHref); if(oAgent.ie){ jindo.$Element(elATag).attr({ "href" : sDecodeHref, "target" : sTarget }); //}else if(oAgent.firefox){ }else{ var sAContent = jindo.$Element(elATag).html(); jindo.$Element(elATag).attr({ "href" : sDecodeHref, "target" : sTarget }); if(this._validateURL(sAContent)){ jindo.$Element(elATag).html(jindo.$Element(elATag).attr("href")); } } /*else{ elATag.href = sDecodeHref; } */ } } } this.oApp.exec("HIDE_ACTIVE_LAYER"); setTimeout(jindo.$Fn(function(){ var oSelection = this.oApp.getEmptySelection(); oSelection.moveToBookmark(sBM); oSelection.collapseToEnd(); oSelection.select(); oSelection.removeStringBookmark(sBM); this.oApp.exec("FOCUS"); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["HYPERLINK", {sSaveTarget:(this.bModify ? "A" : null)}]); }, this).bind(), 17); }else{ alert(this.oApp.$MSG("SE_Hyperlink.invalidURL")); this.oLinkInput.focus(); } }, _isExceptional : function(){ var oNavigator = jindo.$Agent().navigator(), bImg = false, bEmail = false; if(!oNavigator.ie){ return false; } // [SMARTEDITORSUS-612] 이미지 선택 후 링크 추가했을 때 링크가 걸리지 않는 문제 if(this.oApp.getWYSIWYGDocument().selection && this.oApp.getWYSIWYGDocument().selection.type === "None"){ bImg = jindo.$A(this.oSelection.getNodes()).some(function(value, index, array){ if(value.nodeType === 1 && value.tagName === "IMG"){ return true; } }, this); if(bImg){ return true; } } if(oNavigator.nativeVersion > 8){ // version? nativeVersion? return false; } // [SMARTEDITORSUS-579] IE8 이하에서 E-mail 패턴 문자열에 URL 링크 못거는 이슈 bEmail = jindo.$A(this.oSelection.getTextNodes()).some(function(value, index, array){ if(value.nodeValue.indexOf("@") >= 1){ return true; } }, this); if(bEmail){ return true; } return false; }, //@lazyload_js] $ON_EVENT_HYPERLINK_KEYDOWN : function(oEvent){ if (oEvent.key().enter){ this.oApp.exec("APPLY_HYPERLINK"); oEvent.stop(); } }, /** * [MUG-1265] 버튼이 사용불가 상태이면 자동변환기능을 막는다. * @see http://stackoverflow.com/questions/7556007/avoid-transformation-text-to-link-ie-contenteditable-mode * IE9 이전 버전은 AutoURlDetect을 사용할 수 없어 오류 발생되기 때문에, try catch로 블럭 처리(http://msdn.microsoft.com/en-us/library/aa769893%28VS.85%29.aspx) */ $ON_DISABLE_MESSAGE : function(sCmd) { if(sCmd !== "TOGGLE_HYPERLINK_LAYER"){ return; } try{ this.oApp.getWYSIWYGDocument().execCommand("AutoUrlDetect", false, false); } catch(e){} this._bDisabled = true; }, /** * [MUG-1265] 버튼이 사용가능 상태이면 자동변환기능을 복원해준다. */ $ON_ENABLE_MESSAGE : function(sCmd) { if(sCmd !== "TOGGLE_HYPERLINK_LAYER"){ return; } try{ this.oApp.getWYSIWYGDocument().execCommand("AutoUrlDetect", false, true); } catch(e){} this._bDisabled = false; }, irToDb : function(oTmpNode){ if(this._bDisabled){ // [MUG-1265] 버튼이 사용불가 상태이면 자동변환하지 않는다. return; } //저장 시점에 자동 링크를 위한 함수. //[SMARTEDITORSUS-1207][IE][메일] object 삽입 후 글을 저장하면 IE 브라우저가 죽어버리는 현상 //원인 : 확인 불가. IE 저작권 관련 이슈로 추정 //해결 : contents를 가지고 있는 div 태그를 이 함수 내부에서 복사하여 수정 후 call by reference로 넘어온 변수의 innerHTML을 변경 var oCopyNode = oTmpNode.cloneNode(true); try{ oCopyNode.innerHTML; }catch(e) { oCopyNode = jindo.$(oTmpNode.outerHTML); } var oTmpRange = this.oApp.getEmptySelection(); var elFirstNode = oTmpRange._getFirstRealChild(oCopyNode); var elLastNode = oTmpRange._getLastRealChild(oCopyNode); var waAllNodes = jindo.$A(oTmpRange._getNodesBetween(elFirstNode, elLastNode)); var aAllTextNodes = waAllNodes.filter(function(elNode){return (elNode && elNode.nodeType === 3);}).$value(); var a = aAllTextNodes; /* // 텍스트 검색이 용이 하도록 끊어진 텍스트 노드가 있으면 합쳐줌. (화면상으로 ABC라고 보이나 상황에 따라 실제 2개의 텍스트 A, BC로 이루어져 있을 수 있음. 이를 ABC 하나의 노드로 만들어 줌.) // 문제 발생 가능성에 비해서 퍼포먼스나 사이드 이펙트 가능성 높아 일단 주석 var aCleanTextNodes = []; for(var i=0, nLen=aAllTextNodes.length; i<nLen; i++){ if(a[i].nextSibling && a[i].nextSibling.nodeType === 3){ a[i].nextSibling.nodeValue += a[i].nodeValue; a[i].parentNode.removeChild(a[i]); }else{ aCleanTextNodes[aCleanTextNodes.length] = a[i]; } } */ var aCleanTextNodes = aAllTextNodes; // IE에서 PRE를 제외한 다른 태그 하위에 있는 텍스트 노드는 줄바꿈 등의 값을 변질시킴 var elTmpDiv = this.oApp.getWYSIWYGDocument().createElement("DIV"); var elParent, bAnchorFound; var sTmpStr = "@"+(new Date()).getTime()+"@"; var rxTmpStr = new RegExp(sTmpStr, "g"); for(var i=0, nLen=aAllTextNodes.length; i<nLen; i++){ // Anchor가 이미 걸려 있는 텍스트이면 링크를 다시 걸지 않음. elParent = a[i].parentNode; bAnchorFound = false; while(elParent){ if(elParent.tagName === "A" || elParent.tagName === "PRE"){ bAnchorFound = true; break; } elParent = elParent.parentNode; } if(bAnchorFound){ continue; } // www.또는 http://으로 시작하는 텍스트에 링크 걸어 줌 // IE에서 텍스트 노드 앞쪽의 스페이스나 주석등이 사라지는 현상이 있어 sTmpStr을 앞에 붙여줌. elTmpDiv.innerHTML = ""; try { elTmpDiv.appendChild(a[i].cloneNode(true)); // IE에서 innerHTML를 이용 해 직접 텍스트 노드 값을 할당 할 경우 줄바꿈등이 깨질 수 있어, 텍스트 노드로 만들어서 이를 바로 append 시켜줌 elTmpDiv.innerHTML = (sTmpStr+elTmpDiv.innerHTML).replace(/(&nbsp|\s)?(((?!http:\/\/)www\.(?:(?!\&nbsp;|\s|"|').)+)|(http:\/\/(?:(?!&nbsp;|\s|"|').)+))/ig, this._generateAutoLink); // innerHTML 내에 텍스트가 있을 경우 insert 시에 주변 텍스트 노드와 합쳐지는 현상이 있어 div로 위치를 먼저 잡고 하나씩 삽입 a[i].parentNode.insertBefore(elTmpDiv, a[i]); a[i].parentNode.removeChild(a[i]); } catch(e1) { } while(elTmpDiv.firstChild){ elTmpDiv.parentNode.insertBefore(elTmpDiv.firstChild, elTmpDiv); } elTmpDiv.parentNode.removeChild(elTmpDiv); // alert(a[i].nodeValue); } elTmpDiv = oTmpRange = elFirstNode = elLastNode = waAllNodes = aAllTextNodes = a = aCleanTextNodes = elParent = null; oCopyNode.innerHTML = oCopyNode.innerHTML.replace(rxTmpStr, ""); oTmpNode.innerHTML = oCopyNode.innerHTML; oCopyNode = null; //alert(oTmpNode.innerHTML); }, _getSelectedNode : function(){ var aNodes = this.oSelection.getNodes(); for (var i = 0; i < aNodes.length; i++) { if (aNodes[i].tagName && aNodes[i].tagName == "A") { return aNodes[i]; } } }, _validateURL : function(sURL){ if(!sURL){return false;} // escape 불가능한 %가 들어있나 확인 try{ var aURLParts = sURL.split("?"); aURLParts[0] = aURLParts[0].replace(/%[a-z0-9]{2}/gi, "U"); decodeURIComponent(aURLParts[0]); }catch(e){ return false; } return /^(http|https|ftp|mailto):(\/\/)?(([-가-힣]|\w)+(?:[\/\.:@]([-가-힣]|\w)+)+)\/?(.*)?\s*$/i.test(sURL); } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the lineheight using layer * @name hp_SE2M_LineHeightWithLayerUI.js */ nhn.husky.SE2M_LineHeightWithLayerUI = jindo.$Class({ name : "SE2M_LineHeightWithLayerUI", MIN_LINE_HEIGHT : 50, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["lineHeight", "click", "SE2M_TOGGLE_LINEHEIGHT_LAYER"]); }, //@lazyload_js SE2M_TOGGLE_LINEHEIGHT_LAYER[ _assignHTMLObjects : function(elAppContainer) { //this.elLineHeightSelect = jindo.$$.getSingle("SELECT.husky_seditor_ui_lineHeight_select", elAppContainer); this.oDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_lineHeight_layer", elAppContainer); this.aLIOptions = jindo.$A(jindo.$$("LI", this.oDropdownLayer)).filter(function(v,i,a){return (v.firstChild !== null);})._array; this.oInput = jindo.$$.getSingle("INPUT", this.oDropdownLayer); var tmp = jindo.$$.getSingle(".husky_se2m_lineHeight_direct_input", this.oDropdownLayer); tmp = jindo.$$("BUTTON", tmp); this.oBtn_up = tmp[0]; this.oBtn_down = tmp[1]; this.oBtn_ok = tmp[2]; this.oBtn_cancel = tmp[3]; }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLObjects(this.oApp.htOptions.elAppContainer); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aLIOptions]); for(var i=0; i<this.aLIOptions.length; i++){ this.oApp.registerBrowserEvent(this.aLIOptions[i], "click", "SET_LINEHEIGHT_FROM_LAYER_UI", [this._getLineHeightFromLI(this.aLIOptions[i])]); } this.oApp.registerBrowserEvent(this.oBtn_up, "click", "SE2M_INC_LINEHEIGHT", []); this.oApp.registerBrowserEvent(this.oBtn_down, "click", "SE2M_DEC_LINEHEIGHT", []); this.oApp.registerBrowserEvent(this.oBtn_ok, "click", "SE2M_SET_LINEHEIGHT_FROM_DIRECT_INPUT", []); this.oApp.registerBrowserEvent(this.oBtn_cancel, "click", "SE2M_CANCEL_LINEHEIGHT", []); this.oApp.registerBrowserEvent(this.oInput, "keydown", "EVENT_SE2M_LINEHEIGHT_KEYDOWN"); }, $ON_EVENT_SE2M_LINEHEIGHT_KEYDOWN : function(oEvent){ if (oEvent.key().enter){ this.oApp.exec("SE2M_SET_LINEHEIGHT_FROM_DIRECT_INPUT"); oEvent.stop(); } }, $ON_SE2M_TOGGLE_LINEHEIGHT_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oDropdownLayer, null, "LINEHEIGHT_LAYER_SHOWN", [], "LINEHEIGHT_LAYER_HIDDEN", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['lineheight']); }, $ON_SE2M_INC_LINEHEIGHT : function(){ this.oInput.value = parseInt(this.oInput.value, 10) || this.MIN_LINE_HEIGHT; this.oInput.value++; }, $ON_SE2M_DEC_LINEHEIGHT : function(){ this.oInput.value = parseInt(this.oInput.value, 10) || this.MIN_LINE_HEIGHT; if(this.oInput.value > this.MIN_LINE_HEIGHT){this.oInput.value--;} }, $ON_LINEHEIGHT_LAYER_SHOWN : function(){ this.oApp.exec("SELECT_UI", ["lineHeight"]); this.oInitialSelection = this.oApp.getSelection(); var nLineHeight = this.oApp.getLineStyle("lineHeight"); if(nLineHeight != null && nLineHeight !== 0){ this.oInput.value = (nLineHeight*100).toFixed(0); var elLi = this._getMatchingLI(this.oInput.value+"%"); if(elLi){jindo.$Element(elLi.firstChild).addClass("active");} }else{ this.oInput.value = ""; } }, $ON_LINEHEIGHT_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["lineHeight"]); this._clearOptionSelection(); }, $ON_SE2M_SET_LINEHEIGHT_FROM_DIRECT_INPUT : function(){ var nInputValue = parseInt(this.oInput.value, 10); var sValue = (nInputValue < this.MIN_LINE_HEIGHT) ? this.MIN_LINE_HEIGHT : nInputValue; this._setLineHeightAndCloseLayer(sValue); }, $ON_SET_LINEHEIGHT_FROM_LAYER_UI : function(sValue){ this._setLineHeightAndCloseLayer(sValue); }, $ON_SE2M_CANCEL_LINEHEIGHT : function(){ this.oInitialSelection.select(); this.oApp.exec("HIDE_ACTIVE_LAYER"); }, _setLineHeightAndCloseLayer : function(sValue){ var nLineHeight = parseInt(sValue, 10)/100; if(nLineHeight>0){ this.oApp.exec("SET_LINE_STYLE", ["lineHeight", nLineHeight]); }else{ alert(this.oApp.$MSG("SE_LineHeight.invalidLineHeight")); } this.oApp.exec("SE2M_TOGGLE_LINEHEIGHT_LAYER", []); var oNavigator = jindo.$Agent().navigator(); if(oNavigator.chrome || oNavigator.safari){ this.oApp.exec("FOCUS"); // [SMARTEDITORSUS-654] } }, _getMatchingLI : function(sValue){ var elLi; sValue = sValue.toLowerCase(); for(var i=0; i<this.aLIOptions.length; i++){ elLi = this.aLIOptions[i]; if(this._getLineHeightFromLI(elLi).toLowerCase() == sValue){return elLi;} } return null; }, _getLineHeightFromLI : function(elLi){ return elLi.firstChild.firstChild.innerHTML; }, _clearOptionSelection : function(elLi){ for(var i=0; i<this.aLIOptions.length; i++){ jindo.$Element(this.aLIOptions[i].firstChild).removeClass("active"); } } //@lazyload_js] }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to setting/changing the line style * @name hp_SE_LineStyler.js */ nhn.husky.SE2M_LineStyler = jindo.$Class({ name : "SE2M_LineStyler", $BEFORE_MSG_APP_READY : function() { this.oApp.exec("ADD_APP_PROPERTY", ["getLineStyle", jindo.$Fn(this.getLineStyle, this).bind()]); }, //SMARTEDITORSUS-987 SE2M_TOGGLE_LINEHEIGHT_LAYER,SET_LINE_STYLE 동적 로딩 제거 $ON_SE2M_TOGGLE_LINEHEIGHT_LAYER : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["getLineStyle", jindo.$Fn(this.getLineStyle, this).bind()]); }, $ON_SET_LINE_STYLE : function(sStyleName, styleValue, htOptions){ this.oSelection = this.oApp.getSelection(); var nodes = this._getSelectedNodes(false); this.setLineStyle(sStyleName, styleValue, htOptions, nodes); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, $ON_SET_LINE_BLOCK_STYLE : function(sStyleName, styleValue, htOptions){ this.oSelection = this.oApp.getSelection(); this.setLineBlockStyle(sStyleName, styleValue, htOptions); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, getLineStyle : function(sStyle){ var nodes = this._getSelectedNodes(false); var curWrapper, prevWrapper; var sCurStyle, sStyleValue; if(nodes.length === 0){return null;} var iLength = nodes.length; if(iLength === 0){ sStyleValue = null; }else{ prevWrapper = this._getLineWrapper(nodes[0]); sStyleValue = this._getWrapperLineStyle(sStyle, prevWrapper); } var firstNode = this.oSelection.getStartNode(); if(sStyleValue != null){ for(var i=1; i<iLength; i++){ if(this._isChildOf(nodes[i], curWrapper)){continue;} if(!nodes[i]){continue;} curWrapper = this._getLineWrapper(nodes[i]); if(curWrapper == prevWrapper){continue;} sCurStyle = this._getWrapperLineStyle(sStyle, curWrapper); if(sCurStyle != sStyleValue){ sStyleValue = null; break; } prevWrapper = curWrapper; } } curWrapper = this._getLineWrapper(nodes[iLength-1]); var lastNode = this.oSelection.getEndNode(); selectText = jindo.$Fn(function(firstNode, lastNode){ this.oSelection.setEndNodes(firstNode, lastNode); this.oSelection.select(); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, this).bind(firstNode, lastNode); setTimeout(selectText, 0); return sStyleValue; }, // height in percentage. For example pass 1 to set the line height to 100% and 1.5 to set it to 150% setLineStyle : function(sStyleName, styleValue, htOptions, nodes){ thisRef = this; var bWrapperCreated = false; function _setLineStyle(div, sStyleName, styleValue){ if(!div){ bWrapperCreated = true; // try to wrap with P first try{ div = thisRef.oSelection.surroundContentsWithNewNode("P"); // if the range contains a block-level tag, wrap it with a DIV }catch(e){ div = thisRef.oSelection.surroundContentsWithNewNode("DIV"); } } if(typeof styleValue == "function"){ styleValue(div); }else{ div.style[sStyleName] = styleValue; } if(div.childNodes.length === 0){ div.innerHTML = "&nbsp;"; } return div; } function isInBody(node){ while(node && node.tagName != "BODY"){ node = nhn.DOMFix.parentNode(node); } if(!node){return false;} return true; } if(nodes.length === 0){ return; } var curWrapper, prevWrapper; var iLength = nodes.length; if((!htOptions || !htOptions["bDontAddUndoHistory"])){ this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["LINE STYLE"]); } prevWrapper = this._getLineWrapper(nodes[0]); prevWrapper = _setLineStyle(prevWrapper, sStyleName, styleValue); var startNode = prevWrapper; var endNode = prevWrapper; for(var i=1; i<iLength; i++){ // Skip the node if a copy of the node were wrapped and the actual node no longer exists within the document. try{ if(!isInBody(nhn.DOMFix.parentNode(nodes[i]))){continue;} }catch(e){continue;} if(this._isChildOf(nodes[i], curWrapper)){continue;} curWrapper = this._getLineWrapper(nodes[i]); if(curWrapper == prevWrapper){continue;} curWrapper = _setLineStyle(curWrapper, sStyleName, styleValue); prevWrapper = curWrapper; } endNode = curWrapper || startNode; if(bWrapperCreated && (!htOptions || !htOptions.bDoNotSelect)) { setTimeout(jindo.$Fn(function(startNode, endNode, htOptions){ if(startNode == endNode){ this.oSelection.selectNodeContents(startNode); if(startNode.childNodes.length==1 && startNode.firstChild.tagName == "BR"){ this.oSelection.collapseToStart(); } }else{ this.oSelection.setEndNodes(startNode, endNode); } this.oSelection.select(); if((!htOptions || !htOptions["bDontAddUndoHistory"])){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["LINE STYLE"]); } }, this).bind(startNode, endNode, htOptions), 0); } }, /** * Block Style 적용 */ setLineBlockStyle : function(sStyleName, styleValue, htOptions) { var htSelectedTDs = {}; //var aTempNodes = aTextnodes = []; var aTempNodes = []; var aTextnodes = []; this.oApp.exec("GET_SELECTED_TD_BLOCK",['aTdCells',htSelectedTDs]); var aNodes = htSelectedTDs.aTdCells; for( var j = 0; j < aNodes.length ; j++){ this.oSelection.selectNode(aNodes[j]); aTempNodes = this.oSelection.getNodes(); for(var k = 0, m = 0; k < aTempNodes.length ; k++){ if(aTempNodes[k].nodeType == 3 || (aTempNodes[k].tagName == "BR" && k == 0)) { aTextnodes[m] = aTempNodes[k]; m ++; } } this.setLineStyle(sStyleName, styleValue, htOptions, aTextnodes); aTempNodes = aTextnodes = []; } }, getTextNodes : function(bSplitTextEndNodes, oSelection){ var txtFilter = function(oNode){ // 편집 중에 생겨난 빈 LI/P에도 스타일 먹이도록 포함함 if((oNode.nodeType == 3 && oNode.nodeValue != "\n" && oNode.nodeValue != "") || (oNode.tagName == "LI" && oNode.innerHTML == "") || (oNode.tagName == "P" && oNode.innerHTML == "")){ return true; }else{ return false; } }; return oSelection.getNodes(bSplitTextEndNodes, txtFilter); }, _getSelectedNodes : function(bDontUpdate){ if(!bDontUpdate){ this.oSelection = this.oApp.getSelection(); } // 페이지 최하단에 빈 LI 있을 경우 해당 LI 포함하도록 expand if(this.oSelection.endContainer.tagName == "LI" && this.oSelection.endOffset == 0 && this.oSelection.endContainer.innerHTML == ""){ this.oSelection.setEndAfter(this.oSelection.endContainer); } if(this.oSelection.collapsed){this.oSelection.selectNode(this.oSelection.commonAncestorContainer);} //var nodes = this.oSelection.getTextNodes(); var nodes = this.getTextNodes(false, this.oSelection); if(nodes.length === 0){ var tmp = this.oSelection.getStartNode(); if(tmp){ nodes[0] = tmp; }else{ var elTmp = this.oSelection._document.createTextNode("\u00A0"); this.oSelection.insertNode(elTmp); nodes = [elTmp]; } } return nodes; }, _getWrapperLineStyle : function(sStyle, div){ var sStyleValue = null; if(div && div.style[sStyle]){ sStyleValue = div.style[sStyle]; }else{ div = this.oSelection.commonAncesterContainer; while(div && !this.oSelection.rxLineBreaker.test(div.tagName)){ if(div && div.style[sStyle]){ sStyleValue = div.style[sStyle]; break; } div = nhn.DOMFix.parentNode(div); } } return sStyleValue; }, _isChildOf : function(node, container){ while(node && node.tagName != "BODY"){ if(node == container){return true;} node = nhn.DOMFix.parentNode(node); } return false; }, _getLineWrapper : function(node){ var oTmpSelection = this.oApp.getEmptySelection(); oTmpSelection.selectNode(node); var oLineInfo = oTmpSelection.getLineInfo(); var oStart = oLineInfo.oStart; var oEnd = oLineInfo.oEnd; var a, b; var breakerA, breakerB; var div = null; a = oStart.oNode; breakerA = oStart.oLineBreaker; b = oEnd.oNode; breakerB = oEnd.oLineBreaker; this.oSelection.setEndNodes(a, b); if(breakerA == breakerB){ if(breakerA.tagName == "P" || breakerA.tagName == "DIV" || breakerA.tagName == "LI"){ // if(breakerA.tagName == "P" || breakerA.tagName == "DIV"){ div = breakerA; }else{ this.oSelection.setEndNodes(breakerA.firstChild, breakerA.lastChild); } } return div; } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to detecting the style change * @name hp_SE_WYSIWYGStyleGetter.js */ nhn.husky.SE_WYSIWYGStyleGetter = jindo.$Class({ name : "SE_WYSIWYGStyleGetter", hKeyUp : null, getStyleInterval : 200, oStyleMap : { fontFamily : { type : "Value", css : "fontFamily" }, fontSize : { type : "Value", css : "fontSize" }, lineHeight : { type : "Value", css : "lineHeight", converter : function(sValue, oStyle){ if(!sValue.match(/px$/)){ return sValue; } return Math.ceil((parseInt(sValue, 10)/parseInt(oStyle.fontSize, 10))*10)/10; } }, bold : { command : "bold" }, underline : { command : "underline" }, italic : { command : "italic" }, lineThrough : { command : "strikethrough" }, superscript : { command : "superscript" }, subscript : { command : "subscript" }, justifyleft : { command : "justifyleft" }, justifycenter : { command : "justifycenter" }, justifyright : { command : "justifyright" }, justifyfull : { command : "justifyfull" }, orderedlist : { command : "insertorderedlist" }, unorderedlist : { command : "insertunorderedlist" } }, $init : function(){ this.oStyle = this._getBlankStyle(); }, $LOCAL_BEFORE_ALL : function(){ return (this.oApp.getEditingMode() == "WYSIWYG"); }, $ON_MSG_APP_READY : function(){ this.oDocument = this.oApp.getWYSIWYGDocument(); this.oApp.exec("ADD_APP_PROPERTY", ["getCurrentStyle", jindo.$Fn(this.getCurrentStyle, this).bind()]); if(jindo.$Agent().navigator().safari || jindo.$Agent().navigator().chrome || jindo.$Agent().navigator().ie){ this.oStyleMap.textAlign = { type : "Value", css : "textAlign" }; } }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(oEvnet){ /* if(this.hKeyUp){ clearTimeout(this.hKeyUp); } this.oApp.delayedExec("CHECK_STYLE_CHANGE", [], 100); */ this.oApp.exec("CHECK_STYLE_CHANGE"); }, $ON_EVENT_EDITING_AREA_KEYPRESS : function(oEvent){ // ctrl+a in FF triggers keypress event with keyCode 97, other browsers don't throw keypress event for ctrl+a var oKeyInfo; if(this.oApp.oNavigator.firefox){ oKeyInfo = oEvent.key(); if(oKeyInfo.ctrl && oKeyInfo.keyCode == 97){ return; } } if(this.bAllSelected){ this.bAllSelected = false; return; } /* // queryCommandState often fails to return correct result for Korean/Enter. So just ignore them. if(this.oApp.oNavigator.firefox && (oKeyInfo.keyCode == 229 || oKeyInfo.keyCode == 13)){ return; } */ this.oApp.exec("CHECK_STYLE_CHANGE"); //this.oApp.delayedExec("CHECK_STYLE_CHANGE", [], 0); }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ var oKeyInfo = oEvent.key(); // ctrl+a if((this.oApp.oNavigator.ie || this.oApp.oNavigator.firefox) && oKeyInfo.ctrl && oKeyInfo.keyCode == 65){ this.oApp.exec("RESET_STYLE_STATUS"); this.bAllSelected = true; return; } /* backspace 8 enter 13 page up 33 page down 34 end 35 home 36 left arrow 37 up arrow 38 right arrow 39 down arrow 40 insert 45 delete 46 */ // other key strokes are taken care by keypress event if(!(oKeyInfo.keyCode == 8 || (oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40) || oKeyInfo.keyCode == 45 || oKeyInfo.keyCode == 46)) return; // take care of ctrl+a -> delete/bksp sequence if(this.bAllSelected){ // firefox will throw both keydown and keypress events for those input(keydown first), so let keypress take care of them if(this.oApp.oNavigator.firefox){ return; } this.bAllSelected = false; return; } this.oApp.exec("CHECK_STYLE_CHANGE"); }, $ON_CHECK_STYLE_CHANGE : function(){ this._getStyle(); }, $ON_RESET_STYLE_STATUS : function(){ this.oStyle = this._getBlankStyle(); var oBodyStyle = this._getStyleOf(this.oApp.getWYSIWYGDocument().body); this.oStyle.fontFamily = oBodyStyle.fontFamily; this.oStyle.fontSize = oBodyStyle.fontSize; this.oStyle["justifyleft"]="@^"; for(var sAttributeName in this.oStyle){ //this.oApp.exec("SET_STYLE_STATUS", [sAttributeName, this.oStyle[sAttributeName]]); this.oApp.exec("MSG_STYLE_CHANGED", [sAttributeName, this.oStyle[sAttributeName]]); } }, getCurrentStyle : function(){ return this.oStyle; }, _check_style_change : function(){ this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _getBlankStyle : function(){ var oBlankStyle = {}; for(var attributeName in this.oStyleMap){ if(this.oStyleMap[attributeName].type == "Value"){ oBlankStyle[attributeName] = ""; }else{ oBlankStyle[attributeName] = 0; } } return oBlankStyle; }, _getStyle : function(){ var oStyle; if(nhn.CurrentSelection.isCollapsed()){ oStyle = this._getStyleOf(nhn.CurrentSelection.getCommonAncestorContainer()); }else{ var oSelection = this.oApp.getSelection(); var funcFilter = function(oNode){ if (!oNode.childNodes || oNode.childNodes.length == 0) return true; else return false; } var aBottomNodes = oSelection.getNodes(false, funcFilter); if(aBottomNodes.length == 0){ oStyle = this._getStyleOf(oSelection.commonAncestorContainer); }else{ oStyle = this._getStyleOf(aBottomNodes[0]); } } for(attributeName in oStyle){ if(this.oStyleMap[attributeName].converter){ oStyle[attributeName] = this.oStyleMap[attributeName].converter(oStyle[attributeName], oStyle); } if(this.oStyle[attributeName] != oStyle[attributeName]){ this.oApp.exec("MSG_STYLE_CHANGED", [attributeName, oStyle[attributeName]]); } } this.oStyle = oStyle; }, _getStyleOf : function(oNode){ var oStyle = this._getBlankStyle(); // this must not happen if(!oNode){ return oStyle; } if( oNode.nodeType == 3 ){ oNode = oNode.parentNode; }else if( oNode.nodeType == 9 ){ //document에는 css를 적용할 수 없음. oNode = oNode.body; } var welNode = jindo.$Element(oNode); var attribute, cssName; for(var styleName in this.oStyle){ attribute = this.oStyleMap[styleName]; if(attribute.type && attribute.type == "Value"){ try{ if(attribute.css){ var sValue = welNode.css(attribute.css); if(styleName == "fontFamily"){ sValue = sValue.split(/,/)[0]; } oStyle[styleName] = sValue; } else if(attribute.command){ oStyle[styleName] = this.oDocument.queryCommandState(attribute.command); } else { // todo } }catch(e){} }else{ if(attribute.command){ try{ if(this.oDocument.queryCommandState(attribute.command)){ oStyle[styleName] = "@^"; }else{ oStyle[styleName] = "@-"; } }catch(e){} }else{ // todo } } } switch(oStyle["textAlign"]){ case "left": oStyle["justifyleft"]="@^"; break; case "center": oStyle["justifycenter"]="@^"; break; case "right": oStyle["justifyright"]="@^"; break; case "justify": oStyle["justifyfull"]="@^"; break; } // IE에서는 기본 정렬이 queryCommandState로 넘어오지 않아서 정렬이 없다면, 왼쪽 정렬로 가정함 if(oStyle["justifyleft"]=="@-" && oStyle["justifycenter"]=="@-" && oStyle["justifyright"]=="@-" && oStyle["justifyfull"]=="@-"){oStyle["justifyleft"]="@^";} return oStyle; } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to styling the font * @name hp_SE_WYSIWYGStyler.js * @required SE_EditingArea_WYSIWYG, HuskyRangeManager */ nhn.husky.SE_WYSIWYGStyler = jindo.$Class({ name : "SE_WYSIWYGStyler", _sZWSP : "\u200B", // ZWNBSP(\uFEFF) 를 사용하면 IE9 이상의 경우 높이값을 갖지 못해 커서위치가 이상함 [SMARTEDITORSUS-178] $init : function(){ var htBrowser = jindo.$Agent().navigator(); if(!htBrowser.ie || htBrowser.nativeVersion < 9 || document.documentMode < 9){ this._addCursorHolder = function(){}; } }, _addCursorHolder : function(oSelection, oSpan){ var oBody = this.oApp.getWYSIWYGDocument().body, oAncestor, welSpan = jindo.$Element(oSpan), sHtml, tmpTextNode; sHtml = oBody.innerHTML; oAncestor = oBody; if(sHtml === welSpan.outerHTML()){ tmpTextNode = oSelection._document.createTextNode(this._sZWSP); oAncestor.appendChild(tmpTextNode); return; } oAncestor = nhn.husky.SE2M_Utils.findAncestorByTagName("P", oSpan); if(!oAncestor){ return; } sHtml = oAncestor.innerHTML; if(sHtml.indexOf("&nbsp;") > -1){ return; } tmpTextNode = oSelection._document.createTextNode(this._sZWSP); oAncestor.appendChild(tmpTextNode); }, $PRECONDITION : function(sFullCommand, aArgs){ return (this.oApp.getEditingMode() == "WYSIWYG"); }, $ON_SET_WYSIWYG_STYLE : function(oStyles){ var oSelection = this.oApp.getSelection(); var htSelectedTDs = {}; this.oApp.exec("IS_SELECTED_TD_BLOCK",['bIsSelectedTd',htSelectedTDs]); var bSelectedBlock = htSelectedTDs.bIsSelectedTd; // style cursor or !(selected block) if(oSelection.collapsed && !bSelectedBlock){ this.oApp.exec("RECORD_UNDO_ACTION", ["FONT STYLE", {bMustBlockElement : true}]); var oSpan, bNewSpan = false; var elCAC = oSelection.commonAncestorContainer; //var elCAC = nhn.CurrentSelection.getCommonAncestorContainer(); if(elCAC.nodeType == 3){ elCAC = elCAC.parentNode; } // [SMARTEDITORSUS-1648] SPAN > 굵게/밑줄/기울림/취소선이 있는 경우, 상위 SPAN을 찾는다. if(elCAC && oSelection._rxCursorHolder.test(elCAC.innerHTML)){ oSpan = oSelection._findParentSingleSpan(elCAC); } // 스타일을 적용할 SPAN이 없으면 새로 생성 if(!oSpan){ oSpan = this.oApp.getWYSIWYGDocument().createElement("SPAN"); oSpan.innerHTML = this._sZWSP; bNewSpan = true; }else if(oSpan.innerHTML == ""){ // 내용이 아예 없으면 크롬에서 커서가 위치하지 못함 oSpan.innerHTML = this._sZWSP; } var sValue; for(var sName in oStyles){ sValue = oStyles[sName]; if(typeof sValue != "string"){ continue; } oSpan.style[sName] = sValue; } if(bNewSpan){ if(oSelection.startContainer.tagName == "BODY" && oSelection.startOffset === 0){ var oVeryFirstNode = oSelection._getVeryFirstRealChild(this.oApp.getWYSIWYGDocument().body); var bAppendable = true; var elTmp = oVeryFirstNode.cloneNode(false); // some browsers may throw an exception for trying to set the innerHTML of BR/IMG tags try{ elTmp.innerHTML = "test"; if(elTmp.innerHTML != "test"){ bAppendable = false; } }catch(e){ bAppendable = false; } if(bAppendable && elTmp.nodeType == 1 && elTmp.tagName == "BR"){// [SMARTEDITORSUS-311] [FF4] Cursor Holder 인 BR 의 하위노드로 SPAN 을 추가하여 발생하는 문제 oSelection.selectNode(oVeryFirstNode); oSelection.collapseToStart(); oSelection.insertNode(oSpan); }else if(bAppendable && oVeryFirstNode.tagName != "IFRAME" && oVeryFirstNode.appendChild && typeof oVeryFirstNode.innerHTML == "string"){ oVeryFirstNode.appendChild(oSpan); }else{ oSelection.selectNode(oVeryFirstNode); oSelection.collapseToStart(); oSelection.insertNode(oSpan); } }else{ oSelection.collapseToStart(); oSelection.insertNode(oSpan); } }else{ oSelection = this.oApp.getEmptySelection(); } // [SMARTEDITORSUS-229] 새로 생성되는 SPAN 에도 취소선/밑줄 처리 추가 if(!!oStyles.color){ oSelection._checkTextDecoration(oSpan); } // [SMARTEDITORSUS-1648] ZWSP 를 삽입하는 방법을 사용해서 굳이 필요하지는 않지만 만약을 위해 코멘트처리함 //this._addCursorHolder(oSelection, oSpan); // [SMARTEDITORSUS-178] [IE9] 커서가 위로 올라가는 문제 // [SMARTEDITORSUS-1648] oSpan이 굵게//밑줄/기울임/취소선태그보다 상위인 경우, IE에서 굵게//밑줄/기울임/취소선태그 밖으로 나가게 된다. 때문에 SPAN을 새로 만든 경우 oSpan을, 그렇지 않은 경우 elCAC를 잡는다. oSelection.selectNodeContents(bNewSpan?oSpan:elCAC); oSelection.collapseToEnd(); // TODO: focus 는 왜 있는 것일까? => IE에서 style 적용후 포커스가 날아가서 글작성이 안됨??? oSelection._window.focus(); oSelection._window.document.body.focus(); oSelection.select(); // 영역으로 스타일이 잡혀 있는 경우(예:현재 커서가 B블럭 안에 존재) 해당 영역이 사라져 버리는 오류 발생해서 제거 // http://bts.nhncorp.com/nhnbts/browse/COM-912 /* var oCursorStyle = this.oApp.getCurrentStyle(); if(oCursorStyle.bold == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["bold"], 0); } if(oCursorStyle.underline == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["underline"], 0); } if(oCursorStyle.italic == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["italic"], 0); } if(oCursorStyle.lineThrough == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["strikethrough"], 0); } */ // FF3 will actually display %uFEFF when it is followed by a number AND certain font-family is used(like Gulim), so remove the character for FF3 //if(jindo.$Agent().navigator().firefox && jindo.$Agent().navigator().version == 3){ // FF4+ may have similar problems, so ignore the version number // [SMARTEDITORSUS-416] 커서가 올라가지 않도록 BR 을 살려둠 // if(jindo.$Agent().navigator().firefox){ // oSpan.innerHTML = ""; // } return; } this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["FONT STYLE", {bMustBlockElement:true}]); if(bSelectedBlock){ var aNodes; this.oApp.exec("GET_SELECTED_TD_BLOCK",['aTdCells',htSelectedTDs]); aNodes = htSelectedTDs.aTdCells; for( var j = 0; j < aNodes.length ; j++){ oSelection.selectNodeContents(aNodes[j]); oSelection.styleRange(oStyles); oSelection.select(); } } else { var bCheckTextDecoration = !!oStyles.color; // [SMARTEDITORSUS-26] 취소선/밑줄 색상 적용 처리 var bIncludeLI = oStyles.fontSize || oStyles.fontFamily; oSelection.styleRange(oStyles, null, null, bIncludeLI, bCheckTextDecoration); // http://bts.nhncorp.com/nhnbts/browse/COM-964 // // In FF when, // 1) Some text was wrapped with a styling SPAN and a bogus BR is followed // eg: <span style="XXX">TEST</span><br> // 2) And some place outside the span is clicked. // // The text cursor will be located outside the SPAN like the following, // <span style="XXX">TEST</span>[CURSOR]<br> // // which is not what the user would expect // Desired result: <span style="XXX">TEST[CURSOR]</span><br> // // To make the cursor go inside the styling SPAN, remove the bogus BR when the styling SPAN is created. // -> Style TEST<br> as <span style="XXX">TEST</span> (remove unnecessary BR) // -> Cannot monitor clicks/cursor position real-time so make the contents error-proof instead. if(jindo.$Agent().navigator().firefox){ var aStyleParents = oSelection.aStyleParents; for(var i=0, nLen=aStyleParents.length; i<nLen; i++){ var elNode = aStyleParents[i]; if(elNode.nextSibling && elNode.nextSibling.tagName == "BR" && !elNode.nextSibling.nextSibling){ elNode.parentNode.removeChild(elNode.nextSibling); } } } oSelection._window.focus(); oSelection.select(); } this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["FONT STYLE", {bMustBlockElement:true}]); } }); //} //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to Find/Replace * @name hp_SE2M_FindReplacePlugin.js */ nhn.husky.SE2M_FindReplacePlugin = jindo.$Class({ name : "SE2M_FindReplacePlugin", oEditingWindow : null, oFindReplace : null, bFindMode : true, bLayerShown : false, $init : function(){ this.nDefaultTop = 20; }, $ON_MSG_APP_READY : function(){ // the right document will be available only when the src is completely loaded this.oEditingWindow = this.oApp.getWYSIWYGWindow(); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+f", "SHOW_FIND_LAYER", []]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+h", "SHOW_REPLACE_LAYER", []]); this.oApp.exec("REGISTER_UI_EVENT", ["findAndReplace", "click", "TOGGLE_FIND_REPLACE_LAYER"]); }, $ON_SHOW_ACTIVE_LAYER : function(){ this.oApp.exec("HIDE_DIALOG_LAYER", [this.elDropdownLayer]); }, //@lazyload_js TOGGLE_FIND_REPLACE_LAYER,SHOW_FIND_LAYER,SHOW_REPLACE_LAYER,SHOW_FIND_REPLACE_LAYER:N_FindReplace.js[ _assignHTMLElements : function(){ var oAppContainer = this.oApp.htOptions.elAppContainer; this.oApp.exec("LOAD_HTML", ["find_and_replace"]); // this.oEditingWindow = jindo.$$.getSingle("IFRAME", oAppContainer); this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_findAndReplace_layer", oAppContainer); this.welDropdownLayer = jindo.$Element(this.elDropdownLayer); var oTmp = jindo.$$("LI", this.elDropdownLayer); this.oFindTab = oTmp[0]; this.oReplaceTab = oTmp[1]; oTmp = jindo.$$(".container > .bx", this.elDropdownLayer); this.oFindInputSet = jindo.$$.getSingle(".husky_se2m_find_ui", this.elDropdownLayer); this.oReplaceInputSet = jindo.$$.getSingle(".husky_se2m_replace_ui", this.elDropdownLayer); this.elTitle = jindo.$$.getSingle("H3", this.elDropdownLayer); this.oFindInput_Keyword = jindo.$$.getSingle("INPUT", this.oFindInputSet); oTmp = jindo.$$("INPUT", this.oReplaceInputSet); this.oReplaceInput_Original = oTmp[0]; this.oReplaceInput_Replacement = oTmp[1]; this.oFindNextButton = jindo.$$.getSingle("BUTTON.husky_se2m_find_next", this.elDropdownLayer); this.oReplaceFindNextButton = jindo.$$.getSingle("BUTTON.husky_se2m_replace_find_next", this.elDropdownLayer); this.oReplaceButton = jindo.$$.getSingle("BUTTON.husky_se2m_replace", this.elDropdownLayer); this.oReplaceAllButton = jindo.$$.getSingle("BUTTON.husky_se2m_replace_all", this.elDropdownLayer); this.aCloseButtons = jindo.$$("BUTTON.husky_se2m_cancel", this.elDropdownLayer); }, $LOCAL_BEFORE_FIRST : function(sMsg){ this._assignHTMLElements(); this.oFindReplace = new nhn.FindReplace(this.oEditingWindow); for(var i=0; i<this.aCloseButtons.length; i++){ // var func = jindo.$Fn(this.oApp.exec, this.oApp).bind("HIDE_DIALOG_LAYER", [this.elDropdownLayer]); var func = jindo.$Fn(this.oApp.exec, this.oApp).bind("HIDE_FIND_REPLACE_LAYER", [this.elDropdownLayer]); jindo.$Fn(func, this).attach(this.aCloseButtons[i], "click"); } jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("SHOW_FIND", []), this).attach(this.oFindTab, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("SHOW_REPLACE", []), this).attach(this.oReplaceTab, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("FIND", []), this).attach(this.oFindNextButton, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("FIND", []), this).attach(this.oReplaceFindNextButton, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("REPLACE", []), this).attach(this.oReplaceButton, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("REPLACE_ALL", []), this).attach(this.oReplaceAllButton, "click"); this.oFindInput_Keyword.value = ""; this.oReplaceInput_Original.value = ""; this.oReplaceInput_Replacement.value = ""; //레이어의 이동 범위 설정. var elIframe = this.oApp.getWYSIWYGWindow().frameElement; this.htOffsetPos = jindo.$Element(elIframe).offset(); this.nEditorWidth = elIframe.offsetWidth; this.elDropdownLayer.style.display = "block"; this.htInitialPos = this.welDropdownLayer.offset(); var htScrollXY = this.oApp.oUtils.getScrollXY(); // this.welDropdownLayer.offset(this.htOffsetPos.top-htScrollXY.y, this.htOffsetPos.left-htScrollXY.x); this.welDropdownLayer.offset(this.htOffsetPos.top, this.htOffsetPos.left); this.htTopLeftCorner = {x:parseInt(this.elDropdownLayer.style.left, 10), y:parseInt(this.elDropdownLayer.style.top, 10)}; // offset width가 IE에서 css lazy loading 때문에 제대로 잡히지 않아 상수로 설정 //this.nLayerWidth = this.elDropdownLayer.offsetWidth; this.nLayerWidth = 258; this.nLayerHeight = 160; //this.nLayerWidth = Math.abs(parseInt(this.elDropdownLayer.style.marginLeft))+20; this.elDropdownLayer.style.display = "none"; }, // [SMARTEDITORSUS-728] 찾기/바꾸기 레이어 오픈 툴바 버튼 active/inactive 처리 추가 $ON_TOGGLE_FIND_REPLACE_LAYER : function(){ if(!this.bLayerShown) { this.oApp.exec("SHOW_FIND_REPLACE_LAYER"); } else { this.oApp.exec("HIDE_FIND_REPLACE_LAYER"); } }, $ON_SHOW_FIND_REPLACE_LAYER : function(){ this.bLayerShown = true; this.oApp.exec("DISABLE_ALL_UI", [{aExceptions: ["findAndReplace"]}]); this.oApp.exec("SELECT_UI", ["findAndReplace"]); this.oApp.exec("HIDE_ALL_DIALOG_LAYER", []); this.elDropdownLayer.style.top = this.nDefaultTop+"px"; this.oApp.exec("SHOW_DIALOG_LAYER", [this.elDropdownLayer, { elHandle: this.elTitle, fnOnDragStart : jindo.$Fn(this.oApp.exec, this.oApp).bind("SHOW_EDITING_AREA_COVER"), fnOnDragEnd : jindo.$Fn(this.oApp.exec, this.oApp).bind("HIDE_EDITING_AREA_COVER"), nMinX : this.htTopLeftCorner.x, nMinY : this.nDefaultTop, nMaxX : this.htTopLeftCorner.x + this.oApp.getEditingAreaWidth() - this.nLayerWidth, nMaxY : this.htTopLeftCorner.y + this.oApp.getEditingAreaHeight() - this.nLayerHeight, sOnShowMsg : "FIND_REPLACE_LAYER_SHOWN" }]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['findreplace']); }, $ON_HIDE_FIND_REPLACE_LAYER : function() { this.oApp.exec("ENABLE_ALL_UI"); this.oApp.exec("DESELECT_UI", ["findAndReplace"]); this.oApp.exec("HIDE_ALL_DIALOG_LAYER", []); this.bLayerShown = false; }, $ON_FIND_REPLACE_LAYER_SHOWN : function(){ this.oApp.exec("POSITION_TOOLBAR_LAYER", [this.elDropdownLayer]); if(this.bFindMode){ this.oFindInput_Keyword.value = "_clear_"; this.oFindInput_Keyword.value = ""; this.oFindInput_Keyword.focus(); }else{ this.oReplaceInput_Original.value = "_clear_"; this.oReplaceInput_Original.value = ""; this.oReplaceInput_Replacement.value = ""; this.oReplaceInput_Original.focus(); } this.oApp.exec("HIDE_CURRENT_ACTIVE_LAYER", []); }, $ON_SHOW_FIND_LAYER : function(){ this.oApp.exec("SHOW_FIND"); this.oApp.exec("SHOW_FIND_REPLACE_LAYER"); }, $ON_SHOW_REPLACE_LAYER : function(){ this.oApp.exec("SHOW_REPLACE"); this.oApp.exec("SHOW_FIND_REPLACE_LAYER"); }, $ON_SHOW_FIND : function(){ this.bFindMode = true; this.oFindInput_Keyword.value = this.oReplaceInput_Original.value; jindo.$Element(this.oFindTab).addClass("active"); jindo.$Element(this.oReplaceTab).removeClass("active"); jindo.$Element(this.oFindNextButton).removeClass("normal"); jindo.$Element(this.oFindNextButton).addClass("strong"); this.oFindInputSet.style.display = "block"; this.oReplaceInputSet.style.display = "none"; this.oReplaceButton.style.display = "none"; this.oReplaceAllButton.style.display = "none"; jindo.$Element(this.elDropdownLayer).removeClass("replace"); jindo.$Element(this.elDropdownLayer).addClass("find"); }, $ON_SHOW_REPLACE : function(){ this.bFindMode = false; this.oReplaceInput_Original.value = this.oFindInput_Keyword.value; jindo.$Element(this.oFindTab).removeClass("active"); jindo.$Element(this.oReplaceTab).addClass("active"); jindo.$Element(this.oFindNextButton).removeClass("strong"); jindo.$Element(this.oFindNextButton).addClass("normal"); this.oFindInputSet.style.display = "none"; this.oReplaceInputSet.style.display = "block"; this.oReplaceButton.style.display = "inline"; this.oReplaceAllButton.style.display = "inline"; jindo.$Element(this.elDropdownLayer).removeClass("find"); jindo.$Element(this.elDropdownLayer).addClass("replace"); }, $ON_FIND : function(){ var sKeyword; if(this.bFindMode){ sKeyword = this.oFindInput_Keyword.value; }else{ sKeyword = this.oReplaceInput_Original.value; } var oSelection = this.oApp.getSelection(); oSelection.select(); switch(this.oFindReplace.find(sKeyword, false)){ case 1: alert(this.oApp.$MSG("SE_FindReplace.keywordNotFound")); oSelection.select(); break; case 2: alert(this.oApp.$MSG("SE_FindReplace.keywordMissing")); break; } }, $ON_REPLACE : function(){ var sOriginal = this.oReplaceInput_Original.value; var sReplacement = this.oReplaceInput_Replacement.value; var oSelection = this.oApp.getSelection(); this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["REPLACE"]); var iReplaceResult = this.oFindReplace.replace(sOriginal, sReplacement, false); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["REPLACE"]); switch(iReplaceResult){ case 1: case 3: alert(this.oApp.$MSG("SE_FindReplace.keywordNotFound")); oSelection.select(); break; case 4: alert(this.oApp.$MSG("SE_FindReplace.keywordMissing")); break; } }, $ON_REPLACE_ALL : function(){ var sOriginal = this.oReplaceInput_Original.value; var sReplacement = this.oReplaceInput_Replacement.value; var oSelection = this.oApp.getSelection(); this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["REPLACE ALL", {sSaveTarget:"BODY"}]); var iReplaceAllResult = this.oFindReplace.replaceAll(sOriginal, sReplacement, false); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["REPLACE ALL", {sSaveTarget:"BODY"}]); if(iReplaceAllResult === 0){ alert(this.oApp.$MSG("SE_FindReplace.replaceKeywordNotFound")); oSelection.select(); this.oApp.exec("FOCUS"); }else{ if(iReplaceAllResult<0){ alert(this.oApp.$MSG("SE_FindReplace.keywordMissing")); oSelection.select(); }else{ alert(this.oApp.$MSG("SE_FindReplace.replaceAllResultP1")+iReplaceAllResult+this.oApp.$MSG("SE_FindReplace.replaceAllResultP2")); oSelection = this.oApp.getEmptySelection(); oSelection.select(); this.oApp.exec("FOCUS"); } } } //@lazyload_js] }); //} /** * @fileOverview This file contains Husky plugin that takes care of the operations related to quote * @name hp_SE_Quote.js * @required SE_EditingArea_WYSIWYG */ nhn.husky.SE2M_Quote = jindo.$Class({ name : "SE2M_Quote", htQuoteStyles_view : null, $init : function(){ var htConfig = nhn.husky.SE2M_Configuration.Quote || {}; var sImageBaseURL = htConfig.sImageBaseURL; this.nMaxLevel = htConfig.nMaxLevel || 14; this.htQuoteStyles_view = {}; this.htQuoteStyles_view["se2_quote1"] = "_zoom:1;padding:0 8px; margin:0 0 30px 20px; margin-right:15px; border-left:2px solid #cccccc;color:#888888;"; this.htQuoteStyles_view["se2_quote2"] = "_zoom:1;margin:0 0 30px 13px;padding:0 8px 0 16px;background:url("+sImageBaseURL+"/bg_quote2.gif) 0 3px no-repeat;color:#888888;"; this.htQuoteStyles_view["se2_quote3"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px dashed #cccccc;color:#888888;"; this.htQuoteStyles_view["se2_quote4"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px dashed #66b246;color:#888888;"; this.htQuoteStyles_view["se2_quote5"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px dashed #cccccc;background:url("+sImageBaseURL+"/bg_b1.png) repeat;_background:none;_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sImageBaseURL+"/bg_b1.png',sizingMethod='scale');color:#888888;"; this.htQuoteStyles_view["se2_quote6"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px solid #e5e5e5;color:#888888;"; this.htQuoteStyles_view["se2_quote7"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px solid #66b246;color:#888888;"; this.htQuoteStyles_view["se2_quote8"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px solid #e5e5e5;background:url("+sImageBaseURL+"/bg_b1.png) repeat;_background:none;_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sImageBaseURL+"/bg_b1.png',sizingMethod='scale');color:#888888;"; this.htQuoteStyles_view["se2_quote9"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:2px solid #e5e5e5;color:#888888;"; this.htQuoteStyles_view["se2_quote10"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:2px solid #e5e5e5;background:url("+sImageBaseURL+"/bg_b1.png) repeat;_background:none;_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sImageBaseURL+"/bg_b1.png',sizingMethod='scale');color:#888888;"; }, _assignHTMLElements : function(){ //@ec this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_seditor_blockquote_layer", this.oApp.htOptions.elAppContainer); this.aLI = jindo.$$("LI", this.elDropdownLayer); }, $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER", ["DB_TO_IR", jindo.$Fn(function(sContents){ sContents = sContents.replace(/<(blockquote)[^>]*class=['"]?(se2_quote[0-9]+)['"]?[^>]*>/gi, "<$1 class=$2>"); return sContents; }, this).bind()]); this.oApp.exec("ADD_CONVERTER", ["IR_TO_DB", jindo.$Fn(function(sContents){ var htQuoteStyles_view = this.htQuoteStyles_view; sContents = sContents.replace(/<(blockquote)[^>]*class=['"]?(se2_quote[0-9]+)['"]?[^>]*>/gi, function(sAll, sTag, sClassName){ return '<'+sTag+' class='+sClassName+' style="'+htQuoteStyles_view[sClassName]+'">'; }); return sContents; }, this).bind()]); this.htSE1toSE2Map = { "01" : "1", "02" : "2", "03" : "6", "04" : "8", "05" : "9", "07" : "3", "08" : "5" }; // convert SE1's quotes to SE2's // -> 블로그 개발 쪽에서 처리 하기로 함. /* this.oApp.exec("ADD_CONVERTER", ["DB_TO_IR", jindo.$Fn(function(sContents){ return sContents.replace(/<blockquote[^>]* class="?vview_quote([0-9]+)"?[^>]*>((?:\s|.)*?)<\/blockquote>/ig, jindo.$Fn(function(m0,sQuoteType,sQuoteContents){ if (/<!--quote_txt-->((?:\s|.)*?)<!--\/quote_txt-->/ig.test(sQuoteContents)){ if(!this.htSE1toSE2Map[sQuoteType]){ return m0; } return '<blockquote class="se2_quote'+this.htSE1toSE2Map[sQuoteType]+'">'+RegExp.$1+'</blockquote>'; }else{ return ''; } }, this).bind()); }, this).bind()]); */ }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLElements(); this.oApp.registerBrowserEvent(this.elDropdownLayer, "click", "EVENT_SE2_BLOCKQUOTE_LAYER_CLICK", []); this.oApp.delayedExec("SE2_ATTACH_HOVER_EVENTS", [this.aLI], 0); }, $ON_MSG_APP_READY: function(){ this.oApp.exec("REGISTER_UI_EVENT", ["quote", "click", "TOGGLE_BLOCKQUOTE_LAYER"]); }, //@lazyload_js TOGGLE_BLOCKQUOTE_LAYER[ $ON_TOGGLE_BLOCKQUOTE_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "SELECT_UI", ["quote"], "DESELECT_UI", ["quote"]]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['quote']); }, $ON_EVENT_SE2_BLOCKQUOTE_LAYER_CLICK : function(weEvent){ var elButton = nhn.husky.SE2M_Utils.findAncestorByTagName("BUTTON", weEvent.element); if(!elButton || elButton.tagName != "BUTTON"){return;} var sClass = elButton.className; this.oApp.exec("APPLY_BLOCKQUOTE", [sClass]); }, $ON_APPLY_BLOCKQUOTE : function(sClass){ if(sClass.match(/(se2_quote[0-9]+)/)){ this._wrapBlock("BLOCKQUOTE", RegExp.$1); }else{ this._unwrapBlock("BLOCKQUOTE"); } this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, /** * 인용구의 중첩 가능한 최대 개수를 넘었는지 확인함 * 인용구 내부에서 인용구를 적용하면 중첩되지 않으므로 자식노드에 대해서만 확인함 */ _isExceedMaxDepth : function(elNode){ var countChildQuote = function(elNode){ var elChild = elNode.firstChild; var nCount = 0; var nMaxCount = 0; if(!elChild){ if(elNode.tagName && elNode.tagName === "BLOCKQUOTE"){ return 1; }else{ return 0; } } while(elChild){ if(elChild.nodeType === 1){ nCount = countChildQuote(elChild); if(elChild.tagName === "BLOCKQUOTE"){ nCount += 1; } if(nMaxCount < nCount){ nMaxCount = nCount; } if(nMaxCount >= this.nMaxLevel){ return nMaxCount; } } elChild = elChild.nextSibling; } return nMaxCount; }; return (countChildQuote(elNode) >= this.nMaxLevel); }, _unwrapBlock : function(tag){ var oSelection = this.oApp.getSelection(); var elCommonAncestor = oSelection.commonAncestorContainer; while(elCommonAncestor && elCommonAncestor.tagName != tag){elCommonAncestor = elCommonAncestor.parentNode;} if(!elCommonAncestor){return;} this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["CANCEL BLOCK QUOTE", {sSaveTarget:"BODY"}]); while(elCommonAncestor.firstChild){elCommonAncestor.parentNode.insertBefore(elCommonAncestor.firstChild, elCommonAncestor);} elCommonAncestor.parentNode.removeChild(elCommonAncestor); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["CANCEL BLOCK QUOTE", {sSaveTarget:"BODY"}]); }, _wrapBlock : function(tag, className){ var oSelection, oLineInfo, oStart, oEnd, rxDontUseAsWhole = /BODY|TD|LI/i, oStartNode, oEndNode, oNode, elCommonAncestor, elCommonNode, elParentQuote, elInsertBefore, oFormattingNode, elNextNode, elParentNode, aQuoteChild, aQuoteCloneChild, i, nLen, oP, sBookmarkID; this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["BLOCK QUOTE", {sSaveTarget:"BODY"}]); oSelection = this.oApp.getSelection(); // var sBookmarkID = oSelection.placeStringBookmark(); // [SMARTEDITORSUS-430] 문자를 입력하고 Enter 후 인용구를 적용할 때 위의 문자들이 인용구 안에 들어가는 문제 // [SMARTEDITORSUS-1323] 사진 첨부 후 인용구 적용 시 첨부한 사진이 삭제되는 현상 // [SMARTEDITORSUS-1567] 엔터키를 한 번도 누르지 않고 인용구를 삽입하는 경우에 대응 /*if(oSelection.startContainer === oSelection.endContainer && oSelection.startContainer.nodeType === 1 && oSelection.startContainer.tagName === "P"){ if(nhn.husky.SE2M_Utils.isBlankNode(oSelection.startContainer) || nhn.husky.SE2M_Utils.isFirstChildOfNode("IMG", oSelection.startContainer.tagName, oSelection.startContainer) || nhn.husky.SE2M_Utils.isFirstChildOfNode("IFRAME", oSelection.startContainer.tagName, oSelection.startContainer)){ oLineInfo = oSelection.getLineInfo(true); }else{ oLineInfo = oSelection.getLineInfo(false); } }else{ oLineInfo = oSelection.getLineInfo(false); }*/ if(oSelection.startContainer === oSelection.endContainer){ if(oSelection.startContainer.nodeType === 1 && oSelection.startContainer.tagName === "P"){ if(nhn.husky.SE2M_Utils.isBlankNode(oSelection.startContainer) || nhn.husky.SE2M_Utils.isFirstChildOfNode("IMG", oSelection.startContainer.tagName, oSelection.startContainer) || nhn.husky.SE2M_Utils.isFirstChildOfNode("IFRAME", oSelection.startContainer.tagName, oSelection.startContainer)){ oLineInfo = oSelection.getLineInfo(true); }else{ oLineInfo = oSelection.getLineInfo(false); } }else{ // 시작 컨테이너와 끝 컨테이너는 같되 P 태그가 아닌 경우로, // 엔터를 한 번도 입력하지 않은 상황이다. // TD 태그나 BODY 태그 내부에 속해 있을 것이라고 가정하고 진행하는데, // 올바른 정렬 적용을 위해 현재 위치에 속한 컨텐츠를 P 태그로 감싸 주게 된다. var _startContainer = oSelection.startContainer; var _startOffset = oSelection.startOffset; var _endContainer = oSelection.endContainer; var _endOffset = oSelection.endOffset; var _sBM = oSelection.placeStringBookmark(); var _elBookmark = oSelection.getStringBookmark(_sBM); var _elParent = _elBookmark.parentNode; var _elAncestor = nhn.husky.SE2M_Utils.findAncestorByTagName("P", _elParent); // 원래 P 태그를 포함할 수 있는 부모 목록 var _aParagraphContainer = ["TD", "BODY"]; // 탐색 순서는 TD, BODY 순 if(!_elAncestor){ for(var i = 0, len = _aParagraphContainer.length; i < len; i++){ _elAncestor = nhn.husky.SE2M_Utils.findAncestorByTagName(_aParagraphContainer[i], _elParent); if(_elAncestor){ break; } } var _elParagraph = document.createElement("P"); var _aAncestorChildren = _elAncestor.childNodes; for(var i = 0, len = _aAncestorChildren.length; i < len; i++){ _elParagraph.appendChild(_aAncestorChildren[0]); } _elAncestor.appendChild(_elParagraph); } oSelection.removeStringBookmark(_sBM); oSelection = this.oApp.getSelection(); oSelection.setStart(_startContainer, _startOffset); oSelection.setEnd(_endContainer, _endOffset); oLineInfo = oSelection.getLineInfo(true); } }else{ oLineInfo = oSelection.getLineInfo(false); } // --[SMARTEDITORSUS-1567] oStart = oLineInfo.oStart; oEnd = oLineInfo.oEnd; if(oStart.bParentBreak && !rxDontUseAsWhole.test(oStart.oLineBreaker.tagName)){ oStartNode = oStart.oNode.parentNode; }else{ oStartNode = oStart.oNode; } if(oEnd.bParentBreak && !rxDontUseAsWhole.test(oEnd.oLineBreaker.tagName)){ oEndNode = oEnd.oNode.parentNode; }else{ oEndNode = oEnd.oNode; } oSelection.setStartBefore(oStartNode); oSelection.setEndAfter(oEndNode); oNode = this._expandToTableStart(oSelection, oEndNode); if(oNode){ oEndNode = oNode; oSelection.setEndAfter(oNode); } oNode = this._expandToTableStart(oSelection, oStartNode); if(oNode){ oStartNode = oNode; oSelection.setStartBefore(oNode); } oNode = oStartNode; // IE에서는 commonAncestorContainer 자체는 select 가능하지 않고, 하위에 commonAncestorContainer를 대체 하더라도 똑같은 영역이 셀렉트 되어 보이는 // 노드가 있을 경우 하위 노드가 commonAncestorContainer로 반환됨. // 그래서, 스크립트로 commonAncestorContainer 계산 하도록 함. // 예) // <P><SPAN>TEST</SPAN></p>를 선택 할 경우, <SPAN>TEST</SPAN>가 commonAncestorContainer로 잡힘 oSelection.fixCommonAncestorContainer(); elCommonAncestor = oSelection.commonAncestorContainer; if(oSelection.startContainer == oSelection.endContainer && oSelection.endOffset-oSelection.startOffset == 1){ elCommonNode = oSelection.startContainer.childNodes[oSelection.startOffset]; }else{ elCommonNode = oSelection.commonAncestorContainer; } elParentQuote = this._findParentQuote(elCommonNode); if(elParentQuote){ elParentQuote.className = className; return; } while(!elCommonAncestor.tagName || (elCommonAncestor.tagName && elCommonAncestor.tagName.match(/UL|OL|LI|IMG|IFRAME/))){ elCommonAncestor = elCommonAncestor.parentNode; } // find the insertion position for the formatting tag right beneath the common ancestor container while(oNode && oNode != elCommonAncestor && oNode.parentNode != elCommonAncestor){oNode = oNode.parentNode;} if(oNode == elCommonAncestor){ elInsertBefore = elCommonAncestor.firstChild; }else{ elInsertBefore = oNode; } oFormattingNode = oSelection._document.createElement(tag); if(className){ oFormattingNode.className = className; // SMARTEDITORSUS-1239 blockquate style 적용 this._setStyle(oFormattingNode, this.htQuoteStyles_view[className]); } elCommonAncestor.insertBefore(oFormattingNode, elInsertBefore); oSelection.setStartAfter(oFormattingNode); oSelection.setEndAfter(oEndNode); oSelection.surroundContents(oFormattingNode); if(this._isExceedMaxDepth(oFormattingNode)){ alert(this.oApp.$MSG("SE2M_Quote.exceedMaxCount").replace("#MaxCount#", (this.nMaxLevel + 1))); this.oApp.exec("HIDE_ACTIVE_LAYER", []); elNextNode = oFormattingNode.nextSibling; elParentNode = oFormattingNode.parentNode; aQuoteChild = oFormattingNode.childNodes; aQuoteCloneChild = []; jindo.$Element(oFormattingNode).leave(); for(i = 0, nLen = aQuoteChild.length; i < nLen; i++){ aQuoteCloneChild[i] = aQuoteChild[i]; } for(i = 0, nLen = aQuoteCloneChild.length; i < nLen; i++){ if(!!elNextNode){ jindo.$Element(elNextNode).before(aQuoteCloneChild[i]); }else{ jindo.$Element(elParentNode).append(aQuoteCloneChild[i]); } } return; } oSelection.selectNodeContents(oFormattingNode); // insert an empty line below, so the text cursor can move there if(oFormattingNode && oFormattingNode.parentNode && oFormattingNode.parentNode.tagName == "BODY" && !oFormattingNode.nextSibling){ oP = oSelection._document.createElement("P"); //oP.innerHTML = unescape("<br/>"); oP.innerHTML = "&nbsp;"; oFormattingNode.parentNode.insertBefore(oP, oFormattingNode.nextSibling); } // oSelection.removeStringBookmark(sBookmarkID); // Insert an empty line inside the blockquote if it's empty. // This is done to position the cursor correctly when the contents of the blockquote is empty in Chrome. if(nhn.husky.SE2M_Utils.isBlankNode(oFormattingNode)){ // oFormattingNode.innerHTML = ""; // oP = oSelection._document.createElement("P"); // oP.innerHTML = "&nbsp;"; // oFormattingNode.insertBefore(oP, null); // oSelection = this.oApp.getEmptySelection(); // oSelection.selectNode(oP); // [SMARTEDITORSUS-645] 편집영역 포커스 없이 인용구 추가했을 때 IE7에서 박스가 늘어나는 문제 // [SMARTEDITORSUS-1567] [Chrome] 인용구 삽입 직전 내용이 아무것도 없는 경우에 대응 //oFormattingNode.innerHTML = "&nbsp;"; var htBrowser = jindo.$Agent().navigator(); if(htBrowser.chrome){ // P 태그로 감싸주지 않으면 blockquote 태그에 정렬이 적용되는데, DB로 넘어갈 때 스타일이 적용되지 않는 문제 발견 oFormattingNode.innerHTML = "<p>&nbsp;</p>"; }else{ oFormattingNode.innerHTML = "&nbsp;"; } // --[SMARTEDITORSUS-1567] oSelection.selectNodeContents(oFormattingNode); oSelection.collapseToStart(); oSelection.select(); } //oSelection.select(); this.oApp.exec("REFRESH_WYSIWYG"); setTimeout(jindo.$Fn(function(oSelection){ sBookmarkID = oSelection.placeStringBookmark(); oSelection.select(); oSelection.removeStringBookmark(sBookmarkID); this.oApp.exec("FOCUS"); // [SMARTEDITORSUS-469] [SMARTEDITORSUS-434] 에디터 로드 후 최초 삽입한 인용구 안에 포커스가 가지 않는 문제 },this).bind(oSelection), 0); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["BLOCK QUOTE", {sSaveTarget:"BODY"}]); return oFormattingNode; }, _expandToTableStart : function(oSelection, oNode){ var elCommonAncestor = oSelection.commonAncestorContainer; var oResultNode = null; var bLastIteration = false; while(oNode && !bLastIteration){ if(oNode == elCommonAncestor){bLastIteration = true;} if(/TBODY|TFOOT|THEAD|TR/i.test(oNode.tagName)){ oResultNode = this._getTableRoot(oNode); break; } oNode = oNode.parentNode; } return oResultNode; }, _getTableRoot : function(oNode){ while(oNode && oNode.tagName != "TABLE"){oNode = oNode.parentNode;} return oNode; }, _setStyle : function(el, sStyle) { el.setAttribute("style", sStyle); el.style.cssText = sStyle; }, //@lazyload_js] // [SMARTEDITORSUS-209] 인용구 내에 내용이 없을 때 Backspace 로 인용구가 삭제되도록 처리 $ON_EVENT_EDITING_AREA_KEYDOWN : function(weEvent) { var oSelection, elParentQuote; if ('WYSIWYG' !== this.oApp.getEditingMode()){ return; } if(8 !== weEvent.key().keyCode){ return; } oSelection = this.oApp.getSelection(); oSelection.fixCommonAncestorContainer(); elParentQuote = this._findParentQuote(oSelection.commonAncestorContainer); if(!elParentQuote){ return; } if(this._isBlankQuote(elParentQuote)){ weEvent.stop(jindo.$Event.CANCEL_DEFAULT); oSelection.selectNode(elParentQuote); oSelection.collapseToStart(); jindo.$Element(elParentQuote).leave(); oSelection.select(); } }, // [SMARTEDITORSUS-215] Delete 로 인용구 뒤의 P 가 제거되지 않도록 처리 $ON_EVENT_EDITING_AREA_KEYUP : function(weEvent) { var oSelection, elParentQuote, oP; if ('WYSIWYG' !== this.oApp.getEditingMode()){ return; } if(46 !== weEvent.key().keyCode){ return; } oSelection = this.oApp.getSelection(); oSelection.fixCommonAncestorContainer(); elParentQuote = this._findParentQuote(oSelection.commonAncestorContainer); if(!elParentQuote){ return false; } if(!elParentQuote.nextSibling){ weEvent.stop(jindo.$Event.CANCEL_DEFAULT); oP = oSelection._document.createElement("P"); oP.innerHTML = "&nbsp;"; jindo.$Element(elParentQuote).after(oP); setTimeout(jindo.$Fn(function(oSelection){ var sBookmarkID = oSelection.placeStringBookmark(); oSelection.select(); oSelection.removeStringBookmark(sBookmarkID); },this).bind(oSelection), 0); } }, _isBlankQuote : function(elParentQuote){ var elChild, aChildNodes, i, nLen, bChrome = this.oApp.oNavigator.chrome, bSafari = this.oApp.oNavigator.safari, isBlankText = function(sText){ sText = sText.replace(/[\r\n]/ig, '').replace(unescape("%uFEFF"), ''); if(sText === ""){ return true; } if(sText === "&nbsp;" || sText === " "){ // [SMARTEDITORSUS-479] return true; } return false; }, isBlank = function(oNode){ if(oNode.nodeType === 3 && isBlankText(oNode.nodeValue)){ return true; } if((oNode.tagName === "P" || oNode.tagName === "SPAN") && (isBlankText(oNode.innerHTML) || oNode.innerHTML === "<br>")){ return true; } return false; }, isBlankTable = function(oNode){ if((jindo.$$("tr", oNode)).length === 0){ return true; } return false; }; if(isBlankText(elParentQuote.innerHTML) || elParentQuote.innerHTML === "<br>"){ return true; } if(bChrome || bSafari){ // [SMARTEDITORSUS-352], [SMARTEDITORSUS-502] var aTable = jindo.$$("TABLE", elParentQuote), nTable = aTable.length, elTable; for(i=0; i<nTable; i++){ elTable = aTable[i]; if(isBlankTable(elTable)){ jindo.$Element(elTable).leave(); } } } aChildNodes = elParentQuote.childNodes; for(i=0, nLen=aChildNodes.length; i<nLen; i++){ elChild = aChildNodes[i]; if(!isBlank(elChild)){ return false; } } return true; }, _findParentQuote : function(el){ return this._findAncestor(jindo.$Fn(function(elNode){ if(!elNode){return false;} if(elNode.tagName !== "BLOCKQUOTE"){return false;} if(!elNode.className){return false;} var sClassName = elNode.className; if(!this.htQuoteStyles_view[sClassName]){return false;} return true; }, this).bind(), el); }, _findAncestor : function(fnCondition, elNode){ while(elNode && !fnCondition(elNode)){elNode = elNode.parentNode;} return elNode; } }); //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to inserting special characters * @name hp_SE2M_SCharacter.js * @required HuskyRangeManager */ nhn.husky.SE2M_SCharacter = jindo.$Class({ name : "SE2M_SCharacter", $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["sCharacter", "click", "TOGGLE_SCHARACTER_LAYER"]); }, //@lazyload_js TOGGLE_SCHARACTER_LAYER[ _assignHTMLObjects : function(oAppContainer){ oAppContainer = jindo.$(oAppContainer) || document; this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_seditor_sCharacter_layer", oAppContainer); this.oTextField = jindo.$$.getSingle("INPUT", this.elDropdownLayer); this.oInsertButton = jindo.$$.getSingle("BUTTON.se2_confirm", this.elDropdownLayer); this.aCloseButton = jindo.$$("BUTTON.husky_se2m_sCharacter_close", this.elDropdownLayer); this.aSCharList = jindo.$$("UL.husky_se2m_sCharacter_list", this.elDropdownLayer); var oLabelUL = jindo.$$.getSingle("UL.se2_char_tab", this.elDropdownLayer); this.aLabel = jindo.$$(">LI", oLabelUL); }, $LOCAL_BEFORE_FIRST : function(sFullMsg){ this.bIE = jindo.$Agent().navigator().ie; this._assignHTMLObjects(this.oApp.htOptions.elAppContainer); this.charSet = []; this.charSet[0] = unescape('FF5B FF5D 3014 3015 3008 3009 300A 300B 300C 300D 300E 300F 3010 3011 2018 2019 201C 201D 3001 3002 %B7 2025 2026 %A7 203B 2606 2605 25CB 25CF 25CE 25C7 25C6 25A1 25A0 25B3 25B2 25BD 25BC 25C1 25C0 25B7 25B6 2664 2660 2661 2665 2667 2663 2299 25C8 25A3 25D0 25D1 2592 25A4 25A5 25A8 25A7 25A6 25A9 %B1 %D7 %F7 2260 2264 2265 221E 2234 %B0 2032 2033 2220 22A5 2312 2202 2261 2252 226A 226B 221A 223D 221D 2235 222B 222C 2208 220B 2286 2287 2282 2283 222A 2229 2227 2228 FFE2 21D2 21D4 2200 2203 %B4 FF5E 02C7 02D8 02DD 02DA 02D9 %B8 02DB %A1 %BF 02D0 222E 2211 220F 266D 2669 266A 266C 327F 2192 2190 2191 2193 2194 2195 2197 2199 2196 2198 321C 2116 33C7 2122 33C2 33D8 2121 2668 260F 260E 261C 261E %B6 2020 2021 %AE %AA %BA 2642 2640').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[1] = unescape('%BD 2153 2154 %BC %BE 215B 215C 215D 215E %B9 %B2 %B3 2074 207F 2081 2082 2083 2084 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 FFE6 %24 FFE5 FFE1 20AC 2103 212B 2109 FFE0 %A4 2030 3395 3396 3397 2113 3398 33C4 33A3 33A4 33A5 33A6 3399 339A 339B 339C 339D 339E 339F 33A0 33A1 33A2 33CA 338D 338E 338F 33CF 3388 3389 33C8 33A7 33A8 33B0 33B1 33B2 33B3 33B4 33B5 33B6 33B7 33B8 33B9 3380 3381 3382 3383 3384 33BA 33BB 33BC 33BD 33BE 33BF 3390 3391 3392 3393 3394 2126 33C0 33C1 338A 338B 338C 33D6 33C5 33AD 33AE 33AF 33DB 33A9 33AA 33AB 33AC 33DD 33D0 33D3 33C3 33C9 33DC 33C6').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[2] = unescape('3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 326A 326B 326C 326D 326E 326F 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 327A 327B 24D0 24D1 24D2 24D3 24D4 24D5 24D6 24D7 24D8 24D9 24DA 24DB 24DC 24DD 24DE 24DF 24E0 24E1 24E2 24E3 24E4 24E5 24E6 24E7 24E8 24E9 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 246A 246B 246C 246D 246E 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 320A 320B 320C 320D 320E 320F 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 321A 321B 249C 249D 249E 249F 24A0 24A1 24A2 24A3 24A4 24A5 24A6 24A7 24A8 24A9 24AA 24AB 24AC 24AD 24AE 24AF 24B0 24B1 24B2 24B3 24B4 24B5 2474 2475 2476 2477 2478 2479 247A 247B 247C 247D 247E 247F 2480 2481 2482').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[3] = unescape('3131 3132 3133 3134 3135 3136 3137 3138 3139 313A 313B 313C 313D 313E 313F 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 314A 314B 314C 314D 314E 314F 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 315A 315B 315C 315D 315E 315F 3160 3161 3162 3163 3165 3166 3167 3168 3169 316A 316B 316C 316D 316E 316F 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 317A 317B 317C 317D 317E 317F 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 318A 318B 318C 318D 318E').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[4] = unescape('0391 0392 0393 0394 0395 0396 0397 0398 0399 039A 039B 039C 039D 039E 039F 03A0 03A1 03A3 03A4 03A5 03A6 03A7 03A8 03A9 03B1 03B2 03B3 03B4 03B5 03B6 03B7 03B8 03B9 03BA 03BB 03BC 03BD 03BE 03BF 03C0 03C1 03C3 03C4 03C5 03C6 03C7 03C8 03C9 %C6 %D0 0126 0132 013F 0141 %D8 0152 %DE 0166 014A %E6 0111 %F0 0127 I 0133 0138 0140 0142 0142 0153 %DF %FE 0167 014B 0149 0411 0413 0414 0401 0416 0417 0418 0419 041B 041F 0426 0427 0428 0429 042A 042B 042C 042D 042E 042F 0431 0432 0433 0434 0451 0436 0437 0438 0439 043B 043F 0444 0446 0447 0448 0449 044A 044B 044C 044D 044E 044F').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[5] = unescape('3041 3042 3043 3044 3045 3046 3047 3048 3049 304A 304B 304C 304D 304E 304F 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 305A 305B 305C 305D 305E 305F 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 306A 306B 306C 306D 306E 306F 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 307A 307B 307C 307D 307E 307F 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 308A 308B 308C 308D 308E 308F 3090 3091 3092 3093 30A1 30A2 30A3 30A4 30A5 30A6 30A7 30A8 30A9 30AA 30AB 30AC 30AD 30AE 30AF 30B0 30B1 30B2 30B3 30B4 30B5 30B6 30B7 30B8 30B9 30BA 30BB 30BC 30BD 30BE 30BF 30C0 30C1 30C2 30C3 30C4 30C5 30C6 30C7 30C8 30C9 30CA 30CB 30CC 30CD 30CE 30CF 30D0 30D1 30D2 30D3 30D4 30D5 30D6 30D7 30D8 30D9 30DA 30DB 30DC 30DD 30DE 30DF 30E0 30E1 30E2 30E3 30E4 30E5 30E6 30E7 30E8 30E9 30EA 30EB 30EC 30ED 30EE 30EF 30F0 30F1 30F2 30F3 30F4 30F5 30F6').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); var funcInsert = jindo.$Fn(this.oApp.exec, this.oApp).bind("INSERT_SCHARACTERS", [this.oTextField.value]); jindo.$Fn(funcInsert, this).attach(this.oInsertButton, "click"); this.oApp.exec("SET_SCHARACTER_LIST", [this.charSet]); for(var i=0; i<this.aLabel.length; i++){ var func = jindo.$Fn(this.oApp.exec, this.oApp).bind("CHANGE_SCHARACTER_SET", [i]); jindo.$Fn(func, this).attach(this.aLabel[i].firstChild, "mousedown"); } for(var i=0; i<this.aCloseButton.length; i++){ this.oApp.registerBrowserEvent(this.aCloseButton[i], "click", "HIDE_ACTIVE_LAYER", []); } this.oApp.registerBrowserEvent(this.elDropdownLayer, "click", "EVENT_SCHARACTER_CLICKED", []); }, $ON_TOGGLE_SCHARACTER_LAYER : function(){ this.oTextField.value = ""; this.oSelection = this.oApp.getSelection(); this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "MSG_SCHARACTER_LAYER_SHOWN", [], "MSG_SCHARACTER_LAYER_HIDDEN", [""]]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['symbol']); }, $ON_MSG_SCHARACTER_LAYER_SHOWN : function(){ this.oTextField.focus(); this.oApp.exec("SELECT_UI", ["sCharacter"]); }, $ON_MSG_SCHARACTER_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["sCharacter"]); }, $ON_EVENT_SCHARACTER_CLICKED : function(weEvent){ var elButton = nhn.husky.SE2M_Utils.findAncestorByTagName("BUTTON", weEvent.element); if(!elButton || elButton.tagName != "BUTTON"){return;} if(elButton.parentNode.tagName != "LI"){return;} var sChar = elButton.firstChild.innerHTML; if(sChar.length > 1){return;} this.oApp.exec("SELECT_SCHARACTER", [sChar]); weEvent.stop(); }, $ON_SELECT_SCHARACTER : function(schar){ this.oTextField.value += schar; if(this.oTextField.createTextRange){ var oTextRange = this.oTextField.createTextRange(); oTextRange.collapse(false); oTextRange.select(); }else{ if(this.oTextField.selectionEnd){ this.oTextField.selectionEnd = this.oTextField.value.length; this.oTextField.focus(); } } }, $ON_INSERT_SCHARACTERS : function(){ this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["INSERT SCHARACTER"]); this.oApp.exec("PASTE_HTML", [this.oTextField.value]); this.oApp.exec("FOCUS"); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["INSERT SCHARACTER"]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, $ON_CHANGE_SCHARACTER_SET : function(nSCharSet){ for(var i=0; i<this.aSCharList.length; i++){ if(jindo.$Element(this.aLabel[i]).hasClass("active")){ if(i == nSCharSet){return;} jindo.$Element(this.aLabel[i]).removeClass("active"); } } this._drawSCharList(nSCharSet); jindo.$Element(this.aLabel[nSCharSet]).addClass("active"); }, $ON_SET_SCHARACTER_LIST : function(charSet){ this.charSet = charSet; this.bSCharSetDrawn = new Array(this.charSet.length); this._drawSCharList(0); }, _drawSCharList : function(i){ if(this.bSCharSetDrawn[i]){return;} this.bSCharSetDrawn[i] = true; var len = this.charSet[i].length; var aLI = new Array(len); this.aSCharList[i].innerHTML = ''; var button, span; for(var ii=0; ii<len; ii++){ aLI[ii] = jindo.$("<LI>"); if(this.bIE){ button = jindo.$("<BUTTON>"); button.setAttribute('type', 'button'); }else{ button = jindo.$("<BUTTON>"); button.type = "button"; } span = jindo.$("<SPAN>"); span.innerHTML = unescape(this.charSet[i][ii]); button.appendChild(span); aLI[ii].appendChild(button); aLI[ii].onmouseover = function(){this.className='hover'}; aLI[ii].onmouseout = function(){this.className=''}; this.aSCharList[i].appendChild(aLI[ii]); } //this.oApp.delayedExec("SE2_ATTACH_HOVER_EVENTS", [jindo.$$(">LI", this.aSCharList[i]), 0]); } //@lazyload_js] }); //} /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font style in the table. * @requires SE2M_TableEditor.js * @name SE2M_TableBlockManager */ nhn.husky.SE2M_TableBlockStyler = jindo.$Class({ name : "SE2M_TableBlockStyler", nSelectedTD : 0, htSelectedTD : {}, aTdRange : [], $init : function(){ }, $LOCAL_BEFORE_ALL : function(){ return (this.oApp.getEditingMode() == "WYSIWYG"); }, $ON_MSG_APP_READY : function(){ this.oDocument = this.oApp.getWYSIWYGDocument(); }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(wevE){ if(this.oApp.getEditingMode() != "WYSIWYG") return; this.setTdBlock(); }, /** * selected Area가 td block인지 체크하는 함수. */ $ON_IS_SELECTED_TD_BLOCK : function(sAttr,oReturn) { if( this.nSelectedTD > 0){ oReturn[sAttr] = true; return oReturn[sAttr]; }else{ oReturn[sAttr] = false; return oReturn[sAttr]; } }, /** * */ $ON_GET_SELECTED_TD_BLOCK : function(sAttr,oReturn){ //use : this.oApp.exec("GET_SELECTED_TD_BLOCK",['aCells',this.htSelectedTD]); oReturn[sAttr] = this.htSelectedTD.aTdCells; }, setTdBlock : function() { this.oApp.exec("GET_SELECTED_CELLS",['aTdCells',this.htSelectedTD]); //tableEditor로 부터 얻어온다. var aNodes = this.htSelectedTD.aTdCells; if(aNodes){ this.nSelectedTD = aNodes.length; } }, $ON_DELETE_BLOCK_CONTENTS : function(){ var self = this, welParent, oBlockNode, oChildNode; this.setTdBlock(); for (var j = 0; j < this.nSelectedTD ; j++){ jindo.$Element(this.htSelectedTD.aTdCells[j]).child( function(elChild){ welParent = jindo.$Element(elChild._element.parentNode); welParent.remove(elChild); oBlockNode = self.oDocument.createElement('P'); if (jindo.$Agent().navigator().firefox) { oChildNode = self.oDocument.createElement('BR'); } else { oChildNode = self.oDocument.createTextNode('\u00A0'); } oBlockNode.appendChild(oChildNode); welParent.append(oBlockNode); }, 1); } } }); //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to table creation * @name hp_SE_Table.js */ nhn.husky.SE2M_TableCreator = jindo.$Class({ name : "SE2M_TableCreator", _sSETblClass : "__se_tbl", nRows : 3, nColumns : 4, nBorderSize : 1, sBorderColor : "#000000", sBGColor: "#000000", nBorderStyleIdx : 3, nTableStyleIdx : 1, nMinRows : 1, nMaxRows : 20, nMinColumns : 1, nMaxColumns : 20, nMinBorderWidth : 1, nMaxBorderWidth : 10, rxLastDigits : null, sReEditGuideMsg_table : null, // 테두리 스타일 목록 // 표 스타일 스타일 목록 oSelection : null, $ON_MSG_APP_READY : function(){ this.sReEditGuideMsg_table = this.oApp.$MSG(nhn.husky.SE2M_Configuration.SE2M_ReEditAction.aReEditGuideMsg[3]); this.oApp.exec("REGISTER_UI_EVENT", ["table", "click", "TOGGLE_TABLE_LAYER"]); }, // [SMARTEDITORSUS-365] 테이블퀵에디터 > 속성 직접입력 > 테두리 스타일 // - 테두리 없음을 선택하는 경우 본문에 삽입하는 표에 가이드 라인을 표시해 줍니다. 보기 시에는 테두리가 보이지 않습니다. $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER_DOM", ["IR_TO_DB", jindo.$Fn(this.irToDbDOM, this).bind()]); this.oApp.exec("ADD_CONVERTER_DOM", ["DB_TO_IR", jindo.$Fn(this.dbToIrDOM, this).bind()]); }, irToDbDOM : function(oTmpNode){ /** * 저장을 위한 Table Tag 는 아래와 같이 변경됩니다. * (1) <TABLE> * <table border="1" cellpadding="0" cellspacing="0" style="border:1px dashed #c7c7c7; border-left:0; border-bottom:0;" attr_no_border_tbl="1" class="__se_tbl"> * --> <table border="0" cellpadding="1" cellspacing="0" attr_no_border_tbl="1" class="__se_tbl"> * (2) <TD> * <td style="border:1px dashed #c7c7c7; border-top:0; border-right:0; background-color:#ffef00" width="245"><p>&nbsp;</p></td> * --> <td style="background-color:#ffef00" width="245">&nbsp;</td> */ var aNoBorderTable = []; var aTables = jindo.$$('table[class=__se_tbl]', oTmpNode, {oneTimeOffCache:true}); // 테두리가 없음 속성의 table (임의로 추가한 attr_no_border_tbl 속성이 있는 table 을 찾음) jindo.$A(aTables).forEach(function(oValue, nIdx, oArray) { if(jindo.$Element(oValue).attr("attr_no_border_tbl")){ aNoBorderTable.push(oValue); } }, this); if(aNoBorderTable.length < 1){ return; } // [SMARTEDITORSUS-410] 글 저장 시, 테두리 없음 속성을 선택할 때 임의로 표시한 가이드 라인 property 만 style 에서 제거해 준다. // <TABLE> 과 <TD> 의 속성값을 변경 및 제거 var aTDs = [], oTable; for(var i = 0, nCount = aNoBorderTable.length; i < nCount; i++){ oTable = aNoBorderTable[i]; // <TABLE> 에서 border, cellpadding 속성값 변경, style property 제거 jindo.$Element(oTable).css({"border": "", "borderLeft": "", "borderBottom": ""}); jindo.$Element(oTable).attr({"border": 0, "cellpadding": 1}); // <TD> 에서는 background-color 를 제외한 style 을 모두 제거 aTDs = jindo.$$('tbody>tr>td', oTable); jindo.$A(aTDs).forEach(function(oTD, nIdx, oTDArray) { jindo.$Element(oTD).css({"border": "", "borderTop": "", "borderRight": ""}); }); } }, dbToIrDOM : function(oTmpNode){ /** * 수정을 위한 Table Tag 는 아래와 같이 변경됩니다. * (1) <TABLE> * <table border="0" cellpadding="1" cellspacing="0" attr_no_border_tbl="1" class="__se_tbl"> * --> <table border="1" cellpadding="0" cellspacing="0" style="border:1px dashed #c7c7c7; border-left:0; border-bottom:0;" attr_no_border_tbl="1" class="__se_tbl"> * (2) <TD> * <td style="background-color:#ffef00" width="245">&nbsp;</td> * --> <td style="border:1px dashed #c7c7c7; border-top:0; border-right:0; background-color:#ffef00" width="245"><p>&nbsp;</p></td> */ var aNoBorderTable = []; var aTables = jindo.$$('table[class=__se_tbl]', oTmpNode, {oneTimeOffCache:true}); // 테두리가 없음 속성의 table (임의로 추가한 attr_no_border_tbl 속성이 있는 table 을 찾음) jindo.$A(aTables).forEach(function(oValue, nIdx, oArray) { if(jindo.$Element(oValue).attr("attr_no_border_tbl")){ aNoBorderTable.push(oValue); } }, this); if(aNoBorderTable.length < 1){ return; } // <TABLE> 과 <TD> 의 속성값을 변경/추가 var aTDs = [], oTable; for(var i = 0, nCount = aNoBorderTable.length; i < nCount; i++){ oTable = aNoBorderTable[i]; // <TABLE> 에서 border, cellpadding 속성값 변경/ style 속성 추가 jindo.$Element(oTable).css({"border": "1px dashed #c7c7c7", "borderLeft": 0, "borderBottom": 0}); jindo.$Element(oTable).attr({"border": 1, "cellpadding": 0}); // <TD> 에서 style 속성값 추가 aTDs = jindo.$$('tbody>tr>td', oTable); jindo.$A(aTDs).forEach(function(oTD, nIdx, oTDArray) { jindo.$Element(oTD).css({"border": "1px dashed #c7c7c7", "borderTop": 0, "borderRight": 0}); }); } }, //@lazyload_js TOGGLE_TABLE_LAYER[ _assignHTMLObjects : function(oAppContainer){ this.oApp.exec("LOAD_HTML", ["create_table"]); var tmp = null; this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_table_layer", oAppContainer); this.welDropdownLayer = jindo.$Element(this.elDropdownLayer); tmp = jindo.$$("INPUT", this.elDropdownLayer); this.elText_row = tmp[0]; this.elText_col = tmp[1]; this.elRadio_manualStyle = tmp[2]; this.elText_borderSize = tmp[3]; this.elText_borderColor = tmp[4]; this.elText_BGColor = tmp[5]; this.elRadio_templateStyle = tmp[6]; tmp = jindo.$$("BUTTON", this.elDropdownLayer); this.elBtn_rowInc = tmp[0]; this.elBtn_rowDec = tmp[1]; this.elBtn_colInc = tmp[2]; this.elBtn_colDec = tmp[3]; this.elBtn_borderStyle = tmp[4]; this.elBtn_incBorderSize = jindo.$$.getSingle("BUTTON.se2m_incBorder", this.elDropdownLayer); this.elBtn_decBorderSize = jindo.$$.getSingle("BUTTON.se2m_decBorder", this.elDropdownLayer); this.elLayer_Dim1 = jindo.$$.getSingle("DIV.se2_t_dim0", this.elDropdownLayer); this.elLayer_Dim2 = jindo.$$.getSingle("DIV.se2_t_dim3", this.elDropdownLayer); // border style layer contains btn elm's tmp = jindo.$$("SPAN.se2_pre_color>BUTTON", this.elDropdownLayer); this.elBtn_borderColor = tmp[0]; this.elBtn_BGColor = tmp[1]; this.elBtn_tableStyle = jindo.$$.getSingle("DIV.se2_select_ty2>BUTTON", this.elDropdownLayer); tmp = jindo.$$("P.se2_btn_area>BUTTON", this.elDropdownLayer); this.elBtn_apply = tmp[0]; this.elBtn_cancel = tmp[1]; this.elTable_preview = jindo.$$.getSingle("TABLE.husky_se2m_table_preview", this.elDropdownLayer); this.elLayer_borderStyle = jindo.$$.getSingle("DIV.husky_se2m_table_border_style_layer", this.elDropdownLayer); this.elPanel_borderStylePreview = jindo.$$.getSingle("SPAN.husky_se2m_table_border_style_preview", this.elDropdownLayer); this.elPanel_borderColorPallet = jindo.$$.getSingle("DIV.husky_se2m_table_border_color_pallet", this.elDropdownLayer); this.elPanel_bgColorPallet = jindo.$$.getSingle("DIV.husky_se2m_table_bgcolor_pallet", this.elDropdownLayer); this.elLayer_tableStyle = jindo.$$.getSingle("DIV.husky_se2m_table_style_layer", this.elDropdownLayer); this.elPanel_tableStylePreview = jindo.$$.getSingle("SPAN.husky_se2m_table_style_preview", this.elDropdownLayer); this.aElBtn_borderStyle = jindo.$$("BUTTON", this.elLayer_borderStyle); this.aElBtn_tableStyle = jindo.$$("BUTTON", this.elLayer_tableStyle); this.sNoBorderText = jindo.$$.getSingle("SPAN.se2m_no_border", this.elDropdownLayer).innerHTML; this.rxLastDigits = RegExp("([0-9]+)$"); }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLObjects(this.oApp.htOptions.elAppContainer); this.oApp.registerBrowserEvent(this.elText_row, "change", "TABLE_SET_ROW_NUM", [null, 0]); this.oApp.registerBrowserEvent(this.elText_col, "change", "TABLE_SET_COLUMN_NUM", [null, 0]); this.oApp.registerBrowserEvent(this.elText_borderSize, "change", "TABLE_SET_BORDER_SIZE", [null, 0]); this.oApp.registerBrowserEvent(this.elBtn_rowInc, "click", "TABLE_INC_ROW"); this.oApp.registerBrowserEvent(this.elBtn_rowDec, "click", "TABLE_DEC_ROW"); jindo.$Fn(this._numRowKeydown, this).attach(this.elText_row.parentNode, "keydown"); this.oApp.registerBrowserEvent(this.elBtn_colInc, "click", "TABLE_INC_COLUMN"); this.oApp.registerBrowserEvent(this.elBtn_colDec, "click", "TABLE_DEC_COLUMN"); jindo.$Fn(this._numColKeydown, this).attach(this.elText_col.parentNode, "keydown"); this.oApp.registerBrowserEvent(this.elBtn_incBorderSize, "click", "TABLE_INC_BORDER_SIZE"); this.oApp.registerBrowserEvent(this.elBtn_decBorderSize, "click", "TABLE_DEC_BORDER_SIZE"); jindo.$Fn(this._borderSizeKeydown, this).attach(this.elText_borderSize.parentNode, "keydown"); this.oApp.registerBrowserEvent(this.elBtn_borderStyle, "click", "TABLE_TOGGLE_BORDER_STYLE_LAYER"); this.oApp.registerBrowserEvent(this.elBtn_tableStyle, "click", "TABLE_TOGGLE_STYLE_LAYER"); this.oApp.registerBrowserEvent(this.elBtn_borderColor, "click", "TABLE_TOGGLE_BORDER_COLOR_PALLET"); this.oApp.registerBrowserEvent(this.elBtn_BGColor, "click", "TABLE_TOGGLE_BGCOLOR_PALLET"); this.oApp.registerBrowserEvent(this.elRadio_manualStyle, "click", "TABLE_ENABLE_MANUAL_STYLE"); this.oApp.registerBrowserEvent(this.elRadio_templateStyle, "click", "TABLE_ENABLE_TEMPLATE_STYLE"); //this.oApp.registerBrowserEvent(this.elDropdownLayer, "click", "TABLE_LAYER_CLICKED"); //this.oApp.registerBrowserEvent(this.elLayer_borderStyle, "click", "TABLE_BORDER_STYLE_LAYER_CLICKED"); //this.oApp.registerBrowserEvent(this.elLayer_tableStyle, "click", "TABLE_STYLE_LAYER_CLICKED"); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aElBtn_borderStyle]); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aElBtn_tableStyle]); var i; for(i=0; i<this.aElBtn_borderStyle.length; i++){ this.oApp.registerBrowserEvent(this.aElBtn_borderStyle[i], "click", "TABLE_SELECT_BORDER_STYLE"); } for(i=0; i<this.aElBtn_tableStyle.length; i++){ this.oApp.registerBrowserEvent(this.aElBtn_tableStyle[i], "click", "TABLE_SELECT_STYLE"); } this.oApp.registerBrowserEvent(this.elBtn_apply, "click", "TABLE_INSERT"); this.oApp.registerBrowserEvent(this.elBtn_cancel, "click", "HIDE_ACTIVE_LAYER"); this.oApp.exec("TABLE_SET_BORDER_COLOR", [/#[0-9A-Fa-f]{6}/.test(this.elText_borderColor.value) ? this.elText_borderColor.value : "#cccccc"]); this.oApp.exec("TABLE_SET_BGCOLOR", [/#[0-9A-Fa-f]{6}/.test(this.elText_BGColor.value) ? this.elText_BGColor.value : "#ffffff"]); // 1: manual style // 2: template style this.nStyleMode = 1; // add #BorderSize+x# if needed //--- // [SMARTEDITORSUS-365] 테이블퀵에디터 > 속성 직접입력 > 테두리 스타일 // - 테두리 없음을 선택하는 경우 본문에 삽입하는 표에 가이드 라인을 표시해 줍니다. 보기 시에는 테두리가 보이지 않습니다. this.aTableStyleByBorder = [ '', 'border="1" cellpadding="0" cellspacing="0" style="border:1px dashed #c7c7c7; border-left:0; border-bottom:0;"', 'border="1" cellpadding="0" cellspacing="0" style="border:#BorderSize#px dashed #BorderColor#; border-left:0; border-bottom:0;"', 'border="0" cellpadding="0" cellspacing="0" style="border:#BorderSize#px solid #BorderColor#; border-left:0; border-bottom:0;"', 'border="0" cellpadding="0" cellspacing="1" style="border:#BorderSize#px solid #BorderColor#;"', 'border="0" cellpadding="0" cellspacing="1" style="border:#BorderSize#px double #BorderColor#;"', 'border="0" cellpadding="0" cellspacing="1" style="border-width:#BorderSize*2#px #BorderSize#px #BorderSize#px #BorderSize*2#px; border-style:solid;border-color:#BorderColor#;"', 'border="0" cellpadding="0" cellspacing="1" style="border-width:#BorderSize#px #BorderSize*2#px #BorderSize*2#px #BorderSize#px; border-style:solid;border-color:#BorderColor#;"' ]; this.aTDStyleByBorder = [ '', 'style="border:1px dashed #c7c7c7; border-top:0; border-right:0; background-color:#BGColor#"', 'style="border:#BorderSize#px dashed #BorderColor#; border-top:0; border-right:0; background-color:#BGColor#"', 'style="border:#BorderSize#px solid #BorderColor#; border-top:0; border-right:0; background-color:#BGColor#"', 'style="border:#BorderSize#px solid #BorderColor#; background-color:#BGColor#"', 'style="border:#BorderSize+2#px double #BorderColor#; background-color:#BGColor#"', 'style="border-width:#BorderSize#px #BorderSize*2#px #BorderSize*2#px #BorderSize#px; border-style:solid;border-color:#BorderColor#; background-color:#BGColor#"', 'style="border-width:#BorderSize*2#px #BorderSize#px #BorderSize#px #BorderSize*2#px; border-style:solid;border-color:#BorderColor#; background-color:#BGColor#"' ]; this.oApp.registerBrowserEvent(this.elDropdownLayer, "keydown", "EVENT_TABLE_CREATE_KEYDOWN"); this._drawTableDropdownLayer(); }, $ON_TABLE_SELECT_BORDER_STYLE : function(weEvent){ var elButton = weEvent.currentElement; // var aMatch = this.rxLastDigits.exec(weEvent.element.className); var aMatch = this.rxLastDigits.exec(elButton.className); this._selectBorderStyle(aMatch[1]); }, $ON_TABLE_SELECT_STYLE : function(weEvent){ var aMatch = this.rxLastDigits.exec(weEvent.element.className); this._selectTableStyle(aMatch[1]); }, $ON_TOGGLE_TABLE_LAYER : function(){ // this.oSelection = this.oApp.getSelection(); this._showNewTable(); this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "SELECT_UI", ["table"], "TABLE_CLOSE", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['table']); }, // $ON_TABLE_BORDER_STYLE_LAYER_CLICKED : function(weEvent){ // top.document.title = weEvent.element.tagName; // }, $ON_TABLE_CLOSE_ALL : function(){ this.oApp.exec("TABLE_HIDE_BORDER_COLOR_PALLET", []); this.oApp.exec("TABLE_HIDE_BGCOLOR_PALLET", []); this.oApp.exec("TABLE_HIDE_BORDER_STYLE_LAYER", []); this.oApp.exec("TABLE_HIDE_STYLE_LAYER", []); }, $ON_TABLE_INC_ROW : function(){ this.oApp.exec("TABLE_SET_ROW_NUM", [null, 1]); }, $ON_TABLE_DEC_ROW : function(){ this.oApp.exec("TABLE_SET_ROW_NUM", [null, -1]); }, $ON_TABLE_INC_COLUMN : function(){ this.oApp.exec("TABLE_SET_COLUMN_NUM", [null, 1]); }, $ON_TABLE_DEC_COLUMN : function(){ this.oApp.exec("TABLE_SET_COLUMN_NUM", [null, -1]); }, $ON_TABLE_SET_ROW_NUM : function(nRows, nRowDiff){ nRows = nRows || parseInt(this.elText_row.value, 10) || 0; nRowDiff = nRowDiff || 0; nRows += nRowDiff; if(nRows < this.nMinRows){nRows = this.nMinRows;} if(nRows > this.nMaxRows){nRows = this.nMaxRows;} this.elText_row.value = nRows; this._showNewTable(); }, $ON_TABLE_SET_COLUMN_NUM : function(nColumns, nColumnDiff){ nColumns = nColumns || parseInt(this.elText_col.value, 10) || 0; nColumnDiff = nColumnDiff || 0; nColumns += nColumnDiff; if(nColumns < this.nMinColumns){nColumns = this.nMinColumns;} if(nColumns > this.nMaxColumns){nColumns = this.nMaxColumns;} this.elText_col.value = nColumns; this._showNewTable(); }, _getTableString : function(){ var sTable; if(this.nStyleMode == 1){ sTable = this._doGetTableString(this.nColumns, this.nRows, this.nBorderSize, this.sBorderColor, this.sBGColor, this.nBorderStyleIdx); }else{ sTable = this._doGetTableString(this.nColumns, this.nRows, this.nBorderSize, this.sBorderColor, this.sBGColor, 0); } return sTable; }, $ON_TABLE_INSERT : function(){ this.oApp.exec("IE_FOCUS", []); // [SMARTEDITORSUS-500] IE인 경우 명시적인 focus 추가 //[SMARTEDITORSUS-596]이벤트 발생이 안되는 경우, //max 제한이 적용이 안되기 때문에 테이블 사입 시점에 다시한번 Max 값을 검사한다. this.oApp.exec("TABLE_SET_COLUMN_NUM"); this.oApp.exec("TABLE_SET_ROW_NUM"); this._loadValuesFromHTML(); var sTable, elLinebreak, elBody, welBody, elTmpDiv, elTable, elFirstTD, oSelection, elTableHolder, htBrowser; elBody = this.oApp.getWYSIWYGDocument().body; welBody = jindo.$Element(elBody); htBrowser = jindo.$Agent().navigator(); this.nTableWidth = elBody.offsetWidth; sTable = this._getTableString(); elTmpDiv = this.oApp.getWYSIWYGDocument().createElement("DIV"); elTmpDiv.innerHTML = sTable; elTable = elTmpDiv.firstChild; elTable.className = this._sSETblClass; oSelection = this.oApp.getSelection(); oSelection = this._divideParagraph(oSelection); // [SMARTEDITORSUS-306] this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["INSERT TABLE", {sSaveTarget:"BODY"}]); // If the table were inserted within a styled(strikethough & etc) paragraph, the table may inherit the style in IE. elTableHolder = this.oApp.getWYSIWYGDocument().createElement("DIV"); // 영역을 잡았을 경우, 영역 지우고 테이블 삽입 oSelection.deleteContents(); oSelection.insertNode(elTableHolder); oSelection.selectNode(elTableHolder); this.oApp.exec("REMOVE_STYLE", [oSelection]); if(htBrowser.ie && this.oApp.getWYSIWYGDocument().body.childNodes.length === 1 && this.oApp.getWYSIWYGDocument().body.firstChild === elTableHolder){ // IE에서 table이 body에 바로 붙어 있을 경우, 정렬등에서 문제가 발생 함으로 elTableHolder(DIV)를 남겨둠 elTableHolder.insertBefore(elTable, null); }else{ elTableHolder.parentNode.insertBefore(elTable, elTableHolder); elTableHolder.parentNode.removeChild(elTableHolder); } // FF : 테이블 하단에 BR이 없을 경우, 커서가 테이블 밑으로 이동할 수 없어 BR을 삽입 해 줌. //[SMARTEDITORSUS-181][IE9] 표나 요약글 등의 테이블에서 > 테이블 외부로 커서 이동 불가 if(htBrowser.firefox){ elLinebreak = this.oApp.getWYSIWYGDocument().createElement("BR"); elTable.parentNode.insertBefore(elLinebreak, elTable.nextSibling); }else if(htBrowser.ie ){ elLinebreak = this.oApp.getWYSIWYGDocument().createElement("p"); elTable.parentNode.insertBefore(elLinebreak, elTable.nextSibling); } if(this.nStyleMode == 2){ this.oApp.exec("STYLE_TABLE", [elTable, this.nTableStyleIdx]); } elFirstTD = elTable.getElementsByTagName("TD")[0]; oSelection.selectNodeContents(elFirstTD.firstChild || elFirstTD); oSelection.collapseToEnd(); oSelection.select(); this.oApp.exec("FOCUS"); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["INSERT TABLE", {sSaveTarget:"BODY"}]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.oApp.exec('MSG_DISPLAY_REEDIT_MESSAGE_SHOW', [this.name, this.sReEditGuideMsg_table]); }, /** * P 안에 Table 이 추가되지 않도록 P 태그를 분리함 * * [SMARTEDITORSUS-306] * P 에 Table 을 추가한 경우, DOM 에서 비정상적인 P 를 생성하여 깨지는 경우가 발생함 * 테이블이 추가되는 부분에 P 가 있는 경우, P 를 분리시켜주는 처리 */ _divideParagraph : function(oSelection){ var oParentP, welParentP, sNodeVaule, sBM, oSWrapper, oEWrapper; oSelection.fixCommonAncestorContainer(); // [SMARTEDITORSUS-423] 엔터에 의해 생성된 P 가 아닌 이전 P 가 선택되지 않도록 fix 하도록 처리 oParentP = oSelection.findAncestorByTagName("P"); if(!oParentP){ return oSelection; } if(!oParentP.firstChild || nhn.husky.SE2M_Utils.isBlankNode(oParentP)){ oSelection.selectNode(oParentP); // [SMARTEDITORSUS-423] 불필요한 개행이 일어나지 않도록 빈 P 를 선택하여 TABLE 로 대체하도록 처리 oSelection.select(); return oSelection; } sBM = oSelection.placeStringBookmark(); oSelection.moveToBookmark(sBM); oSWrapper = this.oApp.getWYSIWYGDocument().createElement("P"); oSelection.setStartBefore(oParentP.firstChild); oSelection.surroundContents(oSWrapper); oSelection.collapseToEnd(); oEWrapper = this.oApp.getWYSIWYGDocument().createElement("P"); oSelection.setEndAfter(oParentP.lastChild); oSelection.surroundContents(oEWrapper); oSelection.collapseToStart(); oSelection.removeStringBookmark(sBM); welParentP = jindo.$Element(oParentP); welParentP.after(oEWrapper); welParentP.after(oSWrapper); welParentP.leave(); oSelection = this.oApp.getEmptySelection(); oSelection.setEndAfter(oSWrapper); oSelection.setStartBefore(oEWrapper); oSelection.select(); return oSelection; }, $ON_TABLE_CLOSE : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.oApp.exec("DESELECT_UI", ["table"]); }, $ON_TABLE_SET_BORDER_SIZE : function(nBorderWidth, nBorderWidthDiff){ nBorderWidth = nBorderWidth || parseInt(this.elText_borderSize.value, 10) || 0; nBorderWidthDiff = nBorderWidthDiff || 0; nBorderWidth += nBorderWidthDiff; if(nBorderWidth < this.nMinBorderWidth){nBorderWidth = this.nMinBorderWidth;} if(nBorderWidth > this.nMaxBorderWidth){nBorderWidth = this.nMaxBorderWidth;} this.elText_borderSize.value = nBorderWidth; }, $ON_TABLE_INC_BORDER_SIZE : function(){ this.oApp.exec("TABLE_SET_BORDER_SIZE", [null, 1]); }, $ON_TABLE_DEC_BORDER_SIZE : function(){ this.oApp.exec("TABLE_SET_BORDER_SIZE", [null, -1]); }, $ON_TABLE_TOGGLE_BORDER_STYLE_LAYER : function(){ if(this.elLayer_borderStyle.style.display == "block"){ this.oApp.exec("TABLE_HIDE_BORDER_STYLE_LAYER", []); }else{ this.oApp.exec("TABLE_SHOW_BORDER_STYLE_LAYER", []); } }, $ON_TABLE_SHOW_BORDER_STYLE_LAYER : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.elBtn_borderStyle.className = "se2_view_more2"; this.elLayer_borderStyle.style.display = "block"; this._refresh(); }, $ON_TABLE_HIDE_BORDER_STYLE_LAYER : function(){ this.elBtn_borderStyle.className = "se2_view_more"; this.elLayer_borderStyle.style.display = "none"; this._refresh(); }, $ON_TABLE_TOGGLE_STYLE_LAYER : function(){ if(this.elLayer_tableStyle.style.display == "block"){ this.oApp.exec("TABLE_HIDE_STYLE_LAYER", []); }else{ this.oApp.exec("TABLE_SHOW_STYLE_LAYER", []); } }, $ON_TABLE_SHOW_STYLE_LAYER : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.elBtn_tableStyle.className = "se2_view_more2"; this.elLayer_tableStyle.style.display = "block"; this._refresh(); }, $ON_TABLE_HIDE_STYLE_LAYER : function(){ this.elBtn_tableStyle.className = "se2_view_more"; this.elLayer_tableStyle.style.display = "none"; this._refresh(); }, $ON_TABLE_TOGGLE_BORDER_COLOR_PALLET : function(){ if(this.welDropdownLayer.hasClass("p1")){ this.oApp.exec("TABLE_HIDE_BORDER_COLOR_PALLET", []); }else{ this.oApp.exec("TABLE_SHOW_BORDER_COLOR_PALLET", []); } }, $ON_TABLE_SHOW_BORDER_COLOR_PALLET : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.welDropdownLayer.addClass("p1"); this.welDropdownLayer.removeClass("p2"); this.oApp.exec("SHOW_COLOR_PALETTE", ["TABLE_SET_BORDER_COLOR_FROM_PALETTE", this.elPanel_borderColorPallet]); this.elPanel_borderColorPallet.parentNode.style.display = "block"; }, $ON_TABLE_HIDE_BORDER_COLOR_PALLET : function(){ this.welDropdownLayer.removeClass("p1"); this.oApp.exec("HIDE_COLOR_PALETTE", []); this.elPanel_borderColorPallet.parentNode.style.display = "none"; }, $ON_TABLE_TOGGLE_BGCOLOR_PALLET : function(){ if(this.welDropdownLayer.hasClass("p2")){ this.oApp.exec("TABLE_HIDE_BGCOLOR_PALLET", []); }else{ this.oApp.exec("TABLE_SHOW_BGCOLOR_PALLET", []); } }, $ON_TABLE_SHOW_BGCOLOR_PALLET : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.welDropdownLayer.removeClass("p1"); this.welDropdownLayer.addClass("p2"); this.oApp.exec("SHOW_COLOR_PALETTE", ["TABLE_SET_BGCOLOR_FROM_PALETTE", this.elPanel_bgColorPallet]); this.elPanel_bgColorPallet.parentNode.style.display = "block"; }, $ON_TABLE_HIDE_BGCOLOR_PALLET : function(){ this.welDropdownLayer.removeClass("p2"); this.oApp.exec("HIDE_COLOR_PALETTE", []); this.elPanel_bgColorPallet.parentNode.style.display = "none"; }, $ON_TABLE_SET_BORDER_COLOR_FROM_PALETTE : function(sColorCode){ this.oApp.exec("TABLE_SET_BORDER_COLOR", [sColorCode]); this.oApp.exec("TABLE_HIDE_BORDER_COLOR_PALLET", []); }, $ON_TABLE_SET_BORDER_COLOR : function(sColorCode){ this.elText_borderColor.value = sColorCode; this.elBtn_borderColor.style.backgroundColor = sColorCode; }, $ON_TABLE_SET_BGCOLOR_FROM_PALETTE : function(sColorCode){ this.oApp.exec("TABLE_SET_BGCOLOR", [sColorCode]); this.oApp.exec("TABLE_HIDE_BGCOLOR_PALLET", []); }, $ON_TABLE_SET_BGCOLOR : function(sColorCode){ this.elText_BGColor.value = sColorCode; this.elBtn_BGColor.style.backgroundColor = sColorCode; }, $ON_TABLE_ENABLE_MANUAL_STYLE : function(){ this.nStyleMode = 1; this._drawTableDropdownLayer(); }, $ON_TABLE_ENABLE_TEMPLATE_STYLE : function(){ this.nStyleMode = 2; this._drawTableDropdownLayer(); }, $ON_EVENT_TABLE_CREATE_KEYDOWN : function(oEvent){ if (oEvent.key().enter){ this.elBtn_apply.focus(); this.oApp.exec("TABLE_INSERT"); oEvent.stop(); } }, _drawTableDropdownLayer : function(){ if(this.nBorderStyleIdx == 1){ this.elPanel_borderStylePreview.innerHTML = this.sNoBorderText; this.elLayer_Dim1.className = "se2_t_dim2"; }else{ this.elPanel_borderStylePreview.innerHTML = ""; this.elLayer_Dim1.className = "se2_t_dim0"; } if(this.nStyleMode == 1){ this.elRadio_manualStyle.checked = true; this.elLayer_Dim2.className = "se2_t_dim3"; this.elText_borderSize.disabled = false; this.elText_borderColor.disabled = false; this.elText_BGColor.disabled = false; }else{ this.elRadio_templateStyle.checked = true; this.elLayer_Dim2.className = "se2_t_dim1"; this.elText_borderSize.disabled = true; this.elText_borderColor.disabled = true; this.elText_BGColor.disabled = true; } this.oApp.exec("TABLE_CLOSE_ALL", []); }, _selectBorderStyle : function(nStyleNum){ this.elPanel_borderStylePreview.className = "se2_b_style"+nStyleNum; this.nBorderStyleIdx = nStyleNum; this._drawTableDropdownLayer(); }, _selectTableStyle : function(nStyleNum){ this.elPanel_tableStylePreview.className = "se2_t_style"+nStyleNum; this.nTableStyleIdx = nStyleNum; this._drawTableDropdownLayer(); }, _showNewTable : function(){ var oTmp = document.createElement("DIV"); this._loadValuesFromHTML(); oTmp.innerHTML = this._getPreviewTableString(this.nColumns, this.nRows); //this.nTableWidth = 0; //oTmp.innerHTML = this._getTableString(); var oNewTable = oTmp.firstChild; this.elTable_preview.parentNode.insertBefore(oNewTable, this.elTable_preview); this.elTable_preview.parentNode.removeChild(this.elTable_preview); this.elTable_preview = oNewTable; this._refresh(); }, _getPreviewTableString : function(nColumns, nRows){ var sTable = '<table border="0" cellspacing="1" class="se2_pre_table husky_se2m_table_preview">'; var sRow = '<tr>'; for(var i=0; i<nColumns; i++){ sRow += "<td><p>&nbsp;</p></td>\n"; } sRow += "</tr>\n"; sTable += "<tbody>"; for(var i=0; i<nRows; i++){ sTable += sRow; } sTable += "</tbody>\n"; sTable += "</table>\n"; return sTable; }, _loadValuesFromHTML : function(){ this.nColumns = parseInt(this.elText_col.value, 10) || 1; this.nRows = parseInt(this.elText_row.value, 10) || 1; this.nBorderSize = parseInt(this.elText_borderSize.value, 10) || 1; this.sBorderColor = this.elText_borderColor.value; this.sBGColor = this.elText_BGColor.value; }, _doGetTableString : function(nColumns, nRows, nBorderSize, sBorderColor, sBGColor, nBorderStyleIdx){ var nTDWidth = parseInt(this.nTableWidth/nColumns, 10); var nBorderSize = this.nBorderSize; var sTableStyle = this.aTableStyleByBorder[nBorderStyleIdx].replace(/#BorderSize#/g, this.nBorderSize).replace(/#BorderSize\*([0-9]+)#/g, function(sAll, s1){return nBorderSize*parseInt(s1, 10);}).replace(/#BorderSize\+([0-9]+)#/g, function(sAll, s1){return nBorderSize+parseInt(s1, 10);}).replace("#BorderColor#", this.sBorderColor).replace("#BGColor#", this.sBGColor); var sTDStyle = this.aTDStyleByBorder[nBorderStyleIdx].replace(/#BorderSize#/g, this.nBorderSize).replace(/#BorderSize\*([0-9]+)#/g, function(sAll, s1){return nBorderSize*parseInt(s1, 10);}).replace(/#BorderSize\+([0-9]+)#/g, function(sAll, s1){return nBorderSize+parseInt(s1, 10);}).replace("#BorderColor#", this.sBorderColor).replace("#BGColor#", this.sBGColor); if(nTDWidth){ sTDStyle += " width="+nTDWidth; }else{ //sTableStyle += " width=100%"; sTableStyle += "class=se2_pre_table"; } // [SMARTEDITORSUS-365] 테이블퀵에디터 > 속성 직접입력 > 테두리 스타일 // - 테두리 없음을 선택하는 경우 본문에 삽입하는 표에 가이드 라인을 표시해 줍니다. 보기 시에는 테두리가 보이지 않습니다. // - 글 저장 시에는 글 작성 시에 적용하였던 style 을 제거합니다. 이를 위해서 임의의 속성(attr_no_border_tbl)을 추가하였다가 저장 시점에서 제거해 주도록 합니다. var sTempNoBorderClass = (nBorderStyleIdx == 1) ? 'attr_no_border_tbl="1"' : ''; var sTable = "<table "+sTableStyle+" "+sTempNoBorderClass+">"; var sRow = "<tr>"; for(var i=0; i<nColumns; i++){ sRow += "<td "+sTDStyle+"><p>&nbsp;</p></td>\n"; } sRow += "</tr>\n"; sTable += "<tbody>\n"; for(var i=0; i<nRows; i++){ sTable += sRow; } sTable += "</tbody>\n"; sTable += "</table>\n<br>"; return sTable; }, _numRowKeydown : function(weEvent){ var oKeyInfo = weEvent.key(); // up if(oKeyInfo.keyCode == 38){ this.oApp.exec("TABLE_INC_ROW", []); } // down if(oKeyInfo.keyCode == 40){ this.oApp.exec("TABLE_DEC_ROW", []); } }, _numColKeydown : function(weEvent){ var oKeyInfo = weEvent.key(); // up if(oKeyInfo.keyCode == 38){ this.oApp.exec("TABLE_INC_COLUMN", []); } // down if(oKeyInfo.keyCode == 40){ this.oApp.exec("TABLE_DEC_COLUMN", []); } }, _borderSizeKeydown : function(weEvent){ var oKeyInfo = weEvent.key(); // up if(oKeyInfo.keyCode == 38){ this.oApp.exec("TABLE_INC_BORDER_SIZE", []); } // down if(oKeyInfo.keyCode == 40){ this.oApp.exec("TABLE_DEC_BORDER_SIZE", []); } }, _refresh : function(){ // the dropdown layer breaks without this line in IE 6 when modifying the preview table this.elDropdownLayer.style.zoom=0; this.elDropdownLayer.style.zoom=""; } //@lazyload_js] }); //} nhn.husky.SE2M_TableEditor = jindo.$Class({ name : "SE2M_TableEditor", _sSETblClass : "__se_tbl", _sSEReviewTblClass : "__se_tbl_review", STATUS : { S_0 : 1, // neither cell selection nor cell resizing is active MOUSEDOWN_CELL : 2, // mouse down on a table cell CELL_SELECTING : 3, // cell selection is in progress CELL_SELECTED : 4, // cell selection was (completely) made MOUSEOVER_BORDER : 5, // mouse is over a table/cell border and the cell resizing grip is shown MOUSEDOWN_BORDER : 6 // mouse down on the cell resizing grip (cell resizing is in progress) }, CELL_SELECTION_CLASS : "se2_te_selection", MIN_CELL_WIDTH : 5, MIN_CELL_HEIGHT : 5, TMP_BGC_ATTR : "_se2_tmp_te_bgc", TMP_BGIMG_ATTR : "_se2_tmp_te_bg_img", ATTR_TBL_TEMPLATE : "_se2_tbl_template", nStatus : 1, nMouseEventsStatus : 0, aSelectedCells : [], $ON_REGISTER_CONVERTERS : function(){ // remove the cell selection class this.oApp.exec("ADD_CONVERTER_DOM", ["WYSIWYG_TO_IR", jindo.$Fn(function(elTmpNode){ if(this.aSelectedCells.length < 1){ //return sContents; return; } var aCells; var aCellType = ["TD", "TH"]; for(var n = 0; n < aCellType.length; n++){ aCells = elTmpNode.getElementsByTagName(aCellType[n]); for(var i = 0, nLen = aCells.length; i < nLen; i++){ if(aCells[i].className){ aCells[i].className = aCells[i].className.replace(this.CELL_SELECTION_CLASS, ""); if(aCells[i].getAttribute(this.TMP_BGC_ATTR)){ aCells[i].style.backgroundColor = aCells[i].getAttribute(this.TMP_BGC_ATTR); aCells[i].removeAttribute(this.TMP_BGC_ATTR); }else if(aCells[i].getAttribute(this.TMP_BGIMG_ATTR)){ jindo.$Element(this.aCells[i]).css("backgroundImage",aCells[i].getAttribute(this.TMP_BGIMG_ATTR)); aCells[i].removeAttribute(this.TMP_BGIMG_ATTR); } } } } // this.wfnMouseDown.attach(this.elResizeCover, "mousedown"); // return elTmpNode.innerHTML; // var rxSelectionColor = new RegExp("<(TH|TD)[^>]*)("+this.TMP_BGC_ATTR+"=[^> ]*)([^>]*>)", "gi"); }, this).bind()]); }, //@lazyload_js EVENT_EDITING_AREA_MOUSEMOVE:SE2M_TableTemplate.js[ _assignHTMLObjects : function(){ this.oApp.exec("LOAD_HTML", ["qe_table"]); this.elQELayer = jindo.$$.getSingle("DIV.q_table_wrap", this.oApp.htOptions.elAppContainer); this.elQELayer.style.zIndex = 150; this.elBtnAddRowBelow = jindo.$$.getSingle("BUTTON.se2_addrow", this.elQELayer); this.elBtnAddColumnRight = jindo.$$.getSingle("BUTTON.se2_addcol", this.elQELayer); this.elBtnSplitRow = jindo.$$.getSingle("BUTTON.se2_seprow", this.elQELayer); this.elBtnSplitColumn = jindo.$$.getSingle("BUTTON.se2_sepcol", this.elQELayer); this.elBtnDeleteRow = jindo.$$.getSingle("BUTTON.se2_delrow", this.elQELayer); this.elBtnDeleteColumn = jindo.$$.getSingle("BUTTON.se2_delcol", this.elQELayer); this.elBtnMergeCell = jindo.$$.getSingle("BUTTON.se2_merrow", this.elQELayer); this.elBtnBGPalette = jindo.$$.getSingle("BUTTON.husky_se2m_table_qe_bgcolor_btn", this.elQELayer); this.elBtnBGIMGPalette = jindo.$$.getSingle("BUTTON.husky_se2m_table_qe_bgimage_btn", this.elQELayer); this.elPanelBGPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_bg_paletteHolder", this.elQELayer); this.elPanelBGIMGPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_bg_img_paletteHolder", this.elQELayer); this.elPanelTableBGArea = jindo.$$.getSingle("DIV.se2_qe2", this.elQELayer); this.elPanelTableTemplateArea = jindo.$$.getSingle("DL.se2_qe3", this.elQELayer); this.elPanelReviewBGArea = jindo.$$.getSingle("DL.husky_se2m_tbl_qe_review_bg", this.elQELayer); this.elPanelBGImg = jindo.$$.getSingle("DD", this.elPanelReviewBGArea); this.welPanelTableBGArea = jindo.$Element(this.elPanelTableBGArea); this.welPanelTableTemplateArea = jindo.$Element(this.elPanelTableTemplateArea); this.welPanelReviewBGArea = jindo.$Element(this.elPanelReviewBGArea); // this.elPanelReviewBtnArea = jindo.$$.getSingle("DIV.se2_btn_area", this.elQELayer); //My리뷰 버튼 레이어 this.elPanelDim1 = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim1", this.elQELayer); this.elPanelDim2 = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim2", this.elQELayer); this.elPanelDimDelCol = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim_del_col", this.elQELayer); this.elPanelDimDelRow = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim_del_row", this.elQELayer); this.elInputRadioBGColor = jindo.$$.getSingle("INPUT.husky_se2m_radio_bgc", this.elQELayer); this.elInputRadioBGImg = jindo.$$.getSingle("INPUT.husky_se2m_radio_bgimg", this.elQELayer); this.elSelectBoxTemplate = jindo.$$.getSingle("DIV.se2_select_ty2", this.elQELayer); this.elInputRadioTemplate = jindo.$$.getSingle("INPUT.husky_se2m_radio_template", this.elQELayer); this.elPanelQETemplate = jindo.$$.getSingle("DIV.se2_layer_t_style", this.elQELayer); this.elBtnQETemplate = jindo.$$.getSingle("BUTTON.husky_se2m_template_more", this.elQELayer); this.elPanelQETemplatePreview = jindo.$$.getSingle("SPAN.se2_t_style1", this.elQELayer); this.aElBtn_tableStyle = jindo.$$("BUTTON", this.elPanelQETemplate); for(i = 0; i < this.aElBtn_tableStyle.length; i++){ this.oApp.registerBrowserEvent(this.aElBtn_tableStyle[i], "click", "TABLE_QE_SELECT_TEMPLATE"); } }, $LOCAL_BEFORE_FIRST : function(sMsg){ if(!!sMsg.match(/(REGISTER_CONVERTERS)/)){ this.oApp.acceptLocalBeforeFirstAgain(this, true); return true; }else{ if(!sMsg.match(/(EVENT_EDITING_AREA_MOUSEMOVE)/)){ this.oApp.acceptLocalBeforeFirstAgain(this, true); return false; } } this.htResizing = {}; this.nDraggableCellEdge = 2; var elBody = jindo.$Element(document.body); this.nPageLeftRightMargin = parseInt(elBody.css("marginLeft"), 10) + parseInt(elBody.css("marginRight"), 10); this.nPageTopBottomMargin = parseInt(elBody.css("marginTop"), 10) + parseInt(elBody.css("marginBottom"), 10); //this.nPageLeftRightMargin = parseInt(elBody.css("marginLeft"), 10)+parseInt(elBody.css("marginRight"), 10) + parseInt(elBody.css("paddingLeft"), 10)+parseInt(elBody.css("paddingRight"), 10); //this.nPageTopBottomMargin = parseInt(elBody.css("marginTop"), 10)+parseInt(elBody.css("marginBottom"), 10) + parseInt(elBody.css("paddingTop"), 10)+parseInt(elBody.css("paddingBottom"), 10); this.QE_DIM_MERGE_BTN = 1; this.QE_DIM_BG_COLOR = 2; this.QE_DIM_REVIEW_BG_IMG = 3; this.QE_DIM_TABLE_TEMPLATE = 4; this.rxLastDigits = RegExp("([0-9]+)$"); this._assignHTMLObjects(); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aElBtn_tableStyle]); this.addCSSClass(this.CELL_SELECTION_CLASS, "background-color:#B4C9E9;"); this._createCellResizeGrip(); this.elIFrame = this.oApp.getWYSIWYGWindow().frameElement; this.htFrameOffset = jindo.$Element(this.elIFrame).offset(); var elTarget; this.sEmptyTDSrc = ""; if(this.oApp.oNavigator.firefox){ this.sEmptyTDSrc = "<p><br/></p>"; }else{ this.sEmptyTDSrc = "<p>&nbsp;</p>"; } elTarget = this.oApp.getWYSIWYGDocument(); /* jindo.$Fn(this._mousedown_WYSIWYGDoc, this).attach(elTarget, "mousedown"); jindo.$Fn(this._mousemove_WYSIWYGDoc, this).attach(elTarget, "mousemove"); jindo.$Fn(this._mouseup_WYSIWYGDoc, this).attach(elTarget, "mouseup"); */ elTarget = this.elResizeCover; this.wfnMousedown_ResizeCover = jindo.$Fn(this._mousedown_ResizeCover, this); this.wfnMousemove_ResizeCover = jindo.$Fn(this._mousemove_ResizeCover, this); this.wfnMouseup_ResizeCover = jindo.$Fn(this._mouseup_ResizeCover, this); this.wfnMousedown_ResizeCover.attach(elTarget, "mousedown"); this._changeTableEditorStatus(this.STATUS.S_0); // this.oApp.registerBrowserEvent(doc, "click", "EVENT_EDITING_AREA_CLICK"); this.oApp.registerBrowserEvent(this.elBtnMergeCell, "click", "TE_MERGE_CELLS"); this.oApp.registerBrowserEvent(this.elBtnSplitColumn, "click", "TE_SPLIT_COLUMN"); this.oApp.registerBrowserEvent(this.elBtnSplitRow, "click", "TE_SPLIT_ROW"); // this.oApp.registerBrowserEvent(this.elBtnAddColumnLeft, "click", "TE_INSERT_COLUMN_LEFT"); this.oApp.registerBrowserEvent(this.elBtnAddColumnRight, "click", "TE_INSERT_COLUMN_RIGHT"); this.oApp.registerBrowserEvent(this.elBtnAddRowBelow, "click", "TE_INSERT_ROW_BELOW"); // this.oApp.registerBrowserEvent(this.elBtnAddRowAbove, "click", "TE_INSERT_ROW_ABOVE"); this.oApp.registerBrowserEvent(this.elBtnDeleteColumn, "click", "TE_DELETE_COLUMN"); this.oApp.registerBrowserEvent(this.elBtnDeleteRow, "click", "TE_DELETE_ROW"); this.oApp.registerBrowserEvent(this.elInputRadioBGColor, "click", "DRAW_QE_RADIO_OPTION", [2]); this.oApp.registerBrowserEvent(this.elInputRadioBGImg, "click", "DRAW_QE_RADIO_OPTION", [3]); this.oApp.registerBrowserEvent(this.elInputRadioTemplate, "click", "DRAW_QE_RADIO_OPTION", [4]); this.oApp.registerBrowserEvent(this.elBtnBGPalette, "click", "TABLE_QE_TOGGLE_BGC_PALETTE"); // this.oApp.registerBrowserEvent(this.elPanelReviewBtnArea, "click", "SAVE_QE_MY_REVIEW_ITEM"); //My리뷰 버튼 레이어 this.oApp.registerBrowserEvent(this.elBtnBGIMGPalette, "click", "TABLE_QE_TOGGLE_IMG_PALETTE"); this.oApp.registerBrowserEvent(this.elPanelBGIMGPaletteHolder, "click", "TABLE_QE_SET_IMG_FROM_PALETTE"); //this.elPanelQETemplate //this.elBtnQETemplate this.oApp.registerBrowserEvent(this.elBtnQETemplate, "click", "TABLE_QE_TOGGLE_TEMPLATE"); this.oApp.registerBrowserEvent(document.body, "mouseup", "EVENT_OUTER_DOC_MOUSEUP"); this.oApp.registerBrowserEvent(document.body, "mousemove", "EVENT_OUTER_DOC_MOUSEMOVE"); }, $ON_EVENT_EDITING_AREA_KEYUP : function(oEvent){ // for undo/redo and other hotkey functions var oKeyInfo = oEvent.key(); // 229: Korean/Eng, 33, 34: page up/down, 35,36: end/home, 37,38,39,40: left, up, right, down, 16: shift if(oKeyInfo.keyCode == 229 || oKeyInfo.alt || oKeyInfo.ctrl || oKeyInfo.keyCode == 16){ return; }else if(oKeyInfo.keyCode == 8 || oKeyInfo.keyCode == 46){ this.oApp.exec("DELETE_BLOCK_CONTENTS"); oEvent.stop(); } switch(this.nStatus){ case this.STATUS.CELL_SELECTED: this._changeTableEditorStatus(this.STATUS.S_0); break; } }, $ON_TABLE_QE_SELECT_TEMPLATE : function(weEvent){ var aMatch = this.rxLastDigits.exec(weEvent.element.className); var elCurrentTable = this.elSelectionStartTable; this._changeTableEditorStatus(this.STATUS.S_0); this.oApp.exec("STYLE_TABLE", [elCurrentTable, aMatch[1]]); //this._selectTableStyle(aMatch[1]); var elSaveTarget = !!elCurrentTable && elCurrentTable.parentNode ? elCurrentTable.parentNode : null; var sSaveTarget = !elCurrentTable ? "BODY" : null; this.oApp.exec("RECORD_UNDO_ACTION", ["CHANGE_TABLE_STYLE", {elSaveTarget:elSaveTarget, sSaveTarget : sSaveTarget, bDontSaveSelection:true}]); }, $BEFORE_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ if(sMode !== "WYSIWYG" && this.nStatus !== this.STATUS.S_0){ this._changeTableEditorStatus(this.STATUS.S_0); } }, // [Undo/Redo] Table Selection 처리와 관련된 부분 주석 처리 // $AFTER_DO_RECORD_UNDO_HISTORY : function(){ // if(this.nStatus != this.STATUS.CELL_SELECTED){ // return; // } // // if(this.aSelectedCells.length < 1){ // return; // } // // var aTables = this.oApp.getWYSIWYGDocument().getElementsByTagName("TABLE"); // for(var nTableIdx = 0, nLen = aTables.length; nTableIdx < nLen; nTableIdx++){ // if(aTables[nTableIdx] === this.elSelectionStartTable){ // break; // } // } // // var aUndoHistory = this.oApp.getUndoHistory(); // var oUndoStateIdx = this.oApp.getUndoStateIdx(); // if(!aUndoHistory[oUndoStateIdx.nIdx].htTableSelection){ // aUndoHistory[oUndoStateIdx.nIdx].htTableSelection = []; // } // aUndoHistory[oUndoStateIdx.nIdx].htTableSelection[oUndoStateIdx.nStep] = { // nTableIdx : nTableIdx, // nSX : this.htSelectionSPos.x, // nSY : this.htSelectionSPos.y, // nEX : this.htSelectionEPos.x, // nEY : this.htSelectionEPos.y // }; // }, // // $BEFORE_RESTORE_UNDO_HISTORY : function(){ // if(this.nStatus == this.STATUS.CELL_SELECTED){ // var oSelection = this.oApp.getEmptySelection(); // oSelection.selectNode(this.elSelectionStartTable); // oSelection.collapseToEnd(); // oSelection.select(); // } // }, // // $AFTER_RESTORE_UNDO_HISTORY : function(){ // var aUndoHistory = this.oApp.getUndoHistory(); // var oUndoStateIdx = this.oApp.getUndoStateIdx(); // // if(aUndoHistory[oUndoStateIdx.nIdx].htTableSelection && aUndoHistory[oUndoStateIdx.nIdx].htTableSelection[oUndoStateIdx.nStep]){ // var htTableSelection = aUndoHistory[oUndoStateIdx.nIdx].htTableSelection[oUndoStateIdx.nStep]; // this.elSelectionStartTable = this.oApp.getWYSIWYGDocument().getElementsByTagName("TABLE")[htTableSelection.nTableIdx]; // this.htMap = this._getCellMapping(this.elSelectionStartTable); // // this.htSelectionSPos.x = htTableSelection.nSX; // this.htSelectionSPos.y = htTableSelection.nSY; // this.htSelectionEPos.x = htTableSelection.nEX; // this.htSelectionEPos.y = htTableSelection.nEY; // this._selectCells(this.htSelectionSPos, this.htSelectionEPos); // // this._startCellSelection(); // this._changeTableEditorStatus(this.STATUS.CELL_SELECTED); // }else{ // this._changeTableEditorStatus(this.STATUS.S_0); // } // }, /** * 테이블 셀 배경색 셋팅 */ $ON_TABLE_QE_TOGGLE_BGC_PALETTE : function(){ if(this.elPanelBGPaletteHolder.parentNode.style.display == "block"){ this.oApp.exec("HIDE_TABLE_QE_BGC_PALETTE", []); }else{ this.oApp.exec("SHOW_TABLE_QE_BGC_PALETTE", []); } }, $ON_SHOW_TABLE_QE_BGC_PALETTE : function(){ this.elPanelBGPaletteHolder.parentNode.style.display = "block"; this.oApp.exec("SHOW_COLOR_PALETTE", ["TABLE_QE_SET_BGC_FROM_PALETTE", this.elPanelBGPaletteHolder]); }, $ON_HIDE_TABLE_QE_BGC_PALETTE : function(){ this.elPanelBGPaletteHolder.parentNode.style.display = "none"; this.oApp.exec("HIDE_COLOR_PALETTE", []); }, $ON_TABLE_QE_SET_BGC_FROM_PALETTE : function(sColorCode){ this.oApp.exec("TABLE_QE_SET_BGC", [sColorCode]); if(this.oSelection){ this.oSelection.select(); } this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TABLE_QE_SET_BGC : function(sColorCode){ this.elBtnBGPalette.style.backgroundColor = sColorCode; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ this.aSelectedCells[i].setAttribute(this.TMP_BGC_ATTR, sColorCode); this.aSelectedCells[i].removeAttribute(this.TMP_BGIMG_ATTR); } this.sQEAction = "TABLE_SET_BGCOLOR"; }, /** * 테이블 리뷰 테이블 배경 이미지 셋팅 */ $ON_TABLE_QE_TOGGLE_IMG_PALETTE : function(){ if(this.elPanelBGIMGPaletteHolder.parentNode.style.display == "block"){ this.oApp.exec("HIDE_TABLE_QE_IMG_PALETTE", []); }else{ this.oApp.exec("SHOW_TABLE_QE_IMG_PALETTE", []); } }, $ON_SHOW_TABLE_QE_IMG_PALETTE : function(){ this.elPanelBGIMGPaletteHolder.parentNode.style.display = "block"; }, $ON_HIDE_TABLE_QE_IMG_PALETTE : function(){ this.elPanelBGIMGPaletteHolder.parentNode.style.display = "none"; }, $ON_TABLE_QE_SET_IMG_FROM_PALETTE : function(elEvt){ this.oApp.exec("TABLE_QE_SET_IMG", [elEvt.element]); if(this.oSelection){ this.oSelection.select(); } this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TABLE_QE_SET_IMG : function(elSelected){ var sClassName = jindo.$Element(elSelected).className(); var welBtnBGIMGPalette = jindo.$Element(this.elBtnBGIMGPalette); var aBtnClassNames = welBtnBGIMGPalette.className().split(" "); for(var i = 0, nLen = aBtnClassNames.length; i < nLen; i++){ if(aBtnClassNames[i].indexOf("cellimg") > 0){ welBtnBGIMGPalette.removeClass(aBtnClassNames[i]); } } jindo.$Element(this.elBtnBGIMGPalette).addClass(sClassName); var n = sClassName.substring(11, sClassName.length); //se2_cellimg11 var sImageName = "pattern_"; if(n === "0"){ for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ jindo.$Element(this.aSelectedCells[i]).css("backgroundImage", ""); this.aSelectedCells[i].removeAttribute(this.TMP_BGC_ATTR); this.aSelectedCells[i].removeAttribute(this.TMP_BGIMG_ATTR); } }else{ if(n == 19 || n == 20 || n == 21 || n == 22 || n == 25 || n == 26){ //파일 사이즈때문에 jpg sImageName = sImageName + n + ".jpg"; }else{ sImageName = sImageName + n + ".gif"; } for(var j = 0, nLen = this.aSelectedCells.length; j < nLen ; j++){ jindo.$Element(this.aSelectedCells[j]).css("backgroundImage", "url("+"http://static.se2.naver.com/static/img/"+sImageName+")"); this.aSelectedCells[j].removeAttribute(this.TMP_BGC_ATTR); this.aSelectedCells[j].setAttribute(this.TMP_BGIMG_ATTR, "url("+"http://static.se2.naver.com/static/img/"+sImageName+")"); } } this.sQEAction = "TABLE_SET_BGIMAGE"; }, $ON_SAVE_QE_MY_REVIEW_ITEM : function(){ this.oApp.exec("SAVE_MY_REVIEW_ITEM"); this.oApp.exec("CLOSE_QE_LAYER"); }, /** * 테이블 퀵 에디터 Show */ $ON_SHOW_COMMON_QE : function(){ if(jindo.$Element(this.elSelectionStartTable).hasClass(this._sSETblClass)){ this.oApp.exec("SHOW_TABLE_QE"); }else{ if(jindo.$Element(this.elSelectionStartTable).hasClass(this._sSEReviewTblClass)){ this.oApp.exec("SHOW_REVIEW_QE"); } } }, $ON_SHOW_TABLE_QE : function(){ this.oApp.exec("HIDE_TABLE_QE_BGC_PALETTE", []); this.oApp.exec("TABLE_QE_HIDE_TEMPLATE", []); this.oApp.exec("SETUP_TABLE_QE_MODE", [0]); this.oApp.exec("OPEN_QE_LAYER", [this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y], this.elQELayer, "table"]); //this.oApp.exec("FOCUS"); }, $ON_SHOW_REVIEW_QE : function(){ this.oApp.exec("SETUP_TABLE_QE_MODE", [1]); this.oApp.exec("OPEN_QE_LAYER", [this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y], this.elQELayer, "review"]); }, $ON_CLOSE_SUB_LAYER_QE : function(){ if(typeof this.elPanelBGPaletteHolder != 'undefined'){ this.elPanelBGPaletteHolder.parentNode.style.display = "none"; } if(typeof this.elPanelBGIMGPaletteHolder != 'undefined'){ this.elPanelBGIMGPaletteHolder.parentNode.style.display = "none"; } }, // 0: table // 1: review $ON_SETUP_TABLE_QE_MODE : function(nMode){ var bEnableMerge = true; if(typeof nMode == "number"){ this.nQEMode = nMode; } if(this.aSelectedCells.length < 2){ bEnableMerge = false; } this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_MERGE_BTN, bEnableMerge]); //null인경우를 대비해서 default값을 지정해준다. var sBackgroundColor = this.aSelectedCells[0].getAttribute(this.TMP_BGC_ATTR) || "rgb(255,255,255)"; var bAllMatched = true; for(var i = 1, nLen = this.aSelectedCells.length; i < nLen; i++){ // [SMARTEDITORSUS-1552] 드래그로 셀을 선택하는 중 elCell이 없는 경우 오류 발생 if(this.aSelectedCells[i]){ if(sBackgroundColor != this.aSelectedCells[i].getAttribute(this.TMP_BGC_ATTR)){ bAllMatched = false; break; } } // --[SMARTEDITORSUS-1552] } if(bAllMatched){ this.elBtnBGPalette.style.backgroundColor = sBackgroundColor; }else{ this.elBtnBGPalette.style.backgroundColor = "#FFFFFF"; } var sBackgroundImage = this.aSelectedCells[0].getAttribute(this.TMP_BGIMG_ATTR) || ""; var bAllMatchedImage = true; var sPatternInfo, nPatternImage = 0; var welBtnBGIMGPalette = jindo.$Element(this.elBtnBGIMGPalette); if(!!sBackgroundImage){ var aPattern = sBackgroundImage.match(/\_[0-9]*/); sPatternInfo = (!!aPattern)?aPattern[0] : "_0"; nPatternImage = sPatternInfo.substring(1, sPatternInfo.length); for(var i = 1, nLen = this.aSelectedCells.length; i < nLen; i++){ if(sBackgroundImage != this.aSelectedCells[i].getAttribute(this.TMP_BGIMG_ATTR)){ bAllMatchedImage = false; break; } } } var aBtnClassNames = welBtnBGIMGPalette.className().split(/\s/); for(var j = 0, nLen = aBtnClassNames.length; j < nLen; j++){ if(aBtnClassNames[j].indexOf("cellimg") > 0){ welBtnBGIMGPalette.removeClass(aBtnClassNames[j]); } } if(bAllMatchedImage && nPatternImage > 0){ welBtnBGIMGPalette.addClass("se2_cellimg" + nPatternImage); }else{ welBtnBGIMGPalette.addClass("se2_cellimg0"); } if(this.nQEMode === 0){ //table this.elPanelTableTemplateArea.style.display = "block"; // this.elSelectBoxTemplate.style.display = "block"; this.elPanelReviewBGArea.style.display = "none"; // this.elSelectBoxTemplate.style.position = ""; //this.elPanelReviewBtnArea.style.display = "none"; //My리뷰 버튼 레이어 // 배경Area에서 css를 제거해야함 jindo.$Element(this.elPanelTableBGArea).className("se2_qe2"); var nTpl = this.parseIntOr0(this.elSelectionStartTable.getAttribute(this.ATTR_TBL_TEMPLATE)); if(nTpl){ //this.elInputRadioTemplate.checked = "true"; }else{ this.elInputRadioBGColor.checked = "true"; nTpl = 1; } this.elPanelQETemplatePreview.className = "se2_t_style" + nTpl; this.elPanelBGImg.style.position = ""; }else if(this.nQEMode == 1){ //review this.elPanelTableTemplateArea.style.display = "none"; // this.elSelectBoxTemplate.style.display = "none"; this.elPanelReviewBGArea.style.display = "block"; // this.elSelectBoxTemplate.style.position = "static"; // this.elPanelReviewBtnArea.style.display = "block"; //My리뷰 버튼 레이어 var nTpl = this.parseIntOr0(this.elSelectionStartTable.getAttribute(this.ATTR_REVIEW_TEMPLATE)); this.elPanelBGImg.style.position = "relative"; }else{ this.elPanelTableTemplateArea.style.display = "none"; this.elPanelReviewBGArea.style.display = "none"; // this.elPanelReviewBtnArea.style.display = "none"; //My리뷰 버튼 레이어 } this.oApp.exec("DRAW_QE_RADIO_OPTION", [0]); }, // nClickedIdx // 0: none // 2: bg color // 3: bg img // 4: template $ON_DRAW_QE_RADIO_OPTION : function(nClickedIdx){ if(nClickedIdx !== 0 && nClickedIdx != 2){ this.oApp.exec("HIDE_TABLE_QE_BGC_PALETTE", []); } if(nClickedIdx !== 0 && nClickedIdx != 3){ this.oApp.exec("HIDE_TABLE_QE_IMG_PALETTE", []); } if(nClickedIdx !== 0 && nClickedIdx != 4){ this.oApp.exec("TABLE_QE_HIDE_TEMPLATE", []); } if(this.nQEMode === 0){ // bg image option does not exist in table mode. so select the bgcolor option if(this.elInputRadioBGImg.checked){ this.elInputRadioBGColor.checked = "true"; } if(this.elInputRadioBGColor.checked){ // one dimming layer is being shared so only need to dim once and the rest will be undimmed automatically //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, true]); this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_TABLE_TEMPLATE, false]); }else{ this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, false]); //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_TABLE_TEMPLATE, true]); } }else{ // template option does not exist in review mode. so select the bgcolor optio if(this.elInputRadioTemplate.checked){ this.elInputRadioBGColor.checked = "true"; } if(this.elInputRadioBGColor.checked){ //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, true]); this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_REVIEW_BG_IMG, false]); }else{ this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, false]); //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_REVIEW_BG_IMG, true]); } } }, // nPart // 1: Merge cell btn // 2: Cell bg color // 3: Review - bg image // 4: Table - Template // // bUndim // true: Undim // false(default): Dim $ON_TABLE_QE_DIM : function(nPart, bUndim){ var elPanelDim; var sDimClassPrefix = "se2_qdim"; if(nPart == 1){ elPanelDim = this.elPanelDim1; }else{ elPanelDim = this.elPanelDim2; } if(bUndim){ nPart = 0; } elPanelDim.className = sDimClassPrefix + nPart; }, $ON_TE_SELECT_TABLE : function(elTable){ this.elSelectionStartTable = elTable; this.htMap = this._getCellMapping(this.elSelectionStartTable); }, $ON_TE_SELECT_CELLS : function(htSPos, htEPos){ this._selectCells(htSPos, htEPos); }, $ON_TE_MERGE_CELLS : function(){ if(this.aSelectedCells.length === 0 || this.aSelectedCells.length == 1){ return; } this._removeClassFromSelection(); var i, elFirstTD, elTD; elFirstTD = this.aSelectedCells[0]; var elTable = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", elFirstTD); var nHeight, nWidth; var elCurTD, elLastTD = this.aSelectedCells[0]; nHeight = parseInt(elLastTD.style.height || elLastTD.getAttribute("height"), 10); nWidth = parseInt(elLastTD.style.width || elLastTD.getAttribute("width"), 10); //nHeight = elLastTD.offsetHeight; //nWidth = elLastTD.offsetWidth; for(i = this.htSelectionSPos.x + 1; i < this.htSelectionEPos.x + 1; i++){ curTD = this.htMap[i][this.htSelectionSPos.y]; if(curTD == elLastTD){ continue; } elLastTD = curTD; nWidth += parseInt(curTD.style.width || curTD.getAttribute("width"), 10); //nWidth += curTD.offsetWidth; } elLastTD = this.aSelectedCells[0]; for(i = this.htSelectionSPos.y + 1; i < this.htSelectionEPos.y + 1; i++){ curTD = this.htMap[this.htSelectionSPos.x][i]; if(curTD == elLastTD){ continue; } elLastTD = curTD; nHeight += parseInt(curTD.style.height || curTD.getAttribute("height"), 10); //nHeight += curTD.offsetHeight; } if(nWidth){ elFirstTD.style.width = nWidth + "px"; } if(nHeight){ elFirstTD.style.height = nHeight + "px"; } elFirstTD.setAttribute("colSpan", this.htSelectionEPos.x - this.htSelectionSPos.x + 1); elFirstTD.setAttribute("rowSpan", this.htSelectionEPos.y - this.htSelectionSPos.y + 1); for(i = 1; i < this.aSelectedCells.length; i++){ elTD = this.aSelectedCells[i]; if(elTD.parentNode){ if(!nhn.husky.SE2M_Utils.isBlankNode(elTD)){ elFirstTD.innerHTML += elTD.innerHTML; } elTD.parentNode.removeChild(elTD); } } // this._updateSelection(); this.htMap = this._getCellMapping(this.elSelectionStartTable); this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this._showTableTemplate(this.elSelectionStartTable); this._addClassToSelection(); this.sQEAction = "TABLE_CELL_MERGE"; this.oApp.exec("SHOW_COMMON_QE"); }, $ON_TABLE_QE_TOGGLE_TEMPLATE : function(){ if(this.elPanelQETemplate.style.display == "block"){ this.oApp.exec("TABLE_QE_HIDE_TEMPLATE"); }else{ this.oApp.exec("TABLE_QE_SHOW_TEMPLATE"); } }, $ON_TABLE_QE_SHOW_TEMPLATE : function(){ this.elPanelQETemplate.style.display = "block"; this.oApp.exec("POSITION_TOOLBAR_LAYER", [this.elPanelQETemplate]); }, $ON_TABLE_QE_HIDE_TEMPLATE : function(){ this.elPanelQETemplate.style.display = "none"; }, $ON_STYLE_TABLE : function(elTable, nTableStyleIdx){ if(!elTable){ if(!this._t){ this._t = 1; } elTable = this.elSelectionStartTable; nTableStyleIdx = (this._t++) % 20 + 1; } if(this.oSelection){ this.oSelection.select(); } this._applyTableTemplate(elTable, nTableStyleIdx); }, $ON_TE_DELETE_COLUMN : function(){ if(this.aSelectedCells.length === 0 || this.aSelectedCells.length == 1) { return; } this._selectAll_Column(); this._deleteSelectedCells(); this.sQEAction = "DELETE_TABLE_COLUMN"; this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TE_DELETE_ROW : function(){ if(this.aSelectedCells.length === 0 || this.aSelectedCells.length == 1) { return; } this._selectAll_Row(); this._deleteSelectedCells(); this.sQEAction = "DELETE_TABLE_ROW"; this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TE_INSERT_COLUMN_RIGHT : function(){ if(this.aSelectedCells.length === 0) { return; } this._selectAll_Column(); this._insertColumnAfter(this.htSelectionEPos.x); }, $ON_TE_INSERT_COLUMN_LEFT : function(){ this._selectAll_Column(); this._insertColumnAfter(this.htSelectionSPos.x - 1); }, $ON_TE_INSERT_ROW_BELOW : function(){ if(this.aSelectedCells.length === 0) { return; } this._insertRowBelow(this.htSelectionEPos.y); }, $ON_TE_INSERT_ROW_ABOVE : function(){ this._insertRowBelow(this.htSelectionSPos.y - 1); }, $ON_TE_SPLIT_COLUMN : function(){ var nSpan, nNewSpan, nWidth, nNewWidth; var elCurCell, elNewTD; if(this.aSelectedCells.length === 0) { return; } this._removeClassFromSelection(); var elLastCell = this.aSelectedCells[0]; // Assign colSpan>1 to all selected cells. // If current colSpan == 1 then increase the colSpan of the cell and all the vertically adjacent cells. for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; if(nSpan > 1){ continue; } var htPos = this._getBasisCellPosition(elCurCell); for(var y = 0; y < this.htMap[0].length;){ elCurCell = this.htMap[htPos.x][y]; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; elCurCell.setAttribute("colSpan", nSpan+1); y += parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; } } for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; nNewSpan = (nSpan/2).toFixed(0); elCurCell.setAttribute("colSpan", nNewSpan); elNewTD = this._shallowCloneTD(elCurCell); elNewTD.setAttribute("colSpan", nSpan-nNewSpan); elLastCell = elNewTD; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; elNewTD.setAttribute("rowSpan", nSpan); elNewTD.innerHTML = "&nbsp;"; nWidth = elCurCell.width || elCurCell.style.width; if(nWidth){ nWidth = this.parseIntOr0(nWidth); elCurCell.removeAttribute("width"); nNewWidth = (nWidth/2).toFixed(); elCurCell.style.width = nNewWidth + "px"; elNewTD.style.width = (nWidth - nNewWidth) + "px"; } elCurCell.parentNode.insertBefore(elNewTD, elCurCell.nextSibling); } this._reassignCellSizes(this.elSelectionStartTable); this.htMap = this._getCellMapping(this.elSelectionStartTable); var htPos = this._getBasisCellPosition(elLastCell); this.htSelectionEPos.x = htPos.x; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this.sQEAction = "SPLIT_TABLE_COLUMN"; this.oApp.exec("SHOW_COMMON_QE"); }, $ON_TE_SPLIT_ROW : function(){ var nSpan, nNewSpan, nHeight, nHeight; var elCurCell, elNewTD, htPos, elNewTR; if(this.aSelectedCells.length === 0) { return; } var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); this._removeClassFromSelection(); //top.document.title = this.htSelectionSPos.x+","+this.htSelectionSPos.y+"::"+this.htSelectionEPos.x+","+this.htSelectionEPos.y; var nNewRows = 0; // Assign rowSpan>1 to all selected cells. // If current rowSpan == 1 then increase the rowSpan of the cell and all the horizontally adjacent cells. var elNextTRInsertionPoint; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; if(nSpan > 1){ continue; } htPos = this._getBasisCellPosition(elCurCell); elNextTRInsertionPoint = aTR[htPos.y]; // a new TR has to be inserted when there's an increase in rowSpan elNewTR = this.oApp.getWYSIWYGDocument().createElement("TR"); elNextTRInsertionPoint.parentNode.insertBefore(elNewTR, elNextTRInsertionPoint.nextSibling); nNewRows++; // loop through horizontally adjacent cells and increase their rowSpan for(var x = 0; x < this.htMap.length;){ elCurCell = this.htMap[x][htPos.y]; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; elCurCell.setAttribute("rowSpan", nSpan + 1); x += parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; } } aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var htPos1, htPos2; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; nNewSpan = (nSpan/2).toFixed(0); elCurCell.setAttribute("rowSpan", nNewSpan); elNewTD = this._shallowCloneTD(elCurCell); elNewTD.setAttribute("rowSpan", nSpan - nNewSpan); nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; elNewTD.setAttribute("colSpan", nSpan); elNewTD.innerHTML = "&nbsp;"; nHeight = elCurCell.height || elCurCell.style.height; if(nHeight){ nHeight = this.parseIntOr0(nHeight); elCurCell.removeAttribute("height"); nNewHeight = (nHeight/2).toFixed(); elCurCell.style.height = nNewHeight + "px"; elNewTD.style.height = (nHeight - nNewHeight) + "px"; } //var elTRInsertTo = elCurCell.parentNode; //for(var ii=0; ii<nNewSpan; ii++) elTRInsertTo = elTRInsertTo.nextSibling; var nTRIdx = jindo.$A(aTR).indexOf(elCurCell.parentNode); var nNextTRIdx = parseInt(nTRIdx, 10)+parseInt(nNewSpan, 10); var elTRInsertTo = aTR[nNextTRIdx]; var oSiblingTDs = elTRInsertTo.childNodes; var elInsertionPt = null; var tmp; htPos1 = this._getBasisCellPosition(elCurCell); for(var ii = 0, nNumTDs = oSiblingTDs.length; ii < nNumTDs; ii++){ tmp = oSiblingTDs[ii]; if(!tmp.tagName || tmp.tagName != "TD"){ continue; } htPos2 = this._getBasisCellPosition(tmp); if(htPos1.x < htPos2.x){ elInsertionPt = tmp; break; } } elTRInsertTo.insertBefore(elNewTD, elInsertionPt); } this._reassignCellSizes(this.elSelectionStartTable); this.htMap = this._getCellMapping(this.elSelectionStartTable); this.htSelectionEPos.y += nNewRows; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this.sQEAction = "SPLIT_TABLE_ROW"; this.oApp.exec("SHOW_COMMON_QE"); }, $ON_MSG_CELL_SELECTED : function(){ // disable row/col delete btn this.elPanelDimDelCol.className = "se2_qdim6r"; this.elPanelDimDelRow.className = "se2_qdim6c"; if(this.htSelectionSPos.x === 0 && this.htSelectionEPos.x === this.htMap.length - 1){ this.oApp.exec("MSG_ROW_SELECTED"); } if(this.htSelectionSPos.y === 0 && this.htSelectionEPos.y === this.htMap[0].length - 1){ this.oApp.exec("MSG_COL_SELECTED"); } this.oApp.exec("SHOW_COMMON_QE"); }, $ON_MSG_ROW_SELECTED : function(){ this.elPanelDimDelRow.className = ""; }, $ON_MSG_COL_SELECTED : function(){ this.elPanelDimDelCol.className = ""; }, $ON_EVENT_EDITING_AREA_MOUSEDOWN : function(wevE){ if(!this.oApp.isWYSIWYGEnabled()){ return; } switch(this.nStatus){ case this.STATUS.S_0: // the user may just want to resize the image if(!wevE.element){return;} if(wevE.element.tagName == "IMG"){return;} if(this.oApp.getEditingMode() !== "WYSIWYG"){return;} // change the status to MOUSEDOWN_CELL if the mouse is over a table cell var elTD = nhn.husky.SE2M_Utils.findAncestorByTagName("TD", wevE.element); if(elTD && elTD.tagName == "TD"){ var elTBL = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", elTD); if(!jindo.$Element(elTBL).hasClass(this._sSETblClass) && !jindo.$Element(elTBL).hasClass(this._sSEReviewTblClass)){return;} if(!this._isValidTable(elTBL)){ jindo.$Element(elTBL).removeClass(this._sSETblClass); jindo.$Element(elTBL).removeClass(this._sSEReviewTblClass); return; } if(elTBL){ this.elSelectionStartTD = elTD; this.elSelectionStartTable = elTBL; this._changeTableEditorStatus(this.STATUS.MOUSEDOWN_CELL); } } break; case this.STATUS.MOUSEDOWN_CELL: break; case this.STATUS.CELL_SELECTING: break; case this.STATUS.CELL_SELECTED: this._changeTableEditorStatus(this.STATUS.S_0); break; } }, $ON_EVENT_EDITING_AREA_MOUSEMOVE : function(wevE){ if(this.oApp.getEditingMode() != "WYSIWYG"){return;} switch(this.nStatus){ case this.STATUS.S_0: // if(this._isOnBorder(wevE)){ //this._changeTableEditorStatus(this.MOUSEOVER_BORDER); this._showCellResizeGrip(wevE); }else{ this._hideResizer(); } break; case this.STATUS.MOUSEDOWN_CELL: // change the status to CELL_SELECTING if the mouse moved out of the inital TD var elTD = nhn.husky.SE2M_Utils.findAncestorByTagName("TD", wevE.element); if((elTD && elTD !== this.elSelectionStartTD) || !elTD){ if(!elTD){elTD = this.elSelectionStartTD;} this._reassignCellSizes(this.elSelectionStartTable); this._startCellSelection(); this._selectBetweenCells(this.elSelectionStartTD, elTD); } break; case this.STATUS.CELL_SELECTING: // show selection var elTD = nhn.husky.SE2M_Utils.findAncestorByTagName("TD", wevE.element); if(!elTD || elTD === this.elLastSelectedTD){return;} var elTBL = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", elTD); if(elTBL !== this.elSelectionStartTable){return;} this.elLastSelectedTD = elTD; this._selectBetweenCells(this.elSelectionStartTD, elTD); break; case this.STATUS.CELL_SELECTED: break; } }, // 셀 선택 상태에서 문서영역을 상/하로 벗어날 경우, 벗어난 방향으로 선택 셀을 늘려가며 문서의 스크롤을 해줌 $ON_EVENT_OUTER_DOC_MOUSEMOVE : function(wevE){ switch(this.nStatus){ case this.STATUS.CELL_SELECTING: var htPos = wevE.pos(); var nYPos = htPos.pageY; var nXPos = htPos.pageX; if(nYPos < this.htEditingAreaPos.top){ var y = this.htSelectionSPos.y; if(y > 0){ this.htSelectionSPos.y--; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.aSelectedCells[0]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } }else{ if(nYPos > this.htEditingAreaPos.bottom){ var y = this.htSelectionEPos.y; if(y < this.htMap[0].length - 1){ this.htSelectionEPos.y++; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } } } if(nXPos < this.htEditingAreaPos.left){ var x = this.htSelectionSPos.x; if(x > 0){ this.htSelectionSPos.x--; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.aSelectedCells[0]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } }else{ if(nXPos > this.htEditingAreaPos.right){ var x = this.htSelectionEPos.x; if(x < this.htMap.length - 1){ this.htSelectionEPos.x++; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } } } break; } }, $ON_EVENT_OUTER_DOC_MOUSEUP : function(wevE){ this._eventEditingAreaMouseup(wevE); }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(wevE){ this._eventEditingAreaMouseup(wevE); }, _eventEditingAreaMouseup : function(wevE){ if(this.oApp.getEditingMode() != "WYSIWYG"){return;} switch(this.nStatus){ case this.STATUS.S_0: break; case this.STATUS.MOUSEDOWN_CELL: this._changeTableEditorStatus(this.STATUS.S_0); break; case this.STATUS.CELL_SELECTING: this._changeTableEditorStatus(this.STATUS.CELL_SELECTED); break; case this.STATUS.CELL_SELECTED: break; } }, /** * Table의 block으로 잡힌 영역을 넘겨준다. * @see hp_SE2M_TableBlockStyler.js */ $ON_GET_SELECTED_CELLS : function(sAttr,oReturn){ if(!!this.aSelectedCells){ oReturn[sAttr] = this.aSelectedCells; } }, _coverResizeLayer : function(){ // [SMARTEDITORSUS-1504] 에디터 전체 크기보다 창이 작아졌을 때 elResizeGrid가 최대화된 elResizeCover으로부터 벗어나는 이슈가 있음 //this.elResizeCover.style.position = "absolute"; this.elResizeCover.style.position = "fixed"; // --[SMARTEDITORSUS-1504] var size = jindo.$Document().clientSize(); this.elResizeCover.style.width = size.width - this.nPageLeftRightMargin + "px"; this.elResizeCover.style.height = size.height - this.nPageTopBottomMargin + "px"; //this.elResizeCover.style.width = size.width + "px"; //this.elResizeCover.style.height = size.height + "px"; //document.body.insertBefore(this.elResizeCover, document.body.firstChild); document.body.appendChild(this.elResizeCover); }, _uncoverResizeLayer : function(){ this.elResizeGrid.appendChild(this.elResizeCover); this.elResizeCover.style.position = ""; this.elResizeCover.style.width = "100%"; this.elResizeCover.style.height = "100%"; }, _reassignCellSizes : function(elTable){ var allCells = new Array(2); allCells[0] = jindo.$$(">TBODY>TR>TD", elTable, {oneTimeOffCache:true}); allCells[1] = jindo.$$(">TBODY>TR>TH", elTable, {oneTimeOffCache:true}); var aAllCellsWithSizeInfo = new Array(allCells[0].length + allCells[1].length); var numCells = 0; var nTblBorderPadding = this.parseIntOr0(elTable.border); var nTblCellPadding = this.parseIntOr0(elTable.cellPadding); // remember all the dimensions first and then assign later. // this is done this way because if the table/cell size were set in %, setting one cell size would change size of other cells, which are still yet in %. // 1 for TD and 1 for TH for(var n = 0; n < 2; n++){ for(var i = 0; i < allCells[n].length; i++){ var elCell = allCells[n][i]; var welCell = jindo.$Element(elCell); var htBrowser = jindo.$Agent().navigator(); // [SMARTEDITORSUS-1427][SMARTEDITORSUS-1431][SMARTEDITORSUS-1491][SMARTEDITORSUS-1504] IE9, 10에서 Jindo.$Element#css 가 빈 속성값을 1px로 가져오는 문제점이 있어 대체 /*var nPaddingLeft = this.parseIntOr0(welCell.css("paddingLeft")); var nPaddingRight = this.parseIntOr0(welCell.css("paddingRight")); var nPaddingTop = this.parseIntOr0(welCell.css("paddingTop")); var nPaddingBottom = this.parseIntOr0(welCell.css("paddingBottom")); var nBorderLeft = this.parseBorder(welCell.css("borderLeftWidth"), welCell.css("borderLeftStyle")); var nBorderRight = this.parseBorder(welCell.css("borderRightWidth"), welCell.css("borderRightStyle")); var nBorderTop = this.parseBorder(welCell.css("borderTopWidth"), welCell.css("borderTopStyle")); var nBorderBottom = this.parseBorder(welCell.css("borderBottomWidth"), welCell.css("borderBottomStyle"));*/ var nPaddingLeft, nPaddingRight, nPaddingTop, nPaddingBottom; var nBorderLeft, nBorderRight, nBorderTop, nBorderBottom; // --[SMARTEDITORSUS-1427][SMARTEDITORSUS-1431][SMARTEDITORSUS-1491][SMARTEDITORSUS-1504] var nOffsetWidth, nOffsetHeight; // [SMARTEDITORSUS-1571] IE 10 이상임에도 불구하고, 문서 모드가 8 이하로 설정되어 있는 경우가 있어 메서드 기반 분기로 변경 if(elCell.getComputedStyle){ // --[SMARTEDITORSUS-1571] // getComputedStyle()로 inherit된 스타일을 획득. IE 8 이하에서는 지원되지 않는다. nPaddingLeft = parseFloat(getComputedStyle(elCell).paddingLeft, 10); nPaddingRight = parseFloat(getComputedStyle(elCell).paddingRight, 10); nPaddingTop = parseFloat(getComputedStyle(elCell).paddingTop, 10); nPaddingBottom = parseFloat(getComputedStyle(elCell).paddingBottom, 10); // 최초 리사이징 직전 width attribute에서 style의 width로 이행하는 과정에서 미세보정이 있기 때문에 크기가 조금 변한다. nBorderLeft = parseFloat(getComputedStyle(elCell).borderLeftWidth, 10); nBorderRight = parseFloat(getComputedStyle(elCell).borderRightWidth, 10); nBorderTop = parseFloat(getComputedStyle(elCell).borderTopWidth, 10); nBorderBottom = parseFloat(getComputedStyle(elCell).borderBottomWidth, 10); }else{ // 이 방식은 inherit된 스타일을 가져오지 못하는 문제와 함께, 일부 브라우저의 소수점 값을 버림하는 문제가 있다. // [SMARTEDITORSUS-1427][SMARTEDITORSUS-1431][SMARTEDITORSUS-1491] nPaddingLeft = this.parseIntOr0(elCell.style.paddingLeft); nPaddingRight = this.parseIntOr0(elCell.style.paddingRight); nPaddingTop = this.parseIntOr0(elCell.style.paddingTop); nPaddingBottom = this.parseIntOr0(elCell.style.paddingBottom); // --[SMARTEDITORSUS-1427][SMARTEDITORSUS-1431][SMARTEDITORSUS-1491] // 기존 로직을 사용. IE의 경우 bug로 분류하여 1px를 획득하도록 설정되어 있다. nBorderLeft = this.parseBorder(welCell.css("borderLeftWidth"), welCell.css("borderLeftStyle")); nBorderRight = this.parseBorder(welCell.css("borderRightWidth"), welCell.css("borderRightStyle")); nBorderTop = this.parseBorder(welCell.css("borderTopWidth"), welCell.css("borderTopStyle")); nBorderBottom = this.parseBorder(welCell.css("borderBottomWidth"), welCell.css("borderBottomStyle")); } /** * 매번 발생하는 리사이징 오차를 최소하기 위하여, 2회차부터는 1회차에 적용되는 style 값을 가져온다. * * width와 height attribute는 최초 1회에 제거된다. * 즉 2회차부터는, 동적으로 변하는 style의 width, height 값을 그대로 사용한다. * */ /*nOffsetWidth = elCell.offsetWidth - (nPaddingLeft + nPaddingRight + nBorderLeft + nBorderRight) + "px"; nOffsetHeight = elCell.offsetHeight - (nPaddingTop + nPaddingBottom + nBorderTop + nBorderBottom) + "px";*/ var nWidth = jindo.$Element(elCell).attr("width"); var nHeight = jindo.$Element(elCell).attr("height"); if(!nWidth && !nHeight){ nOffsetWidth = elCell.style.width; nOffsetHeight = elCell.style.height; }else{ nOffsetWidth = elCell.offsetWidth - (nPaddingLeft + nPaddingRight + nBorderLeft + nBorderRight) + "px"; nOffsetHeight = elCell.offsetHeight - (nPaddingTop + nPaddingBottom + nBorderTop + nBorderBottom) + "px"; } /*if(htBrowser.ie && (htBrowser.nativeVersion >= 9 && htBrowser.nativeVersion <= 10)){ // IE9, IE10 // [SMARTEDITORSUS-1427][SMARTEDITORSUS-1431][SMARTEDITORSUS-1491] IE9, 10에서 Jindo.$Element#css 관련 문제에 대응하면 다른 브라우저와 동일한 수식 적용 가능 //nOffsetWidth = elCell.offsetWidth + "px"; //nOffsetHeight = elCell.offsetHeight - (nPaddingTop + nPaddingBottom + nBorderTop + nBorderBottom) + "px"; nOffsetWidth = elCell.offsetWidth - (nPaddingLeft + nPaddingRight + nBorderLeft + nBorderRight) + "px"; nOffsetHeight = elCell.offsetHeight - (nPaddingTop + nPaddingBottom + nBorderTop + nBorderBottom) + "px"; // --[SMARTEDITORSUS-1427][SMARTEDITORSUS-1431][SMARTEDITORSUS-1491] }else{ // Firefox, Chrome, IE7, IE8 nOffsetWidth = elCell.offsetWidth - (nPaddingLeft + nPaddingRight + nBorderLeft + nBorderRight) + "px"; nOffsetHeight = elCell.offsetHeight - (nPaddingTop + nPaddingBottom + nBorderTop + nBorderBottom) + "px"; }*/ // --[SMARTEDITORSUS-1504] aAllCellsWithSizeInfo[numCells++] = [elCell, nOffsetWidth, nOffsetHeight]; } } for(var i = 0; i < numCells; i++){ var aCellInfo = aAllCellsWithSizeInfo[i]; aCellInfo[0].removeAttribute("width"); aCellInfo[0].removeAttribute("height"); aCellInfo[0].style.width = aCellInfo[1]; aCellInfo[0].style.height = aCellInfo[2]; // jindo.$Element(aCellInfo[0]).css("width", aCellInfo[1]); // jindo.$Element(aCellInfo[0]).css("height", aCellInfo[2]); } elTable.removeAttribute("width"); elTable.removeAttribute("height"); elTable.style.width = ""; elTable.style.height = ""; }, _mousedown_ResizeCover : function(oEvent){ this.bResizing = true; this.nStartHeight = oEvent.pos().clientY; // [SMARTEDITORSUS-1504] 표 테두리를 누를 때마다 글양식이 2px씩 세로로 길어지는 문제가 있는데, 이를 위한 flag this.bResizingCover = true; // --[SMARTEDITORSUS-1504] this.wfnMousemove_ResizeCover.attach(this.elResizeCover, "mousemove"); this.wfnMouseup_ResizeCover.attach(document, "mouseup"); this._coverResizeLayer(); this.elResizeGrid.style.border = "1px dotted black"; this.nStartHeight = oEvent.pos().clientY; this.nStartWidth = oEvent.pos().clientX; // [SMARTEDITORSUS-1504] 표 리사이즈용 gripper의 배치를 WYSIWYG 편집 영역 위치 기반으로 개선 this.nClientXDiff = this.nStartWidth - this.htResizing.htEPos.clientX; this.nClientYDiff = this.nStartHeight - this.htResizing.htEPos.clientY; // --[SMARTEDITORSUS-1504] this._reassignCellSizes(this.htResizing.elTable); this.htMap = this._getCellMapping(this.htResizing.elTable); var htPosition = this._getBasisCellPosition(this.htResizing.elCell); var nOffsetX = (parseInt(this.htResizing.elCell.getAttribute("colspan")) || 1) - 1; var nOffsetY = (parseInt(this.htResizing.elCell.getAttribute("rowspan")) || 1) - 1; var x = htPosition.x + nOffsetX + this.htResizing.nHA; var y = htPosition.y + nOffsetY + this.htResizing.nVA; if(x < 0 || y < 0){return;} this.htAllAffectedCells = this._getAllAffectedCells(x, y, this.htResizing.nResizeMode, this.htResizing.elTable); }, _mousemove_ResizeCover : function(oEvent){ // [SMARTEDITORSUS-1504] 표 모서리 Drag 사용성 개선 // - 최초 리사이징 후 해당 위치에서 바로 마우스를 눌러 Drag 가능 if(jindo.$Agent().navigator().chrome || jindo.$Agent().navigator().safari){ if(this.htResizing.nPreviousResizeMode != undefined && this.htResizing.nPreviousResizeMode != 0){ if(this.htResizing.nResizeMode != this.htResizing.nPreviousResizeMode){ this.htResizing.nResizeMode = this.htResizing.nPreviousResizeMode; this._showResizer(); } } } // --[SMARTEDITORSUS-1504] var nHeightChange = oEvent.pos().clientY - this.nStartHeight; var nWidthChange = oEvent.pos().clientX - this.nStartWidth; var oEventPos = oEvent.pos(); // [SMARTEDITORSUS-1504] 표 리사이즈용 gripper의 배치를 WYSIWYG 편집 영역 위치 기반으로 개선 /*if(this.htResizing.nResizeMode == 1){ this.elResizeGrid.style.left = oEventPos.pageX - this.parseIntOr0(this.elResizeGrid.style.width)/2 + "px"; }else{ this.elResizeGrid.style.top = oEventPos.pageY - this.parseIntOr0(this.elResizeGrid.style.height)/2 + "px"; }*/ if(this.htResizing.nResizeMode == 1){ this.elResizeGrid.style.left = oEvent.pos().clientX - this.nClientXDiff - this.parseIntOr0(this.elResizeGrid.style.width)/2 + "px"; }else{ this.elResizeGrid.style.top = oEvent.pos().clientY - this.nClientYDiff - this.parseIntOr0(this.elResizeGrid.style.height)/2 + "px"; } // --[SMARTEDITORSUS-1504] }, _mouseup_ResizeCover : function(oEvent){ this.bResizing = false; this._hideResizer(); this._uncoverResizeLayer(); this.elResizeGrid.style.border = ""; this.wfnMousemove_ResizeCover.detach(this.elResizeCover, "mousemove"); this.wfnMouseup_ResizeCover.detach(document, "mouseup"); var nHeightChange = 0; var nWidthChange = 0; if(this.htResizing.nResizeMode == 2){ nHeightChange = oEvent.pos().clientY - this.nStartHeight; } if(this.htResizing.nResizeMode == 1){ nWidthChange = oEvent.pos().clientX - this.nStartWidth; if(this.htAllAffectedCells.nMinBefore != -1 && nWidthChange < -1*this.htAllAffectedCells.nMinBefore){ nWidthChange = -1 * this.htAllAffectedCells.nMinBefore + this.MIN_CELL_WIDTH; } if(this.htAllAffectedCells.nMinAfter != -1 && nWidthChange > this.htAllAffectedCells.nMinAfter){ nWidthChange = this.htAllAffectedCells.nMinAfter - this.MIN_CELL_WIDTH; } } // [SMARTEDITORSUS-1504] FireFox는 소수점으로 size가 나오는데, parseInt는 소수점 이하를 버림 // [SMARTEDITORSUS-1655] 메서드, 프로퍼티 기반 리팩토링 var width, height; // --[SMARTEDITORSUS-1655] var aCellsBefore = this.htAllAffectedCells.aCellsBefore; for(var i = 0; i < aCellsBefore.length; i++){ var elCell = aCellsBefore[i]; // [SMARTEDITORSUS-1655] width = 0, height = 0; width = elCell.style.width; if(isNaN(parseFloat(width, 10))){ // 값이 없거나 "auto"인 경우 width = 0; }else{ width = parseFloat(width, 10); } width += nWidthChange; height = elCell.style.height; if(isNaN(parseFloat(height, 10))){ // 값이 없거나 "auto"인 경우 height = 0; }else{ height = parseFloat(height, 10); } height += nHeightChange; // --[SMARTEDITORSUS-1655] //var width = this.parseIntOr0(elCell.style.width) + nWidthChange; elCell.style.width = Math.max(width, this.MIN_CELL_WIDTH) + "px"; //var height = this.parseIntOr0(elCell.style.height) + nHeightChange; elCell.style.height = Math.max(height, this.MIN_CELL_HEIGHT) + "px"; } var aCellsAfter = this.htAllAffectedCells.aCellsAfter; for(var i = 0; i < aCellsAfter.length; i++){ var elCell = aCellsAfter[i]; // [SMARTEDITORSUS-1655] width = 0, height = 0; width = elCell.style.width; if(isNaN(parseFloat(width, 10))){ // 값이 없거나 "auto"인 경우 width = 0; }else{ width = parseFloat(width, 10); } width -= nWidthChange; height = elCell.style.height; if(isNaN(parseFloat(height, 10))){ // 값이 없거나 "auto"인 경우 height = 0; }else{ height = parseFloat(height, 10); } height -= nHeightChange; // --[SMARTEDITORSUS-1655] //var width = this.parseIntOr0(elCell.style.width) - nWidthChange; elCell.style.width = Math.max(width, this.MIN_CELL_WIDTH) + "px"; //var height = this.parseIntOr0(elCell.style.height) - nHeightChange; elCell.style.height = Math.max(height, this.MIN_CELL_HEIGHT) + "px"; } // --[SMARTEDITORSUS-1504] // [SMARTEDITORSUS-1504] 표 테두리를 누를 때마다 글양식이 2px씩 세로로 길어지는 문제가 있는데, 이를 위한 flag this.bResizingCover = false; // --[SMARTEDITORSUS-1504] }, $ON_CLOSE_QE_LAYER : function(){ this._changeTableEditorStatus(this.STATUS.S_0); }, _changeTableEditorStatus : function(nNewStatus){ if(this.nStatus == nNewStatus){return;} this.nStatus = nNewStatus; switch(nNewStatus){ case this.STATUS.S_0: if(this.nStatus == this.STATUS.MOUSEDOWN_CELL){ break; } this._deselectCells(); // 히스토리 저장 (선택 위치는 저장하지 않음) if(!!this.sQEAction){ this.oApp.exec("RECORD_UNDO_ACTION", [this.sQEAction, {elSaveTarget:this.elSelectionStartTable, bDontSaveSelection:true}]); this.sQEAction = ""; } if(this.oApp.oNavigator["safari"] || this.oApp.oNavigator["chrome"]){ this.oApp.getWYSIWYGDocument().onselectstart = null; } this.oApp.exec("ENABLE_WYSIWYG", []); this.oApp.exec("CLOSE_QE_LAYER"); this.elSelectionStartTable = null; break; case this.STATUS.CELL_SELECTING: if(this.oApp.oNavigator.ie){ document.body.setCapture(false); } break; case this.STATUS.CELL_SELECTED: this.oApp.delayedExec("MSG_CELL_SELECTED", [], 0); if(this.oApp.oNavigator.ie){ document.body.releaseCapture(); } break; } this.oApp.exec("TABLE_EDITOR_STATUS_CHANGED", [this.nStatus]); }, _isOnBorder : function(wevE){ // ===========================[Start: Set/init global resizing info]=========================== // 0: not resizing // 1: horizontal resizing // 2: vertical resizing this.htResizing.nResizeMode = 0; this.htResizing.elCell = wevE.element; if(wevE.element.tagName != "TD" && wevE.element.tagName != "TH"){return false;} this.htResizing.elTable = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", this.htResizing.elCell); if(!this.htResizing.elTable){return;} if(!jindo.$Element(this.htResizing.elTable).hasClass(this._sSETblClass) && !jindo.$Element(this.htResizing.elTable).hasClass(this._sSEReviewTblClass)){return;} // Adjustment variables: to be used to map the x, y position of the resizing point relative to elCell // eg) When left border of a cell at 2,2 is selected, the actual cell that has to be resized is the one at 1,2. So, set the horizontal adjustment to -1. // Vertical Adjustment this.htResizing.nVA = 0; // Horizontal Adjustment this.htResizing.nHA = 0; this.htResizing.nBorderLeftPos = 0; this.htResizing.nBorderTopPos = -1; this.htResizing.htEPos = wevE.pos(true); this.htResizing.nBorderSize = this.parseIntOr0(this.htResizing.elTable.border); // ===========================[E N D: Set/init global resizing info]=========================== // Separate info is required as the offsetX/Y are different in IE and FF // For IE, (0, 0) is top left corner of the cell including the border. // For FF, (0, 0) is top left corner of the cell excluding the border. var nAdjustedDraggableCellEdge1; var nAdjustedDraggableCellEdge2; if(jindo.$Agent().navigator().ie || jindo.$Agent().navigator().safari){ nAdjustedDraggableCellEdge1 = this.htResizing.nBorderSize + this.nDraggableCellEdge; nAdjustedDraggableCellEdge2 = this.nDraggableCellEdge; }else{ nAdjustedDraggableCellEdge1 = this.nDraggableCellEdge; nAdjustedDraggableCellEdge2 = this.htResizing.nBorderSize + this.nDraggableCellEdge; } // [SMARTEDITORSUS-1504] 경계선 판별에 사용 var elCellWidth = this.htResizing.elCell.clientWidth, elCellHeight = this.htResizing.elCell.clientHeight; nRightBorderCriteria = elCellWidth - this.htResizing.htEPos.offsetX, nBottomBorderCriteria = elCellHeight - this.htResizing.htEPos.offsetY; // --[SMARTEDITORSUS-1504] // top border of the cell is selected if(this.htResizing.htEPos.offsetY <= nAdjustedDraggableCellEdge1){ // top border of the first cell can't be dragged if(this.htResizing.elCell.parentNode.previousSibling){ this.htResizing.nVA = -1; // [SMARTEDITORSUS-1504] 표 리사이즈용 gripper 배치 개선 //this.htResizing.nResizeMode = 2; this.htResizing.nResizeMode = 4; // --[SMARTEDITORSUS-1504] } } // bottom border of the cell is selected // [SMARTEDITORSUS-1504] 표 모서리 Drag 사용성 개선 //if(this.htResizing.elCell.offsetHeight-nAdjustedDraggableCellEdge2 <= this.htResizing.htEPos.offsetY){ if(nBottomBorderCriteria <= nAdjustedDraggableCellEdge2){ this.htResizing.nBorderTopPos = this.htResizing.elCell.offsetHeight + nAdjustedDraggableCellEdge1 - 1; this.htResizing.nResizeMode = 2; } // --[SMARTEDITORSUS-1504] // left border of the cell is selected if(this.htResizing.htEPos.offsetX <= nAdjustedDraggableCellEdge1){ // left border of the first cell can't be dragged // [SMARTEDITORSUS-1504] 표 리사이즈용 gripper 배치 개선 // 일반 표는 아래 if문을 거치지 않지만, 글양식의 경우 가장 좌측 cell의 previousSibling이 textNode이기 때문에 if문에 부합하는 문제가 있었다. /*if(this.htResizing.elCell.previousSibling){ this.htResizing.nHA = -1; this.htResizing.nResizeMode = 0; }*/ // 가장 좌측의 cell은 그 offsetLeft가 table의 scrollLeft와 같다. if(this.htResizing.elTable.scrollLeft != this.htResizing.elCell.offsetLeft){ this.htResizing.nHA = -1; this.htResizing.nResizeMode = 3; } // --[SMARTEDITORSUS-1504] } // right border of the cell is selected // [SMARTEDITORSUS-1504] 표 모서리 Drag 사용성 개선 //if(this.htResizing.elCell.offsetWidth - nAdjustedDraggableCellEdge2 <= this.htResizing.htEPos.offsetX){ if(nRightBorderCriteria <= nAdjustedDraggableCellEdge1){ this.htResizing.nBorderLeftPos = this.htResizing.elCell.offsetWidth + nAdjustedDraggableCellEdge1 - 1; this.htResizing.nResizeMode = 1; } // --[SMARTEDITORSUS-1504] // [SMARTEDITORSUS-1504] 표 모서리 Drag 사용성 개선 if(jindo.$Agent().navigator().chrome || jindo.$Agent().navigator().safari){ if(!this.htResizing.elPreviousCell){ this.htResizing.elPreviousCell = this.htResizing.elCell; }else{ if(this.htResizing.elCell != this.htResizing.elPreviousCell){ this.htResizing.elPreviousCell = this.htResizing.elCell; } } } // --[SMARTEDITORSUS-1504] if(this.htResizing.nResizeMode === 0){return false;} return true; }, _showCellResizeGrip : function(){ // [SMARTEDITORSUS-1504] gripper가 WYSIWYG 편집영역 위치정보에 기반하여 배치되도록 변경 /*if(this.htResizing.nResizeMode == 1){ this.elResizeCover.style.cursor = "col-resize"; }else{ this.elResizeCover.style.cursor = "row-resize"; } this._showResizer();*/ // 만약 iframe 내부에 gripper를 생성한다면, 커서 위치를 기반으로 생성해 주면 됨 /*if(this.htResizing.nResizeMode == 1){ this._setResizerSize((this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2, this.parseIntOr0(jindo.$Element(this.elIFrame).css("height"))); jindo.$Element(this.elResizeGrid).offset(this.htFrameOffset.top, this.htFrameOffset.left + this.htResizing.htEPos.clientX - this.parseIntOr0(this.elResizeGrid.style.width)/2 - this.htResizing.htEPos.offsetX + this.htResizing.nBorderLeftPos); }else{ //가변폭을 지원하기 때문에 매번 현재 Container의 크기를 구해와서 Grip을 생성해야 한다. var elIFrameWidth = this.oApp.elEditingAreaContainer.offsetWidth + "px"; this._setResizerSize(this.parseIntOr0(elIFrameWidth), (this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2); jindo.$Element(this.elResizeGrid).offset(this.htFrameOffset.top + this.htResizing.htEPos.clientY - this.parseIntOr0(this.elResizeGrid.style.height)/2 - this.htResizing.htEPos.offsetY + this.htResizing.nBorderTopPos, this.htFrameOffset.left); }*/ if(this.htResizing.nResizeMode == 1 || this.htResizing.nResizeMode == 3){ this.elResizeCover.style.cursor = "col-resize"; }else if(this.htResizing.nResizeMode == 2 || this.htResizing.nResizeMode == 4){ this.elResizeCover.style.cursor = "row-resize"; } this._showResizer(); // gripper는 대상 셀에서 어느 경계 위에 커서가 위치했느냐에 기반하여 배치 if(this.htResizing.nResizeMode == 1){ // 오른쪽 경계 this._setResizerSize((this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2, this.parseIntOr0(jindo.$Element(this.elIFrame).css("height"))); this.elResizeGrid.style.top = "0px"; this.elResizeGrid.style.left = this.htResizing.elCell.clientWidth + this.htResizing.htEPos.clientX - this.htResizing.htEPos.offsetX - this.parseIntOr0(this.elResizeGrid.style.width)/2 + "px"; }else if(this.htResizing.nResizeMode == 2){ // 아래쪽 경계 //가변폭을 지원하기 때문에 매번 현재 Container의 크기를 구해와서 Grip을 생성해야 한다. var elIFrameWidth = this.oApp.elEditingAreaContainer.offsetWidth + "px"; this._setResizerSize(this.parseIntOr0(elIFrameWidth), (this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2); this.elResizeGrid.style.top = this.htResizing.elCell.clientHeight + this.htResizing.htEPos.clientY - this.htResizing.htEPos.offsetY - this.parseIntOr0(this.elResizeGrid.style.height)/2 + "px"; this.elResizeGrid.style.left = "0px"; }else if(this.htResizing.nResizeMode == 3){ // 왼쪽 경계 this._setResizerSize((this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2, this.parseIntOr0(jindo.$Element(this.elIFrame).css("height"))); this.elResizeGrid.style.top = "0px"; this.elResizeGrid.style.left = + this.htResizing.htEPos.clientX - this.htResizing.htEPos.offsetX - this.parseIntOr0(this.elResizeGrid.style.width)/2 + "px"; // 이후 작업들은 오른쪽 경계를 기준으로 일괄처리 this.htResizing.nResizeMode = 1; }else if(this.htResizing.nResizeMode == 4){ //위쪽 경계 //가변폭을 지원하기 때문에 매번 현재 Container의 크기를 구해와서 Grip을 생성해야 한다. var elIFrameWidth = this.oApp.elEditingAreaContainer.offsetWidth + "px"; this._setResizerSize(this.parseIntOr0(elIFrameWidth), (this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2); this.elResizeGrid.style.top = this.htResizing.htEPos.clientY - this.htResizing.htEPos.offsetY - this.parseIntOr0(this.elResizeGrid.style.height)/2 + "px"; this.elResizeGrid.style.left = "0px"; // 이후 작업들은 아래쪽 경계를 기준으로 일괄처리 this.htResizing.nResizeMode = 2; } // --[SMARTEDITORSUS-1504] }, _getAllAffectedCells : function(basis_x, basis_y, iResizeMode, oTable){ if(!oTable){return [];} var oTbl = this._getCellMapping(oTable); var iTblX = oTbl.length; var iTblY = oTbl[0].length; // 선택 테두리의 앞쪽 셀 var aCellsBefore = []; // 선택 테두리의 뒤쪽 셀 var aCellsAfter = []; var htResult; var nMinBefore = -1, nMinAfter = -1; // horizontal resizing -> need to get vertical rows if(iResizeMode == 1){ for(var y = 0; y < iTblY; y++){ if(aCellsBefore.length>0 && aCellsBefore[aCellsBefore.length-1] == oTbl[basis_x][y]){continue;} aCellsBefore[aCellsBefore.length] = oTbl[basis_x][y]; var nWidth = parseInt(oTbl[basis_x][y].style.width); if(nMinBefore == -1 || nMinBefore > nWidth){ nMinBefore = nWidth; } } if(oTbl.length > basis_x+1){ for(var y = 0; y < iTblY; y++){ if(aCellsAfter.length>0 && aCellsAfter[aCellsAfter.length-1] == oTbl[basis_x+1][y]){continue;} aCellsAfter[aCellsAfter.length] = oTbl[basis_x+1][y]; var nWidth = parseInt(oTbl[basis_x + 1][y].style.width); if(nMinAfter == -1 || nMinAfter > nWidth){ nMinAfter = nWidth; } } } htResult = {aCellsBefore: aCellsBefore, aCellsAfter: aCellsAfter, nMinBefore: nMinBefore, nMinAfter: nMinAfter}; }else{ for(var x = 0; x < iTblX; x++){ if(aCellsBefore.length>0 && aCellsBefore[aCellsBefore.length - 1] == oTbl[x][basis_y]){continue;} aCellsBefore[aCellsBefore.length] = oTbl[x][basis_y]; if(nMinBefore == -1 || nMinBefore > oTbl[x][basis_y].style.height){ nMinBefore = oTbl[x][basis_y].style.height; } } // 높이 리사이징 시에는 선택 테두리 앞쪽 셀만 조절 함으로 아래쪽 셀은 생성 할 필요 없음 htResult = {aCellsBefore: aCellsBefore, aCellsAfter: aCellsAfter, nMinBefore: nMinBefore, nMinAfter: nMinAfter}; } return htResult; }, _createCellResizeGrip : function(){ this.elTmp = document.createElement("DIV"); try{ this.elTmp.innerHTML = '<div style="position:absolute; overflow:hidden; z-index: 99; "><div onmousedown="return false" style="background-color:#000000;filter:alpha(opacity=0);opacity:0.0;-moz-opacity:0.0;-khtml-opacity:0.0;cursor: col-resize; left: 0px; top: 0px; width: 100%; height: 100%;font-size:1px;z-index: 999; "></div></div>'; this.elResizeGrid = this.elTmp.firstChild; this.elResizeCover = this.elResizeGrid.firstChild; }catch(e){} // [SMARTEDITORSUS-1504] gripper를 WYSIWYG 편집 영역 위치 정보에 기반하여 배치하도록 개선 //document.body.appendChild(this.elResizeGrid); // document.body 대신 WYSIWYG 편집 영역을 둘러싼 container div에 추가 var oContainer = jindo.$$.getSingle(".husky_seditor_editing_area_container"); oContainer.appendChild(this.elResizeGrid); // --[SMARTEDITORSUS-1504] }, _selectAll_Row : function(){ this.htSelectionSPos.x = 0; this.htSelectionEPos.x = this.htMap.length - 1; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); }, _selectAll_Column : function(){ this.htSelectionSPos.y = 0; this.htSelectionEPos.y = this.htMap[0].length - 1; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); }, _deleteSelectedCells : function(){ var elTmp; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elTmp = this.aSelectedCells[i]; elTmp.parentNode.removeChild(elTmp); } var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var nSelectionWidth = this.htSelectionEPos.x - this.htSelectionSPos.x + 1; var nWidth = this.htMap.length; if(nSelectionWidth == nWidth){ for(var i = 0, nLen = aTR.length; i < nLen; i++){ elTmp = aTR[i]; // There can be empty but necessary TR's because of Rowspan if(!this.htMap[0][i] || !this.htMap[0][i].parentNode || this.htMap[0][i].parentNode.tagName !== "TR"){ elTmp.parentNode.removeChild(elTmp); } } aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); } if(aTR.length < 1){ this.elSelectionStartTable.parentNode.removeChild(this.elSelectionStartTable); } this._updateSelection(); }, _insertColumnAfter : function(){ this._removeClassFromSelection(); this._hideTableTemplate(this.elSelectionStartTable); var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var sInserted; var sTmpAttr_Inserted = "_tmp_inserted"; var elCell, elCellClone, elCurTR, elInsertionPt; // copy each cells in the following order: top->down, right->left // +---+---+---+---+ // |...|.2.|.1.|...| // |---+---+.1.|...| // |...|.3.|.1.|...| // |...|.3.+---+...| // |...|.3.|.4.+...| // |...+---+---+...| // |...|.6.|.5.|...| // +---+---+---+---+ // [SMARTEDITORSUS-991] IE는 insertionPt의 previousSibling에도 배경색을 적용해줘야 할 필요가 있음. var htBrowser = jindo.$Agent().navigator(); // --[SMARTEDITORSUS-991] for(var y = 0, nYLen = this.htMap[0].length; y < nYLen; y++){ elCurTR = aTR[y]; for(var x = this.htSelectionEPos.x; x >= this.htSelectionSPos.x; x--){ elCell = this.htMap[x][y]; //sInserted = elCell.getAttribute(sTmpAttr_Inserted); //if(sInserted){continue;} //elCell.setAttribute(sTmpAttr_Inserted, "o"); elCellClone = this._shallowCloneTD(elCell); // elCellClone의 outerHTML에 정상적인 rowSpan이 있더라도 IE에서는 이 위치에서 항상 1을 반환. (elCellClone.rowSpan & elCellClone.getAttribute("rowSpan")). //var nSpan = parseInt(elCellClone.getAttribute("rowSpan")); var nSpan = parseInt(elCell.getAttribute("rowSpan")); if(nSpan > 1){ elCellClone.setAttribute("rowSpan", 1); elCellClone.style.height = ""; } nSpan = parseInt(elCell.getAttribute("colSpan")); if(nSpan > 1){ elCellClone.setAttribute("colSpan", 1); elCellClone.style.width = ""; } // 현재 줄(TR)에 속한 셀(TD)을 찾아서 그 앞에 append 한다. elInsertionPt = null; for(var xx = this.htSelectionEPos.x; xx >= this.htSelectionSPos.x; xx--){ if(this.htMap[xx][y].parentNode == elCurTR){ elInsertionPt = this.htMap[xx][y].nextSibling; break; } } elCurTR.insertBefore(elCellClone, elInsertionPt); // [SMARTEDITORSUS-991] IE는 insertionPt의 previousSibling에도 style을 적용해줘야 할 필요가 있음. // [SMARTEDITORSUS-1639] IE에서 JS오류가 발생되어 방어처리 (상하셀이 병합된 상태에서 열삽입하는 경우 발생) if(htBrowser.ie && htBrowser.nativeVersion >= 9 && elInsertionPt){ elInsertionPt.previousSibling.style.backgroundColor = elCellClone.style.backgroundColor; } // --[SMARTEDITORSUS-991] } } // remove the insertion marker from the original cells for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ this.aSelectedCells[i].removeAttribute(sTmpAttr_Inserted); } var nSelectionWidth = this.htSelectionEPos.x - this.htSelectionSPos.x + 1; var nSelectionHeight = this.htSelectionEPos.y - this.htSelectionSPos.y + 1; this.htSelectionSPos.x += nSelectionWidth; this.htSelectionEPos.x += nSelectionWidth; this.htMap = this._getCellMapping(this.elSelectionStartTable); this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this._showTableTemplate(this.elSelectionStartTable); this._addClassToSelection(); this.sQEAction = "INSERT_TABLE_COLUMN"; this.oApp.exec("SHOW_COMMON_QE"); }, _insertRowBelow : function(){ this._selectAll_Row(); this._removeClassFromSelection(); this._hideTableTemplate(this.elSelectionStartTable); var elRowClone; var elTBody = this.htMap[0][0].parentNode.parentNode; var aTRs = jindo.$$(">TR", elTBody, {oneTimeOffCache:true}); var elInsertionPt = aTRs[this.htSelectionEPos.y + 1] || null; // [SMARTEDITORSUS-991] IE는 insertionPt의 previousSibling에도 배경색을 적용해줘야 할 필요가 있음. var htBrowser = jindo.$Agent().navigator(); // --[SMARTEDITORSUS-991] for(var y = this.htSelectionSPos.y; y <= this.htSelectionEPos.y; y++){ elRowClone = this._getTRCloneWithAllTD(y); elTBody.insertBefore(elRowClone, elInsertionPt); // [SMARTEDITORSUS-991] IE는 insertionPt의 previousSibling에도 추가로 배경색을 적용해줘야 할 필요가 있음. if(htBrowser.ie && htBrowser.nativeVersion >= 9){ // IE의 경우 tr 사이에도 빈 텍스트 노드를 하나 추가해 줘야 한다. var elEmptyTextNode = aTRs[this.htSelectionEPos.y].nextSibling.cloneNode(); elTBody.insertBefore(elEmptyTextNode, elInsertionPt); // 스타일을 적용시켜 줄 대상 tr var elPreviousSiblingParent = this.htMap[0][y].parentNode; var aOriginalPreviousSibling = elPreviousSiblingParent.childNodes; var aPreviousSibling = []; for(var i = 0, len = aOriginalPreviousSibling.length; i < len; i++){ aPreviousSibling.push(aOriginalPreviousSibling[i]); } // 배경색을 복사하기 위해 준비 var aRowClone = elRowClone.childNodes; for(var i = 0, len = aRowClone.length; i < len; i++){ var elCloneTD = aRowClone[i]; var elPreviousTD = aPreviousSibling[i]; // [SMARTEDITORSUS-1639] 병합 후 추가시 JS 오류가 발생하는 문제가 있어 nodeName 확인 if(elCloneTD.nodeName == "TD" && elPreviousTD && elPreviousTD.nodeName == "TD"){ elPreviousTD.style.backgroundColor = elCloneTD.style.backgroundColor; } } } // --[SMARTEDITORSUS-991] } var nSelectionWidth = this.htSelectionEPos.x - this.htSelectionSPos.x + 1; var nSelectionHeight = this.htSelectionEPos.y - this.htSelectionSPos.y + 1; this.htSelectionSPos.y += nSelectionHeight; this.htSelectionEPos.y += nSelectionHeight; this.htMap = this._getCellMapping(this.elSelectionStartTable); this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this._showTableTemplate(this.elSelectionStartTable); this._addClassToSelection(); this.sQEAction = "INSERT_TABLE_ROW"; this.oApp.exec("SHOW_COMMON_QE"); }, _updateSelection : function(){ this.aSelectedCells = jindo.$A(this.aSelectedCells).filter(function(v){return (v.parentNode!==null && v.parentNode.parentNode!==null);}).$value(); }, _startCellSelection : function(){ this.htMap = this._getCellMapping(this.elSelectionStartTable); // De-select the default selection this.oApp.getEmptySelection().oBrowserSelection.selectNone(); if(this.oApp.oNavigator["safari"] || this.oApp.oNavigator["chrome"]){ this.oApp.getWYSIWYGDocument().onselectstart = function(){return false;}; } var elIFrame = this.oApp.getWYSIWYGWindow().frameElement; this.htEditingAreaPos = jindo.$Element(elIFrame).offset(); this.htEditingAreaPos.height = elIFrame.offsetHeight; this.htEditingAreaPos.bottom = this.htEditingAreaPos.top + this.htEditingAreaPos.height; this.htEditingAreaPos.width = elIFrame.offsetWidth; this.htEditingAreaPos.right = this.htEditingAreaPos.left + this.htEditingAreaPos.width; /* if(!this.oNavigatorInfo["firefox"]){ this.oApp.exec("DISABLE_WYSIWYG", []); } */ this._changeTableEditorStatus(this.STATUS.CELL_SELECTING); }, _selectBetweenCells : function(elCell1, elCell2){ this._deselectCells(); var oP1 = this._getBasisCellPosition(elCell1); var oP2 = this._getBasisCellPosition(elCell2); this._setEndPos(oP1); this._setEndPos(oP2); var oStartPos = {}, oEndPos = {}; oStartPos.x = Math.min(oP1.x, oP1.ex, oP2.x, oP2.ex); oStartPos.y = Math.min(oP1.y, oP1.ey, oP2.y, oP2.ey); oEndPos.x = Math.max(oP1.x, oP1.ex, oP2.x, oP2.ex); oEndPos.y = Math.max(oP1.y, oP1.ey, oP2.y, oP2.ey); this._selectCells(oStartPos, oEndPos); }, _getNextCell : function(elCell){ while(elCell){ elCell = elCell.nextSibling; if(elCell && elCell.tagName && elCell.tagName.match(/^TD|TH$/)){return elCell;} } return null; }, _getCellMapping : function(elTable){ var aTR = jindo.$$(">TBODY>TR", elTable, {oneTimeOffCache:true}); var nTD = 0; var aTD_FirstRow = aTR[0].childNodes; /* // remove empty TR's from the bottom of the table for(var i=aTR.length-1; i>0; i--){ if(!aTR[i].childNodes || aTR[i].childNodes.length === 0){ aTR[i].parentNode.removeChild(aTR[i]); aTR = aTR.slice(0, i); if(this.htSelectionSPos.y>=i) this.htSelectionSPos.y--; if(this.htSelectionEPos.y>=i) this.htSelectionEPos.y--; }else{ break; } } */ // count the number of columns for(var i = 0; i < aTD_FirstRow.length; i++){ var elTmp = aTD_FirstRow[i]; if(!elTmp.tagName || !elTmp.tagName.match(/^TD|TH$/)){continue;} if(elTmp.getAttribute("colSpan")){ nTD += this.parseIntOr0(elTmp.getAttribute("colSpan")); }else{ nTD ++; } } var nTblX = nTD; var nTblY = aTR.length; var aCellMapping = new Array(nTblX); for(var x = 0; x < nTblX; x++){ aCellMapping[x] = new Array(nTblY); } for(var y = 0; y < nTblY; y++){ var elCell = aTR[y].childNodes[0]; if(!elCell){continue;} if(!elCell.tagName || !elCell.tagName.match(/^TD|TH$/)){elCell = this._getNextCell(elCell);} var x = -1; while(elCell){ x++; if(!aCellMapping[x]){aCellMapping[x] = [];} if(aCellMapping[x][y]){continue;} var colSpan = parseInt(elCell.getAttribute("colSpan"), 10) || 1; var rowSpan = parseInt(elCell.getAttribute("rowSpan"), 10) || 1; /* if(y+rowSpan >= nTblY){ rowSpan = nTblY-y; elCell.setAttribute("rowSpan", rowSpan); } */ for(var yy = 0; yy < rowSpan; yy++){ for(var xx = 0; xx < colSpan; xx++){ if(!aCellMapping[x+xx]){ aCellMapping[x+xx] = []; } aCellMapping[x+xx][y+yy] = elCell; } } elCell = this._getNextCell(elCell); } } // remove empty TR's // (상단 TD의 rowspan만으로 지탱되는) 빈 TR이 있을 경우 IE7 이하에서 랜더링 오류가 발생 할 수 있어 빈 TR을 지워 줌 var bRowRemoved = false; var elLastCell = null; for(var y = 0, nRealY = 0, nYLen = aCellMapping[0].length; y < nYLen; y++, nRealY++){ elLastCell = null; if(!aTR[y].innerHTML.match(/TD|TH/i)){ for(var x = 0, nXLen = aCellMapping.length; x < nXLen; x++){ elCell = aCellMapping[x][y]; if(!elCell || elCell === elLastCell){ continue; } elLastCell = elCell; var rowSpan = parseInt(elCell.getAttribute("rowSpan"), 10) || 1; if(rowSpan > 1){ elCell.setAttribute("rowSpan", rowSpan - 1); } } aTR[y].parentNode.removeChild(aTR[y]); if(this.htSelectionEPos.y >= nRealY){ nRealY--; this.htSelectionEPos.y--; } bRowRemoved = true; } } if(bRowRemoved){ return this._getCellMapping(elTable); } return aCellMapping; }, _selectCells : function(htSPos, htEPos){ this.aSelectedCells = this._getSelectedCells(htSPos, htEPos); this._addClassToSelection(); }, _deselectCells : function(){ this._removeClassFromSelection(); this.aSelectedCells = []; this.htSelectionSPos = {x:-1, y:-1}; this.htSelectionEPos = {x:-1, y:-1}; }, _addClassToSelection : function(){ var welCell, elCell; for(var i = 0; i < this.aSelectedCells.length; i++){ elCell = this.aSelectedCells[i]; // [SMARTEDITORSUS-1552] 드래그로 셀을 선택하는 중 elCell이 없는 경우 오류 발생 if(elCell){ // [SMARTEDITORSUS-1498][SMARTEDITORSUS-1549] 선택된 모든 셀에서 드래그가 발생하지 못하게 방지(FF, Chrome) if(elCell.ondragstart == null){ elCell.ondragstart = function(){ return false; }; } // --[SMARTEDITORSUS-1498][SMARTEDITORSUS-1549] welCell = jindo.$Element(elCell); welCell.addClass(this.CELL_SELECTION_CLASS); // [SMARTEDITORSUS-1498][SMARTEDITORSUS-1549] 선택된 모든 셀에서 드래그가 발생하지 못하게 방지(FF, Chrome) welCell.addClass("undraggable"); // --[SMARTEDITORSUS-1498][SMARTEDITORSUS-1549] if(elCell.style.backgroundColor){ elCell.setAttribute(this.TMP_BGC_ATTR, elCell.style.backgroundColor); welCell.css("backgroundColor", ""); } if(elCell.style.backgroundImage) { elCell.setAttribute(this.TMP_BGIMG_ATTR, elCell.style.backgroundImage); welCell.css("backgroundImage", ""); } } // --[SMARTEDITORSUS-1552] } }, _removeClassFromSelection : function(){ var welCell, elCell; for(var i = 0; i < this.aSelectedCells.length; i++){ elCell = this.aSelectedCells[i]; // [SMARTEDITORSUS-1552] 드래그로 셀을 선택하는 중 elCell이 없는 경우 오류 발생 if(elCell){ welCell = jindo.$Element(elCell); welCell.removeClass(this.CELL_SELECTION_CLASS); // [SMARTEDITORSUS-1498][SMARTEDITORSUS-1549] 선택된 모든 셀에서 드래그가 발생하지 못하게 방지(FF, Chrome) welCell.removeClass("undraggable"); // --[SMARTEDITORSUS-1498][SMARTEDITORSUS-1549] //배경색 if(elCell.getAttribute(this.TMP_BGC_ATTR)){ elCell.style.backgroundColor = elCell.getAttribute(this.TMP_BGC_ATTR); elCell.removeAttribute(this.TMP_BGC_ATTR); } //배경이미지 if(elCell.getAttribute(this.TMP_BGIMG_ATTR)) { welCell.css("backgroundImage",elCell.getAttribute(this.TMP_BGIMG_ATTR)); elCell.removeAttribute(this.TMP_BGIMG_ATTR); } } // --[SMARTEDITORSUS-1552] } }, _expandAndSelect : function(htPos1, htPos2){ var x, y, elTD, nTmp, i; // expand top if(htPos1.y > 0){ for(x = htPos1.x; x <= htPos2.x; x++){ elTD = this.htMap[x][htPos1.y]; if(this.htMap[x][htPos1.y - 1] == elTD){ nTmp = htPos1.y - 2; while(nTmp >= 0 && this.htMap[x][nTmp] == elTD){ nTmp--; } htPos1.y = nTmp + 1; this._expandAndSelect(htPos1, htPos2); return; } } } // expand left if(htPos1.x > 0){ for(y = htPos1.y; y <= htPos2.y; y++){ elTD = this.htMap[htPos1.x][y]; if(this.htMap[htPos1.x - 1][y] == elTD){ nTmp = htPos1.x - 2; while(nTmp >= 0 && this.htMap[nTmp][y] == elTD){ nTmp--; } htPos1.x = nTmp + 1; this._expandAndSelect(htPos1, htPos2); return; } } } // expand bottom if(htPos2.y < this.htMap[0].length - 1){ for(x = htPos1.x; x <= htPos2.x; x++){ elTD = this.htMap[x][htPos2.y]; if(this.htMap[x][htPos2.y + 1] == elTD){ nTmp = htPos2.y + 2; while(nTmp < this.htMap[0].length && this.htMap[x][nTmp] == elTD){ nTmp++; } htPos2.y = nTmp - 1; this._expandAndSelect(htPos1, htPos2); return; } } } // expand right if(htPos2.x < this.htMap.length - 1){ for(y = htPos1.y; y <= htPos2.y; y++){ elTD = this.htMap[htPos2.x][y]; if(this.htMap[htPos2.x + 1][y] == elTD){ nTmp = htPos2.x + 2; while(nTmp < this.htMap.length && this.htMap[nTmp][y] == elTD){ nTmp++; } htPos2.x = nTmp - 1; this._expandAndSelect(htPos1, htPos2); return; } } } }, _getSelectedCells : function(htPos1, htPos2){ this._expandAndSelect(htPos1, htPos2); var x1 = htPos1.x; var y1 = htPos1.y; var x2 = htPos2.x; var y2 = htPos2.y; this.htSelectionSPos = htPos1; this.htSelectionEPos = htPos2; var aResult = []; for(var y = y1; y <= y2; y++){ for(var x = x1; x <= x2; x++){ if(jindo.$A(aResult).has(this.htMap[x][y])){ continue; } aResult[aResult.length] = this.htMap[x][y]; } } return aResult; }, _setEndPos : function(htPos){ var nColspan, nRowspan; nColspan = parseInt(htPos.elCell.getAttribute("colSpan"), 10) || 1; nRowspan = parseInt(htPos.elCell.getAttribute("rowSpan"), 10) || 1; htPos.ex = htPos.x + nColspan - 1; htPos.ey = htPos.y + nRowspan - 1; }, _getBasisCellPosition : function(elCell){ var x = 0, y = 0; for(x = 0; x < this.htMap.length; x++){ for(y = 0; y < this.htMap[x].length; y++){ if(this.htMap[x][y] == elCell){ return {'x': x, 'y': y, elCell: elCell}; } } } return {'x': 0, 'y': 0, elCell: elCell}; }, _applyTableTemplate : function(elTable, nTemplateIdx){ // clear style first if already exists /* if(elTable.getAttribute(this.ATTR_TBL_TEMPLATE)){ this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[this.parseIntOr0(elTable.getAttribute(this.ATTR_TBL_TEMPLATE))], true); }else{ this._clearAllTableStyles(elTable); } */ if (!elTable) { return; } // 사용자가 지정한 스타일 무시하고 새 템플릿 적용 // http://bts.nhncorp.com/nhnbts/browse/COM-871 this._clearAllTableStyles(elTable); this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[nTemplateIdx], false); elTable.setAttribute(this.ATTR_TBL_TEMPLATE, nTemplateIdx); }, _clearAllTableStyles : function(elTable){ elTable.removeAttribute("border"); elTable.removeAttribute("cellPadding"); elTable.removeAttribute("cellSpacing"); elTable.style.padding = ""; elTable.style.border = ""; elTable.style.backgroundColor = ""; elTable.style.color = ""; var aTD = jindo.$$(">TBODY>TR>TD", elTable, {oneTimeOffCache:true}); for(var i = 0, nLen = aTD.length; i < nLen; i++){ aTD[i].style.padding = ""; aTD[i].style.border = ""; aTD[i].style.backgroundColor = ""; aTD[i].style.color = ""; } }, _hideTableTemplate : function(elTable){ if(elTable.getAttribute(this.ATTR_TBL_TEMPLATE)){ this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[this.parseIntOr0(elTable.getAttribute(this.ATTR_TBL_TEMPLATE))], true); } }, _showTableTemplate : function(elTable){ if(elTable.getAttribute(this.ATTR_TBL_TEMPLATE)){ this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[this.parseIntOr0(elTable.getAttribute(this.ATTR_TBL_TEMPLATE))], false); } }, _doApplyTableTemplate : function(elTable, htTableTemplate, bClearStyle){ var htTableProperty = htTableTemplate.htTableProperty; var htTableStyle = htTableTemplate.htTableStyle; var ht1stRowStyle = htTableTemplate.ht1stRowStyle; var ht1stColumnStyle = htTableTemplate.ht1stColumnStyle; var aRowStyle = htTableTemplate.aRowStyle; var elTmp; // replace all TH's with TD's if(htTableProperty){ this._copyAttributesTo(elTable, htTableProperty, bClearStyle); } if(htTableStyle){ this._copyStylesTo(elTable, htTableStyle, bClearStyle); } var aTR = jindo.$$(">TBODY>TR", elTable, {oneTimeOffCache:true}); var nStartRowNum = 0; if(ht1stRowStyle){ var nStartRowNum = 1; for(var ii = 0, nNumCells = aTR[0].childNodes.length; ii < nNumCells; ii++){ elTmp = aTR[0].childNodes[ii]; if(!elTmp.tagName || !elTmp.tagName.match(/^TD|TH$/)){continue;} this._copyStylesTo(elTmp, ht1stRowStyle, bClearStyle); } } var nRowSpan; var elFirstEl; if(ht1stColumnStyle){ // if the style's got a row heading, skip the 1st row. (it was taken care above) var nRowStart = ht1stRowStyle ? 1 : 0; for(var i = nRowStart, nLen = aTR.length; i < nLen;){ elFirstEl = aTR[i].firstChild; nRowSpan = 1; if(elFirstEl && elFirstEl.tagName.match(/^TD|TH$/)){ nRowSpan = parseInt(elFirstEl.getAttribute("rowSpan"), 10) || 1; this._copyStylesTo(elFirstEl, ht1stColumnStyle, bClearStyle); } i += nRowSpan; } } if(aRowStyle){ var nNumStyles = aRowStyle.length; for(var i = nStartRowNum, nLen = aTR.length; i < nLen; i++){ for(var ii = 0, nNumCells = aTR[i].childNodes.length; ii < nNumCells; ii++){ var elTmp = aTR[i].childNodes[ii]; if(!elTmp.tagName || !elTmp.tagName.match(/^TD|TH$/)){continue;} this._copyStylesTo(elTmp, aRowStyle[(i+nStartRowNum)%nNumStyles], bClearStyle); } } } }, _copyAttributesTo : function(oTarget, htProperties, bClearStyle){ var elTmp; for(var x in htProperties){ if(htProperties.hasOwnProperty(x)){ if(bClearStyle){ if(oTarget[x]){ elTmp = document.createElement(oTarget.tagName); elTmp[x] = htProperties[x]; if(elTmp[x] == oTarget[x]){ oTarget.removeAttribute(x); } } }else{ elTmp = document.createElement(oTarget.tagName); elTmp.style[x] = ""; if(!oTarget[x] || oTarget.style[x] == elTmp.style[x]){oTarget.setAttribute(x, htProperties[x]);} } } } }, _copyStylesTo : function(oTarget, htProperties, bClearStyle){ var elTmp; for(var x in htProperties){ if(htProperties.hasOwnProperty(x)){ if(bClearStyle){ if(oTarget.style[x]){ elTmp = document.createElement(oTarget.tagName); elTmp.style[x] = htProperties[x]; if(elTmp.style[x] == oTarget.style[x]){ oTarget.style[x] = ""; } } }else{ elTmp = document.createElement(oTarget.tagName); elTmp.style[x] = ""; if(!oTarget.style[x] || oTarget.style[x] == elTmp.style[x] || x.match(/^border/)){oTarget.style[x] = htProperties[x];} } } } }, _hideResizer : function(){ this.elResizeGrid.style.display = "none"; }, _showResizer : function(){ this.elResizeGrid.style.display = "block"; }, _setResizerSize : function(width, height){ this.elResizeGrid.style.width = width + "px"; this.elResizeGrid.style.height = height + "px"; }, parseBorder : function(vBorder, sBorderStyle){ if(sBorderStyle == "none"){return 0;} var num = parseInt(vBorder, 10); if(isNaN(num)){ if(typeof(vBorder) == "string"){ // IE Bug return 1; /* switch(vBorder){ case "thin": return 1; case "medium": return 3; case "thick": return 5; } */ } } return num; }, parseIntOr0 : function(num){ num = parseInt(num, 10); if(isNaN(num)){return 0;} return num; }, _getTRCloneWithAllTD : function(nRow){ var elResult = this.htMap[0][nRow].parentNode.cloneNode(false); var elCurTD, elCurTDClone; for(var i = 0, nLen = this.htMap.length; i < nLen; i++){ elCurTD = this.htMap[i][nRow]; if(elCurTD.tagName == "TD"){ elCurTDClone = this._shallowCloneTD(elCurTD); elCurTDClone.setAttribute("rowSpan", 1); elCurTDClone.setAttribute("colSpan", 1); elCurTDClone.style.width = ""; elCurTDClone.style.height = ""; elResult.insertBefore(elCurTDClone, null); } } return elResult; }, _shallowCloneTD : function(elTD){ var elResult = elTD.cloneNode(false); elResult.innerHTML = this.sEmptyTDSrc; return elResult; }, // elTbl이 꽉 찬 직사각형 형태의 테이블인지 확인 _isValidTable : function(elTbl){ if(!elTbl || !elTbl.tagName || elTbl.tagName != "TABLE"){ return false; } this.htMap = this._getCellMapping(elTbl); var nXSize = this.htMap.length; if(nXSize < 1){return false;} var nYSize = this.htMap[0].length; if(nYSize < 1){return false;} for(var i = 1; i < nXSize; i++){ // 첫번째 열과 길이가 다른 열이 하나라도 있다면 직사각형이 아님 if(this.htMap[i].length != nYSize || !this.htMap[i][nYSize - 1]){ return false; } // 빈칸이 하나라도 있다면 꽉 찬 직사각형이 아님 for(var j = 0; j < nYSize; j++){ if(!this.htMap[i] || !this.htMap[i][j]){ return false; } } } return true; }, addCSSClass : function(sClassName, sClassRule){ var oDoc = this.oApp.getWYSIWYGDocument(); if(oDoc.styleSheets[0] && oDoc.styleSheets[0].addRule){ // IE oDoc.styleSheets[0].addRule("." + sClassName, sClassRule); }else{ // FF var elHead = oDoc.getElementsByTagName("HEAD")[0]; var elStyle = oDoc.createElement ("STYLE"); //styleElement.type = "text / css"; elHead.appendChild (elStyle); elStyle.sheet.insertRule("." + sClassName + " { "+sClassRule+" }", 0); } } //@lazyload_js] }); /** * @name SE2M_QuickEditor_Common * @class * @description Quick Editor Common function Class * @author NHN AjaxUI Lab - mixed * @version 1.0 * @since 2009.09.29 * */ nhn.husky.SE2M_QuickEditor_Common = jindo.$Class({ /** * class 이름 * @type {String} */ name : "SE2M_QuickEditor_Common", /** * 환경 정보. * @type {Object} */ _environmentData : "", /** * 현재 타입 (table|img) * @type {String} */ _currentType :"", /** * 이벤트가 레이어 안에서 호출되었는지 알기 위한 변수 * @type {Boolean} */ _in_event : false, /** * Ajax처리를 하지 않음 * @type {Boolean} */ _bUseConfig : true, /** * 공통 서버에서 개인 설정 받아오는 AjaxUrl * @See SE2M_Configuration.js */ _sBaseAjaxUrl : "", _sAddTextAjaxUrl : "", /** * 초기 인스턴스 생성 실행되는 함수. */ $init : function() { this.waHotkeys = new jindo.$A([]); this.waHotkeyLayers = new jindo.$A([]); }, $ON_MSG_APP_READY : function() { var htConfiguration = nhn.husky.SE2M_Configuration.QuickEditor; if(htConfiguration){ this._bUseConfig = (!!htConfiguration.common && typeof htConfiguration.common.bUseConfig !== "undefined") ? htConfiguration.common.bUseConfig : true; } if(!this._bUseConfig){ this.setData("{table:'full',img:'full',review:'full'}"); } else { this._sBaseAjaxUrl = htConfiguration.common.sBaseAjaxUrl; this._sAddTextAjaxUrl = htConfiguration.common.sAddTextAjaxUrl; this.getData(); } }, //삭제 시에 qe layer close $ON_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ var oKeyInfo = oEvent.key(); //Backspace : 8, Delete :46 if (oKeyInfo.keyCode == 8 || oKeyInfo.keyCode == 46 ) { // [SMARTEDITORSUS-1213][IE9, 10] 사진 삭제 후 zindex 1000인 div가 잔존하는데, 그 위로 썸네일 drag를 시도하다 보니 drop이 불가능. var htBrowser = jindo.$Agent().navigator(); if(htBrowser.ie && htBrowser.nativeVersion > 8){ var elFirstChild = jindo.$$.getSingle("DIV.husky_seditor_editing_area_container").childNodes[0]; if((elFirstChild.tagName == "DIV") && (elFirstChild.style.zIndex == 1000)){ elFirstChild.parentNode.removeChild(elFirstChild); } } // --[SMARTEDITORSUS-1213] this.oApp.exec("CLOSE_QE_LAYER", [oEvent]); } }, getData : function() { var self = this; jindo.$Ajax(self._sBaseAjaxUrl, { type : "jsonp", timeout : 1, onload: function(rp) { var result = rp.json().result; // [SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] QuickEditor 설정 API 개선 //if (!!result && !!result.length) { if (!!result && !!result.text_data) { //self.setData(result[result.length - 1]); self.setData(result.text_data); } else { self.setData("{table:'full',img:'full',review:'full'}"); } // --[SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] }, onerror : function() { self.setData("{table:'full',img:'full',review:'full'}"); }, ontimeout : function() { self.setData("{table:'full',img:'full',review:'full'}"); } }).request({ text_key : "qeditor_fold" }); }, setData : function(sResult){ var oResult = { table : "full", img : "full", review : "full" }; if(sResult){ oResult = eval("("+sResult+")"); } this._environmentData = { table : { isOpen : false, type : oResult["table"],//full,fold, isFixed : false, position : [] }, img : { isOpen : false, type : oResult["img"],//full,fold isFixed : false }, review : { isOpen : false, type : oResult["review"],//full,fold isFixed : false, position : [] } }; this.waTableTagNames =jindo.$A(["table","tbody","td","tfoot","th","thead","tr"]); }, /** * 위지윅 영역에 단축키가 등록될 때, * tab 과 shift+tab (들여쓰기 / 내어쓰기 ) 를 제외한 단축키 리스트를 저장한다. */ $ON_REGISTER_HOTKEY : function(sHotkey, sCMD, aArgs){ if(sHotkey != "tab" && sHotkey != "shift+tab"){ this.waHotkeys.push([sHotkey, sCMD, aArgs]); } }, //@lazyload_js OPEN_QE_LAYER[ $ON_MSG_BEFOREUNLOAD_FIRED : function(){ // [SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] QuickEditor 설정 API 개선으로, submit 이후 발생하게 되는 beforeunload 이벤트 핸들링 제거 /*if (!this._environmentData || !this._bUseConfig) { return; } jindo.$Ajax(this._sAddTextAjaxUrl,{ type : "jsonp", onload: function(){} }).request({ text_key :"qeditor_fold", text_data : "{table:'"+this._environmentData["table"]["type"]+"',img:'"+this._environmentData["img"]["type"]+"',review:'"+this._environmentData["review"]["type"]+"'}" });*/ // --[SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] }, /** * openType을 저장하는 함수. * @param {String} sType * @param {Boolean} bBol */ setOpenType : function(sType,bBol){ // [SMARTEDITORSUS-1213] 작성된 컨텐츠 수정 화면에서 사진이 로드되자마자 바로 사진을 클릭하면 QuickEditor를 띄우는 데 문제가 있음 if(typeof(this._environmentData) == "undefined" || this._environmentData == null){ this._environmentData = {}; } if(typeof(this._environmentData[sType]) == "undefined" || this._environmentData[sType] == null){ this._environmentData[sType] = {}; } if(typeof(this._environmentData[sType].isOpen) == "undefined" || this._environmentData[sType].isOpen == null){ this._environmentData[sType].isOpen = true; } // --[SMARTEDITORSUS-1213] this._environmentData[sType].isOpen = bBol; }, /** * 레이어가 오픈 할 때 실행되는 이벤트. * 레이어가 처음 뜰 때, * 저장된 단축키 리스트를 레이어에 등록하고 (레이어가 떠 있을때도 단축키가 먹도록 하기 위해) * 레이어에 대한 키보드/마우스 이벤트를 등록한다. * @param {Element} oEle * @param {Element} oLayer * @param {String} sType(img|table|review) */ $ON_OPEN_QE_LAYER : function(oEle,oLayer,sType){ if(this.waHotkeys.length() > 0 && !this.waHotkeyLayers.has(oLayer)){ this.waHotkeyLayers.push(oLayer); var aParam; for(var i=0, nLen=this.waHotkeys.length(); i<nLen; i++){ aParam = this.waHotkeys.get(i); this.oApp.exec("ADD_HOTKEY", [aParam[0], aParam[1], aParam[2], oLayer]); } } var type = sType;//?sType:"table";//this.get_type(oEle); if(type){ this.targetEle = oEle; this.currentEle = oLayer; this.layer_show(type,oEle); } }, /** * 레이어가 닫혔을때 실행되는 이벤트. * @param {jindo.$Event} weEvent */ $ON_CLOSE_QE_LAYER : function(weEvent){ if(!this.currentEle){return;} // this.oApp.exec("HIDE_EDITING_AREA_COVER"); // this.oApp.exec("ENABLE_ALL_UI"); this.oApp.exec("CLOSE_SUB_LAYER_QE"); this.layer_hide(weEvent); }, /** * 어플리케이션이 준비단계일때 실행되는 이벤트 */ $LOCAL_BEFORE_FIRST : function(sMsg) { if (!sMsg.match(/OPEN_QE_LAYER/)) { // (sMsg == "$ON_CLOSE_QE_LAYER" && !this.currentEle) this.oApp.acceptLocalBeforeFirstAgain(this, true); if(sMsg.match(/REGISTER_HOTKEY/)){ return true; } return false; } this.woEditor = jindo.$Element(this.oApp.elEditingAreaContainer); this.woStandard = jindo.$Element(this.oApp.htOptions.elAppContainer).offset(); this._qe_wrap = jindo.$$.getSingle("DIV.quick_wrap", this.oApp.htOptions.elAppContainer); var that = this; new jindo.DragArea(this._qe_wrap, { sClassName : 'q_dragable', bFlowOut : false, nThreshold : 1 }).attach({ beforeDrag : function(oCustomEvent) { oCustomEvent.elFlowOut = oCustomEvent.elArea.parentNode; }, dragStart: function(oCustomEvent){ if(!jindo.$Element(oCustomEvent.elDrag).hasClass('se2_qmax')){ oCustomEvent.elDrag = oCustomEvent.elDrag.parentNode; } that.oApp.exec("SHOW_EDITING_AREA_COVER"); }, dragEnd : function(oCustomEvent){ that.changeFixedMode(); that._in_event = false; //if(that._currentType=="review"||that._currentType=="table"){ // [SMARTEDITORSUS-153] 이미지 퀵 에디터도 같은 로직으로 처리하도록 수정 var richEle = jindo.$Element(oCustomEvent.elDrag); that._environmentData[that._currentType].position = [richEle.css("top"),richEle.css("left")]; //} that.oApp.exec("HIDE_EDITING_AREA_COVER"); } }); var imgFn = jindo.$Fn(this.toggle,this).bind("img"); var tableFn = jindo.$Fn(this.toggle,this).bind("table"); jindo.$Fn(imgFn,this).attach(jindo.$$.getSingle(".q_open_img_fold", this.oApp.htOptions.elAppContainer),"click"); jindo.$Fn(imgFn,this).attach(jindo.$$.getSingle(".q_open_img_full", this.oApp.htOptions.elAppContainer),"click"); jindo.$Fn(tableFn,this).attach(jindo.$$.getSingle(".q_open_table_fold", this.oApp.htOptions.elAppContainer),"click"); jindo.$Fn(tableFn,this).attach(jindo.$$.getSingle(".q_open_table_full", this.oApp.htOptions.elAppContainer),"click"); }, /** * 레이어의 최대화/최소화를 토글링 하는 함수. * @param {String} sType(table|img) * @param {jindo.$Event} weEvent */ toggle : function(sType,weEvent){ sType = this._currentType; // var oBefore = jindo.$Element(jindo.$$.getSingle("._"+this._environmentData[sType].type,this.currentEle)); // var beforeX = oBefore.css("left"); // var beforeY = oBefore.css("top"); this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); if(this._environmentData[sType].type=="full"){ this._environmentData[sType].type = "fold"; }else{ this._environmentData[sType].type = "full"; } // [SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] QuickEditor 설정 API 개선으로, submit 이후 발생하게 되는 beforeunload 이벤트 대신 호출 시점 변경 // QuickEditor를 접고 펼칠 때마다 API 통신을 거치기 때문에 submit이나 beforeunload에 구애받지 않고 안정적인 데이터 저장 가능 if (!this._environmentData || !this._bUseConfig) { return; } jindo.$Ajax(this._sAddTextAjaxUrl,{ type : "jsonp", onload: function(){} }).request({ text_key :"qeditor_fold", text_data : "{table:'"+this._environmentData["table"]["type"]+"',img:'"+this._environmentData["img"]["type"]+"',review:'"+this._environmentData["review"]["type"]+"'}" }); // --[SMARTEDITORSUS-1028][SMARTEDITORSUS-1517] // this.positionCopy(beforeX,beforeY,this._environmentData[sType].type); this.oApp.exec("OPEN_QE_LAYER", [this.targetEle,this.currentEle,sType]); this._in_event = false; weEvent.stop(jindo.$Event.CANCEL_DEFAULT); }, /** * 토글링시 전에 엘리먼트에 위치를 카피하는 함수. * @param {Number} beforeX * @param {Number} beforeY * @param {Element} sAfterEle */ positionCopy:function(beforeX, beforeY, sAfterEle){ jindo.$Element(jindo.$$.getSingle("._"+sAfterEle,this.currentEle)).css({ top : beforeY, left : beforeX }); }, /** * 레이어를 고정으로 할때 실행되는 함수. */ changeFixedMode : function(){ this._environmentData[this._currentType].isFixed = true; }, /** * 에디팅 영역에서 keyup할때 실행되는 함수. * @param {jindo.$Event} weEvent */ /* $ON_EVENT_EDITING_AREA_KEYUP:function(weEvent){ if(this._currentType&&(!this._in_event)&&this._environmentData[this._currentType].isOpen){ this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); } this._in_event = false; }, */ $ON_HIDE_ACTIVE_LAYER : function(){ this.oApp.exec("CLOSE_QE_LAYER"); }, /** * 에디팅 영역에서 mousedown할때 실행되는 함수. * @param {jindo.$Event} weEvent */ $ON_EVENT_EDITING_AREA_MOUSEDOWN:function(weEvent){ if(this._currentType&&(!this._in_event)&&this._environmentData[this._currentType].isOpen){ this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); } this._in_event = false; }, /** * 에디팅 영역에서 mousewheel할때 실행되는 함수. * @param {jindo.$Event} weEvent */ $ON_EVENT_EDITING_AREA_MOUSEWHEEL:function(weEvent){ if(this._currentType&&(!this._in_event)&&this._environmentData[this._currentType].isOpen){ this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); } this._in_event = false; }, /** * 레이어를 띄우는데 레이어가 table(템플릿),img인지를 확인하여 id를 반환하는 함수. * @param {Element} oEle * @return {String} layer id */ get_type : function(oEle){ var tagName = oEle.tagName.toLowerCase(); if(this.waTableTagNames.has(tagName)){ return "table"; }else if(tagName=="img"){ return "img"; } }, /** * 퀵에디터에서 keyup시 실행되는 이벤트 */ $ON_QE_IN_KEYUP : function(){ this._in_event = true; }, /** * 퀵에디터에서 mousedown시 실행되는 이벤트 */ $ON_QE_IN_MOUSEDOWN : function(){ this._in_event = true; }, /** * 퀵에디터에서 mousewheel시 실행되는 이벤트 */ $ON_QE_IN_MOUSEWHEEL : function(){ this._in_event = true; }, /** * 레이어를 숨기는 함수. * @param {jindo.$Event} weEvent */ layer_hide : function(weEvent){ this.setOpenType(this._currentType,false); jindo.$Element(jindo.$$.getSingle("._"+this._environmentData[this._currentType].type,this.currentEle)).hide(); }, /** * 늦게 이벤트 바인딩 하는 함수. * 레이어가 처음 뜰 때 이벤트를 등록한다. */ lazy_common : function(){ this.oApp.registerBrowserEvent(jindo.$(this._qe_wrap), "keyup", "QE_IN_KEYUP"); this.oApp.registerBrowserEvent(jindo.$(this._qe_wrap), "mousedown", "QE_IN_MOUSEDOWN"); this.oApp.registerBrowserEvent(jindo.$(this._qe_wrap), "mousewheel", "QE_IN_MOUSEWHEEL"); this.lazy_common = function(){}; }, /** * 레이어를 보여주는 함수. * @param {String} sType * @param {Element} oEle */ layer_show : function(sType,oEle){ this._currentType = sType; this.setOpenType(this._currentType,true); var layer = jindo.$$.getSingle("._"+this._environmentData[this._currentType].type,this.currentEle); jindo.$Element(layer) .show() .css( this.get_position_layer(oEle , layer) ); this.lazy_common(); }, /** * 레이어의 위치를 반환 하는 함수 * 고정 상태가 아니거나 최소화 상태이면 엘리먼트 위치에 퀵에디터를 띄우고 * 고정 상태이고 최대화 상태이면 표나 글 양식은 저장된 위치에 띄워주고, 이미지는...? * @param {Element} oEle * @param {Element} oLayer */ get_position_layer : function(oEle , oLayer){ if(!this.isCurrentFixed() || this._environmentData[this._currentType].type == "fold"){ return this.calculateLayer(oEle , oLayer); } //if(this._currentType == "review" || this._currentType == "table"){ // [SMARTEDITORSUS-153] 이미지 퀵 에디터도 같은 로직으로 처리하도록 수정 var position = this._environmentData[this._currentType].position; var nTop = parseInt(position[0], 10); var nAppHeight = this.getAppPosition().h; var nLayerHeight = jindo.$Element(oLayer).height(); // [SMARTEDITORSUS-129] 편집 영역 높이를 줄였을 때 퀵에디터가 영역을 벗어나지 않도록 처리 if((nTop + nLayerHeight + this.nYGap) > nAppHeight){ nTop = nAppHeight - nLayerHeight; this._environmentData[this._currentType].position[0] = nTop; } return { top : nTop + "px", left :position[1] }; //} //return this.calculateLayer(null , oLayer); }, /** * 현재 레이어가 고정형태인지 반환하는 함수. */ isCurrentFixed : function(){ return this._environmentData[this._currentType].isFixed; }, /** * 레이어를 띄울 위치를 계산하는 함수. * @param {Element} oEle * @param {Element} oLayer */ calculateLayer : function(oEle, oLayer){ /* * 기준을 한군데로 만들어야 함. * 1. 에디터는 페이지 * 2. 엘리먼트는 안에 에디팅 영역 * 3. 레이어는 에디팅 영역 * * 기준은 페이지로 함. */ var positionInfo = this.getPositionInfo(oEle, oLayer); return { top : positionInfo.y + "px", left : positionInfo.x + "px" }; }, /** * 위치를 반환 하는 함수. * @param {Element} oEle * @param {Element} oLayer */ getPositionInfo : function(oEle, oLayer){ this.nYGap = jindo.$Agent().navigator().ie? -16 : -18; this.nXGap = 1; var oRevisePosition = {}; var eleInfo = this.getElementPosition(oEle, oLayer); var appInfo = this.getAppPosition(); var layerInfo = { w : jindo.$Element(oLayer).width(), h : jindo.$Element(oLayer).height() }; if((eleInfo.x + layerInfo.w + this.nXGap) > appInfo.w){ oRevisePosition.x = appInfo.w - layerInfo.w ; }else{ oRevisePosition.x = eleInfo.x + this.nXGap; } if((eleInfo.y + layerInfo.h + this.nYGap) > appInfo.h){ oRevisePosition.y = appInfo.h - layerInfo.h - 2; }else{ oRevisePosition.y = eleInfo.y + this.nYGap; } return { x : oRevisePosition.x , y : oRevisePosition.y }; }, /** * 기준 엘리먼트의 위치를 반환하는 함수 * 엘리먼트가 있는 경우 * @param {Element} eEle */ getElementPosition : function(eEle, oLayer){ var wEle, oOffset, nEleWidth, nEleHeight, nScrollX, nScrollY; if(eEle){ wEle = jindo.$Element(eEle); oOffset = wEle.offset(); nEleWidth = wEle.width(); nEleHeight = wEle.height(); }else{ oOffset = { top : parseInt(oLayer.style.top, 10) - this.nYGap, left : parseInt(oLayer.style.left, 10) - this.nXGap }; nEleWidth = 0; nEleHeight = 0; } var oAppWindow = this.oApp.getWYSIWYGWindow(); if(typeof oAppWindow.scrollX == "undefined"){ nScrollX = oAppWindow.document.documentElement.scrollLeft; nScrollY = oAppWindow.document.documentElement.scrollTop; }else{ nScrollX = oAppWindow.scrollX; nScrollY = oAppWindow.scrollY; } var oEditotOffset = this.woEditor.offset(); return { x : oOffset.left - nScrollX + nEleWidth, y : oOffset.top - nScrollY + nEleHeight }; }, /** * 에디터의 크기 계산하는 함수. */ getAppPosition : function(){ return { w : this.woEditor.width(), h : this.woEditor.height() }; } //@lazyload_js] }); //{ /** * @fileOverview This file contains Husky plugin that takes care of the hotkey feature * @name hp_Hotkey.js */ nhn.husky.Hotkey = jindo.$Class({ name : "Hotkey", $init : function(){ this.oShortcut = shortcut; }, $ON_ADD_HOTKEY : function(sHotkey, sCMD, aArgs, elTarget){ if(!aArgs){aArgs = [];} var func = jindo.$Fn(this.oApp.exec, this.oApp).bind(sCMD, aArgs); this.oShortcut(sHotkey, elTarget).addEvent(func); } }); //} /** * @classDescription shortcut * @author AjaxUI Lab - mixed */ function Shortcut(sKey,sId){ var sKey = sKey.replace(/\s+/g,""); var store = Shortcut.Store; var action = Shortcut.Action; if(typeof sId === "undefined"&&sKey.constructor == String){ store.set("document",sKey,document); return action.init(store.get("document"),sKey); }else if(sId.constructor == String&&sKey.constructor == String){ store.set(sId,sKey,jindo.$(sId)); return action.init(store.get(sId),sKey); }else if(sId.constructor != String&&sKey.constructor == String){ var fakeId = "nonID"+new Date().getTime(); fakeId = Shortcut.Store.searchId(fakeId,sId); store.set(fakeId,sKey,sId); return action.init(store.get(fakeId),sKey); } alert(sId+"는 반드시 string이거나 없어야 됩니다."); }; Shortcut.Store = { anthorKeyHash:{}, datas:{}, currentId:"", currentKey:"", searchId:function(sId,oElement){ jindo.$H(this.datas).forEach(function(oValue,sKey){ if(oElement == oValue.element){ sId = sKey; jindo.$H.Break(); } }); return sId; }, set:function(sId,sKey,oElement){ this.currentId = sId; this.currentKey = sKey; var idData = this.get(sId); this.datas[sId] = idData?idData.createKey(sKey):new Shortcut.Data(sId,sKey,oElement); }, get:function(sId,sKey){ if(sKey){ return this.datas[sId].keys[sKey]; }else{ return this.datas[sId]; } }, reset:function(sId){ var data = this.datas[sId]; Shortcut.Helper.bind(data.func,data.element,"detach"); delete this.datas[sId]; }, allReset: function(){ jindo.$H(this.datas).forEach(jindo.$Fn(function(value,key) { this.reset(key); },this).bind()); } }; Shortcut.Data = jindo.$Class({ $init:function(sId,sKey,oElement){ this.id = sId; this.element = oElement; this.func = jindo.$Fn(this.fire,this).bind(); Shortcut.Helper.bind(this.func,oElement,"attach"); this.keys = {}; this.keyStemp = {}; this.createKey(sKey); }, createKey:function(sKey){ this.keyStemp[Shortcut.Helper.keyInterpretor(sKey)] = sKey; this.keys[sKey] = {}; var data = this.keys[sKey]; data.key = sKey; data.events = []; data.commonExceptions = []; // data.keyAnalysis = Shortcut.Helper.keyInterpretor(sKey); data.stopDefalutBehavior = true; return this; }, getKeyStamp : function(eEvent){ var sKey = eEvent.keyCode || eEvent.charCode; var returnVal = ""; returnVal += eEvent.altKey?"1":"0"; returnVal += eEvent.ctrlKey?"1":"0"; returnVal += eEvent.metaKey?"1":"0"; returnVal += eEvent.shiftKey?"1":"0"; returnVal += sKey; return returnVal; }, fire:function(eEvent){ eEvent = eEvent||window.eEvent; var oMatchKeyData = this.keyStemp[this.getKeyStamp(eEvent)]; if(oMatchKeyData){ this.excute(new jindo.$Event(eEvent),oMatchKeyData); } }, excute:function(weEvent,sRawKey){ var isExcute = true; var staticFun = Shortcut.Helper; var data = this.keys[sRawKey]; if(staticFun.notCommonException(weEvent,data.commonExceptions)){ jindo.$A(data.events).forEach(function(v){ if(data.stopDefalutBehavior){ var leng = v.exceptions.length; if(leng){ for(var i=0;i<leng;i++){ if(!v.exception[i](weEvent)){ isExcute = false; break; } } if(isExcute){ v.event(weEvent); if(jindo.$Agent().navigator().ie){ var e = weEvent._event; e.keyCode = ""; e.charCode = ""; } weEvent.stop(); }else{ jindo.$A.Break(); } }else{ v.event(weEvent); if(jindo.$Agent().navigator().ie){ var e = weEvent._event; e.keyCode = ""; e.charCode = ""; } weEvent.stop(); } } }); } }, addEvent:function(fpEvent,sRawKey){ var events = this.keys[sRawKey].events; if(!Shortcut.Helper.hasEvent(fpEvent,events)){ events.push({ event:fpEvent, exceptions:[] }); }; }, addException:function(fpException,sRawKey){ var commonExceptions = this.keys[sRawKey].commonExceptions; if(!Shortcut.Helper.hasException(fpException,commonExceptions)){ commonExceptions.push(fpException); }; }, removeException:function(fpException,sRawKey){ var commonExceptions = this.keys[sRawKey].commonExceptions; commonExceptions = jindo.$A(commonExceptions).filter(function(exception){ return exception!=fpException; }).$value(); }, removeEvent:function(fpEvent,sRawKey){ var events = this.keys[sRawKey].events; events = jindo.$A(events).filter(function(event) { return event!=fpEvent; }).$value(); this.unRegister(sRawKey); }, unRegister:function(sRawKey){ var aEvents = this.keys[sRawKey].events; if(aEvents.length) delete this.keys[sRawKey]; var hasNotKey = true; for(var i in this.keys){ hasNotKey =false; break; } if(hasNotKey){ Shortcut.Helper.bind(this.func,this.element,"detach"); delete Shortcut.Store.datas[this.id]; } }, startDefalutBehavior: function(sRawKey){ this._setDefalutBehavior(sRawKey,false); }, stopDefalutBehavior: function(sRawKey){ this._setDefalutBehavior(sRawKey,true); }, _setDefalutBehavior: function(sRawKey,bType){ this.keys[sRawKey].stopDefalutBehavior = bType; } }); Shortcut.Helper = { keyInterpretor:function(sKey){ var keyArray = sKey.split("+"); var wKeyArray = jindo.$A(keyArray); var returnVal = ""; returnVal += wKeyArray.has("alt")?"1":"0"; returnVal += wKeyArray.has("ctrl")?"1":"0"; returnVal += wKeyArray.has("meta")?"1":"0"; returnVal += wKeyArray.has("shift")?"1":"0"; var wKeyArray = wKeyArray.filter(function(v){ return !(v=="alt"||v=="ctrl"||v=="meta"||v=="shift") }); var key = wKeyArray.$value()[0]; if(key){ var sKey = Shortcut.Store.anthorKeyHash[key.toUpperCase()]||key.toUpperCase().charCodeAt(0); returnVal += sKey; } return returnVal; }, notCommonException:function(e,exceptions){ var leng = exceptions.length; for(var i=0;i<leng ;i++){ if(!exceptions[i](e)) return false; } return true; }, hasEvent:function(fpEvent,aEvents){ var nLength = aEvents.length; for(var i=0; i<nLength; ++i){ if(aEvents.event==fpEvent){ return true; } }; return false; }, hasException:function(fpException,commonExceptions){ var nLength = commonExceptions.length; for(var i=0; i<nLength; ++i){ if(commonExceptions[i]==fpException){ return true; } }; return false; }, bind:function(wfFunc,oElement,sType){ if(sType=="attach"){ domAttach(oElement,"keydown",wfFunc); }else{ domDetach(oElement,"keydown",wfFunc); } } }; (function domAttach (){ if(document.addEventListener){ window.domAttach = function(dom,ev,fn){ dom.addEventListener(ev, fn, false); } }else{ window.domAttach = function(dom,ev,fn){ dom.attachEvent("on"+ev, fn); } } })(); (function domDetach (){ if(document.removeEventListener){ window.domDetach = function(dom,ev,fn){ dom.removeEventListener(ev, fn, false); } }else{ window.domDetach = function(dom,ev,fn){ dom.detachEvent("on"+ev, fn); } } })(); Shortcut.Action ={ init:function(oData,sRawKey){ this.dataInstance = oData; this.rawKey = sRawKey; return this; }, addEvent:function(fpEvent){ this.dataInstance.addEvent(fpEvent,this.rawKey); return this; }, removeEvent:function(fpEvent){ this.dataInstance.removeEvent(fpEvent,this.rawKey); return this; }, addException : function(fpException){ this.dataInstance.addException(fpException,this.rawKey); return this; }, removeException : function(fpException){ this.dataInstance.removeException(fpException,this.rawKey); return this; }, // addCommonException : function(fpException){ // return this; // }, // removeCommonEexception : function(fpException){ // return this; // }, startDefalutBehavior: function(){ this.dataInstance.startDefalutBehavior(this.rawKey); return this; }, stopDefalutBehavior: function(){ this.dataInstance.stopDefalutBehavior(this.rawKey); return this; }, resetElement: function(){ Shortcut.Store.reset(this.dataInstance.id); return this; }, resetAll: function(){ Shortcut.Store.allReset(); return this; } }; (function (){ Shortcut.Store.anthorKeyHash = { BACKSPACE : 8, TAB : 9, ENTER : 13, ESC : 27, SPACE : 32, PAGEUP : 33, PAGEDOWN : 34, END : 35, HOME : 36, LEFT : 37, UP : 38, RIGHT : 39, DOWN : 40, DEL : 46, COMMA : 188,//(,) PERIOD : 190,//(.) SLASH : 191//(/), }; var hash = Shortcut.Store.anthorKeyHash; for(var i=1 ; i < 13 ; i++){ Shortcut.Store.anthorKeyHash["F"+i] = i+111; } var agent = jindo.$Agent().navigator(); if(agent.ie||agent.safari||agent.chrome){ hash.HYPHEN = 189;//(-) hash.EQUAL = 187;//(=) }else{ hash.HYPHEN = 109; hash.EQUAL = 61; } })(); var shortcut = Shortcut; if(typeof window.nhn=='undefined') window.nhn = {}; /** * @fileOverview This file contains a function that takes care of the draggable layers * @name N_DraggableLayer.js */ nhn.DraggableLayer = jindo.$Class({ $init : function(elLayer, oOptions){ this.elLayer = elLayer; this.setOptions(oOptions); this.elHandle = this.oOptions.elHandle; elLayer.style.display = "block"; elLayer.style.position = "absolute"; elLayer.style.zIndex = "9999"; this.aBasePosition = this.getBaseOffset(elLayer); // "number-ize" the position and set it as inline style. (the position could've been set as "auto" or set by css, not inline style) var nTop = (this.toInt(jindo.$Element(elLayer).offset().top) - this.aBasePosition.top); var nLeft = (this.toInt(jindo.$Element(elLayer).offset().left) - this.aBasePosition.left); var htXY = this._correctXY({x:nLeft, y:nTop}); elLayer.style.top = htXY.y+"px"; elLayer.style.left = htXY.x+"px"; this.$FnMouseDown = jindo.$Fn(jindo.$Fn(this._mousedown, this).bind(elLayer), this); this.$FnMouseMove = jindo.$Fn(jindo.$Fn(this._mousemove, this).bind(elLayer), this); this.$FnMouseUp = jindo.$Fn(jindo.$Fn(this._mouseup, this).bind(elLayer), this); this.$FnMouseDown.attach(this.elHandle, "mousedown"); this.elHandle.ondragstart = new Function('return false'); this.elHandle.onselectstart = new Function('return false'); }, _mousedown : function(elLayer, oEvent){ if(oEvent.element.tagName == "INPUT") return; this.oOptions.fnOnDragStart(); this.MouseOffsetY = (oEvent.pos().clientY-this.toInt(elLayer.style.top)-this.aBasePosition['top']); this.MouseOffsetX = (oEvent.pos().clientX-this.toInt(elLayer.style.left)-this.aBasePosition['left']); this.$FnMouseMove.attach(elLayer.ownerDocument, "mousemove"); this.$FnMouseUp.attach(elLayer.ownerDocument, "mouseup"); this.elHandle.style.cursor = "move"; }, _mousemove : function(elLayer, oEvent){ var nTop = (oEvent.pos().clientY-this.MouseOffsetY-this.aBasePosition['top']); var nLeft = (oEvent.pos().clientX-this.MouseOffsetX-this.aBasePosition['left']); var htXY = this._correctXY({x:nLeft, y:nTop}); elLayer.style.top = htXY.y + "px"; elLayer.style.left = htXY.x + "px"; }, _mouseup : function(elLayer, oEvent){ this.oOptions.fnOnDragEnd(); this.$FnMouseMove.detach(elLayer.ownerDocument, "mousemove"); this.$FnMouseUp.detach(elLayer.ownerDocument, "mouseup"); this.elHandle.style.cursor = ""; }, _correctXY : function(htXY){ var nLeft = htXY.x; var nTop = htXY.y; if(nTop<this.oOptions.nMinY) nTop = this.oOptions.nMinY; if(nTop>this.oOptions.nMaxY) nTop = this.oOptions.nMaxY; if(nLeft<this.oOptions.nMinX) nLeft = this.oOptions.nMinX; if(nLeft>this.oOptions.nMaxX) nLeft = this.oOptions.nMaxX; return {x:nLeft, y:nTop}; }, toInt : function(num){ var result = parseInt(num); return result || 0; }, findNonStatic : function(oEl){ if(!oEl) return null; if(oEl.tagName == "BODY") return oEl; if(jindo.$Element(oEl).css("position").match(/absolute|relative/i)) return oEl; return this.findNonStatic(oEl.offsetParent); }, getBaseOffset : function(oEl){ var oBase = this.findNonStatic(oEl.offsetParent) || oEl.ownerDocument.body; var tmp = jindo.$Element(oBase).offset(); return {top: tmp.top, left: tmp.left}; }, setOptions : function(htOptions){ this.oOptions = htOptions || {}; this.oOptions.bModal = this.oOptions.bModal || false; this.oOptions.elHandle = this.oOptions.elHandle || this.elLayer; this.oOptions.nMinX = this.oOptions.nMinX || -999999; this.oOptions.nMinY = this.oOptions.nMinY || -999999; this.oOptions.nMaxX = this.oOptions.nMaxX || 999999; this.oOptions.nMaxY = this.oOptions.nMaxY || 999999; this.oOptions.fnOnDragStart = this.oOptions.fnOnDragStart || function(){}; this.oOptions.fnOnDragEnd = this.oOptions.fnOnDragEnd || function(){}; } }); /*[ * TOGGLE_ACTIVE_LAYER * * 액티브 레이어가 화면에 보이는 여부를 토글 한다. * * oLayer HTMLElement 레이어로 사용할 HTML Element * sOnOpenCmd string 화면에 보이는 경우 발생 할 메시지(옵션) * aOnOpenParam array sOnOpenCmd와 함께 넘겨줄 파라미터(옵션) * sOnCloseCmd string 해당 레이어가 화면에서 숨겨질 때 발생 할 메시지(옵션) * aOnCloseParam array sOnCloseCmd와 함께 넘겨줄 파라미터(옵션) * ---------------------------------------------------------------------------]*/ /*[ * SHOW_ACTIVE_LAYER * * 액티브 레이어가 화면에 보이는 여부를 토글 한다. * * oLayer HTMLElement 레이어로 사용할 HTML Element * sOnCloseCmd string 해당 레이어가 화면에서 숨겨질 때 발생 할 메시지(옵션) * aOnCloseParam array sOnCloseCmd와 함께 넘겨줄 파라미터(옵션) * ---------------------------------------------------------------------------]*/ /*[ * HIDE_ACTIVE_LAYER * * 현재 화면에 보이는 액티브 레이어를 화면에서 숨긴다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc 한번에 한개만 화면에 보여야 하는 레이어를 관리하는 플러그인 */ nhn.husky.ActiveLayerManager = jindo.$Class({ name : "ActiveLayerManager", oCurrentLayer : null, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); }, $ON_TOGGLE_ACTIVE_LAYER : function(oLayer, sOnOpenCmd, aOnOpenParam, sOnCloseCmd, aOnCloseParam){ if(oLayer == this.oCurrentLayer){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }else{ this.oApp.exec("SHOW_ACTIVE_LAYER", [oLayer, sOnCloseCmd, aOnCloseParam]); if(sOnOpenCmd){this.oApp.exec(sOnOpenCmd, aOnOpenParam);} } }, $ON_SHOW_ACTIVE_LAYER : function(oLayer, sOnCloseCmd, aOnCloseParam){ oLayer = jindo.$(oLayer); var oPrevLayer = this.oCurrentLayer; if(oLayer == oPrevLayer){return;} this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.sOnCloseCmd = sOnCloseCmd; this.aOnCloseParam = aOnCloseParam; oLayer.style.display = "block"; this.oCurrentLayer = oLayer; this.oApp.exec("ADD_APP_PROPERTY", ["oToolBarLayer", this.oCurrentLayer]); }, $ON_HIDE_ACTIVE_LAYER : function(){ var oLayer = this.oCurrentLayer; if(!oLayer){return;} oLayer.style.display = "none"; this.oCurrentLayer = null; if(this.sOnCloseCmd){ this.oApp.exec(this.sOnCloseCmd, this.aOnCloseParam); } if(!!this.oNavigator.msafari){ this.oApp.getWYSIWYGWindow().focus(); } }, $ON_HIDE_ACTIVE_LAYER_IF_NOT_CHILD : function(el){ var elTmp = el; while(elTmp){ if(elTmp == this.oCurrentLayer){ return; } elTmp = elTmp.parentNode; } this.oApp.exec("HIDE_ACTIVE_LAYER"); }, // for backward compatibility only. // use HIDE_ACTIVE_LAYER instead! $ON_HIDE_CURRENT_ACTIVE_LAYER : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); } }); /*[ * SHOW_DIALOG_LAYER * * 다이얼로그 레이어를 화면에 보여준다. * * oLayer HTMLElement 다이얼로그 레이어로 사용 할 HTML 엘리먼트 * ---------------------------------------------------------------------------]*/ /*[ * HIDE_DIALOG_LAYER * * 다이얼로그 레이어를 화면에 숨긴다. * * oLayer HTMLElement 숨길 다이얼로그 레이어에 해당 하는 HTML 엘리먼트 * ---------------------------------------------------------------------------]*/ /*[ * HIDE_LAST_DIALOG_LAYER * * 마지막으로 화면에 표시한 다이얼로그 레이어를 숨긴다. * * none * ---------------------------------------------------------------------------]*/ /*[ * HIDE_ALL_DIALOG_LAYER * * 표시 중인 모든 다이얼로그 레이어를 숨긴다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc 드래그가 가능한 레이어를 컨트롤 하는 플러그인 */ nhn.husky.DialogLayerManager = jindo.$Class({ name : "DialogLayerManager", aMadeDraggable : null, aOpenedLayers : null, $init : function(){ this.aMadeDraggable = []; this.aDraggableLayer = []; this.aOpenedLayers = []; }, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); }, //@lazyload_js SHOW_DIALOG_LAYER,TOGGLE_DIALOG_LAYER:N_DraggableLayer.js[ $ON_SHOW_DIALOG_LAYER : function(elLayer, htOptions){ elLayer = jindo.$(elLayer); htOptions = htOptions || {}; if(!elLayer){return;} if(jindo.$A(this.aOpenedLayers).has(elLayer)){return;} this.oApp.exec("POSITION_DIALOG_LAYER", [elLayer]); this.aOpenedLayers[this.aOpenedLayers.length] = elLayer; var oDraggableLayer; var nIdx = jindo.$A(this.aMadeDraggable).indexOf(elLayer); if(nIdx == -1){ oDraggableLayer = new nhn.DraggableLayer(elLayer, htOptions); this.aMadeDraggable[this.aMadeDraggable.length] = elLayer; this.aDraggableLayer[this.aDraggableLayer.length] = oDraggableLayer; }else{ if(htOptions){ oDraggableLayer = this.aDraggableLayer[nIdx]; oDraggableLayer.setOptions(htOptions); } elLayer.style.display = "block"; } if(htOptions.sOnShowMsg){ this.oApp.exec(htOptions.sOnShowMsg, htOptions.sOnShowParam); } }, $ON_HIDE_LAST_DIALOG_LAYER : function(){ this.oApp.exec("HIDE_DIALOG_LAYER", [this.aOpenedLayers[this.aOpenedLayers.length-1]]); }, $ON_HIDE_ALL_DIALOG_LAYER : function(){ for(var i=this.aOpenedLayers.length-1; i>=0; i--){ this.oApp.exec("HIDE_DIALOG_LAYER", [this.aOpenedLayers[i]]); } }, $ON_HIDE_DIALOG_LAYER : function(elLayer){ elLayer = jindo.$(elLayer); if(elLayer){elLayer.style.display = "none";} this.aOpenedLayers = jindo.$A(this.aOpenedLayers).refuse(elLayer).$value(); if(!!this.oNavigator.msafari){ this.oApp.getWYSIWYGWindow().focus(); } }, $ON_TOGGLE_DIALOG_LAYER : function(elLayer, htOptions){ if(jindo.$A(this.aOpenedLayers).indexOf(elLayer)){ this.oApp.exec("SHOW_DIALOG_LAYER", [elLayer, htOptions]); }else{ this.oApp.exec("HIDE_DIALOG_LAYER", [elLayer]); } }, $ON_SET_DIALOG_LAYER_POSITION : function(elLayer, nTop, nLeft){ elLayer.style.top = nTop; elLayer.style.left = nLeft; } //@lazyload_js] }); //{ /** * @fileOverview This file contains * @name hp_LazyLoader.js */ nhn.husky.LazyLoader = jindo.$Class({ name : "LazyLoader", // sMsg : KEY // contains htLoadingInfo : {} htMsgInfo : null, // contains objects // sURL : HTML to be loaded // elTarget : where to append the HTML // sSuccessCallback : message name // sFailureCallback : message name // nLoadingStatus : // 0 : loading not started // 1 : loading started // 2 : loading ended aLoadingInfo : null, // aToDo : [{aMsgs: ["EXECCOMMAND"], sURL: "http://127.0.0.1/html_snippet.txt", elTarget: elPlaceHolder}, ...] $init : function(aToDo){ this.htMsgInfo = {}; this.aLoadingInfo = []; this.aToDo = aToDo; }, $ON_MSG_APP_READY : function(){ for(var i=0; i<this.aToDo.length; i++){ var htToDoDetail = this.aToDo[i]; this._createBeforeHandlersAndSaveURLInfo(htToDoDetail.oMsgs, htToDoDetail.sURL, htToDoDetail.elTarget, htToDoDetail.htOptions); } }, $LOCAL_BEFORE_ALL : function(sMsgHandler, aParams){ var sMsg = sMsgHandler.replace("$BEFORE_", ""); var htCurMsgInfo = this.htMsgInfo[sMsg]; // ignore current message if(htCurMsgInfo.nLoadingStatus == 1){return true;} // the HTML was loaded before(probably by another message), remove the loading handler and re-send the message if(htCurMsgInfo.nLoadingStatus == 2){ this[sMsgHandler] = function(){ this._removeHandler(sMsgHandler); this.oApp.delayedExec(sMsg, aParams, 0); return false; }; return true; } htCurMsgInfo.bLoadingStatus = 1; (new jindo.$Ajax(htCurMsgInfo.sURL, { onload : jindo.$Fn(this._onload, this).bind(sMsg, aParams) })).request(); return true; }, _onload : function(sMsg, aParams, oResponse){ if(oResponse._response.readyState == 4) { this.htMsgInfo[sMsg].elTarget.innerHTML = oResponse.text(); this.htMsgInfo[sMsg].nLoadingStatus = 2; this._removeHandler("$BEFORE_"+sMsg); this.oApp.exec("sMsg", aParams); }else{ this.oApp.exec(this.htMsgInfo[sMsg].sFailureCallback, []); } }, _removeHandler : function(sMsgHandler){ delete this[sMsgHandler]; this.oApp.createMessageMap(sMsgHandler); }, _createBeforeHandlersAndSaveURLInfo : function(oMsgs, sURL, elTarget, htOptions){ htOptions = htOptions || {}; var htNewInfo = { sURL : sURL, elTarget : elTarget, sSuccessCallback : htOptions.sSuccessCallback, sFailureCallback : htOptions.sFailureCallback, nLoadingStatus : 0 }; this.aLoadingInfo[this.aLoadingInfo.legnth] = htNewInfo; // extract msgs if plugin is given if(!(oMsgs instanceof Array)){ var oPlugin = oMsgs; oMsgs = []; var htMsgAdded = {}; for(var sFunctionName in oPlugin){ if(sFunctionName.match(/^\$(BEFORE|ON|AFTER)_(.+)$/)){ var sMsg = RegExp.$2; if(sMsg == "MSG_APP_READY"){continue;} if(!htMsgAdded[sMsg]){ oMsgs[oMsgs.length] = RegExp.$2; htMsgAdded[sMsg] = true; } } } } for(var i=0; i<oMsgs.length; i++){ // create HTML loading handler var sTmpMsg = "$BEFORE_"+oMsgs[i]; this[sTmpMsg] = function(){return false;}; this.oApp.createMessageMap(sTmpMsg); // add loading info this.htMsgInfo[oMsgs[i]] = htNewInfo; } } }); //} //{ /** * @fileOverview This file contains Husky plugin that maps a message code to the actual message * @name hp_MessageManager.js */ nhn.husky.MessageManager = jindo.$Class({ name : "MessageManager", oMessageMap : null, sLocale : "ko_KR", $init : function(oMessageMap, sLocale){ switch(sLocale) { case "ja_JP" : this.oMessageMap = oMessageMap_ja_JP; break; case "en_US" : this.oMessageMap = oMessageMap_en_US; break; case "zh_CN" : this.oMessageMap = oMessageMap_zh_CN; break; default : // Korean this.oMessageMap = oMessageMap; break; } }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["$MSG", jindo.$Fn(this.getMessage, this).bind()]); }, getMessage : function(sMsg){ if(this.oMessageMap[sMsg]){return unescape(this.oMessageMap[sMsg]);} return sMsg; } }); //} /** * @name nhn.husky.PopUpManager * @namespace * @description 팝업 매니저 클래스. * <dt><strong>Spec Code</strong></dt> * <dd><a href="http://ajaxui.nhndesign.com/svnview/SmartEditor2_Official/tags/SE2M_popupManager/0.1/test/spec/hp_popupManager_spec.html" target="_new">Spec</a></dd> * <dt><strong>wiki</strong></dt> * <dd><a href="http://wikin.nhncorp.com/pages/viewpage.action?pageId=63501152" target="_new">wiki</a></dd> * @author NHN AjaxUI Lab - sung jong min * @version 0.1 * @since 2009.07.06 */ nhn.husky.PopUpManager = {}; /** * @ignore */ nhn.husky.PopUpManager._instance = null; /** * @ignore */ nhn.husky.PopUpManager._pluginKeyCnt = 0; /** * @description 팝업 매니저 인스턴스 호출 메소드, nhn.husky js framework 기반 코드 * @public * @param {Object} oApp 허스키 코어 객체를 넘겨준다.(this.oApp) * @return {Object} nhn.husky.PopUpManager Instance * @example 팝업관련 플러그인 제작 예제 * nhn.husky.NewPlugin = function(){ * this.$ON_APP_READY = function(){ * // 팝업 매니저 getInstance 메소드를 호출한다. * // 허스키 코어의 참조값을 넘겨준다(this.oApp) * this.oPopupMgr = nhn.husky.PopUpMaganer.getInstance(this.oApp); * }; * * // 팝업을 요청하는 메시지 메소드는 아래와 같음 * this.$ON_NEWPLUGIN_OPEN_WINDOW = function(){ * var oWinOp = { * oApp : this.oApp, // oApp this.oApp 허스키 참조값 * sUrl : "", // sUrl : 페이지 URL * sName : "", // sName : 페이지 name * nWidth : 400, * nHeight : 400, * bScroll : true * } * this.oPopUpMgr.openWindow(oWinOp); * }; * * // 팝업페이지 응답데이타 반환 메시지 메소드를 정의함. * // 각 플러그인 팝업페이지에서 해당 메시지와 데이타를 넘기게 됨. * this.@ON_NEWPLUGIN_WINDOW_CALLBACK = function(){ * // 팝업페이지별로 정의된 형태의 아규먼트 데이타가 넘어오면 처리한다. * } * } * @example 팝업 페이지와 opener 호출 인터페이스 예제 * onclick시 * "nhn.husky.PopUpManager.setCallback(window, "NEWPLUGIN_WINDOW_CALLBACK", oData);" * 형태로 호출함. * * */ nhn.husky.PopUpManager.getInstance = function(oApp) { if (this._instance==null) { this._instance = new (function(){ this._whtPluginWin = new jindo.$H(); this._whtPlugin = new jindo.$H(); this.addPlugin = function(sKey, vValue){ this._whtPlugin.add(sKey, vValue); }; this.getPlugin = function() { return this._whtPlugin; }; this.getPluginWin = function() { return this._whtPluginWin; }; this.openWindow = function(oWinOpt) { var op= { oApp : null, sUrl : "", sName : "popup", sLeft : null, sTop : null, nWidth : 400, nHeight : 400, sProperties : null, bScroll : true }; for(var i in oWinOpt) op[i] = oWinOpt[i]; if(op.oApp == null) { alert("팝업 요청시 옵션으로 oApp(허스키 reference) 값을 설정하셔야 합니다."); } var left = op.sLeft || (screen.availWidth-op.nWidth)/2; var top = op.sTop ||(screen.availHeight-op.nHeight)/2; var sProperties = op.sProperties != null ? op.sProperties : "top="+ top +",left="+ left +",width="+op.nWidth+",height="+op.nHeight+",scrollbars="+(op.bScroll?"yes":"no")+",status=yes"; var win = window.open(op.sUrl, op.sName,sProperties); if (!!win) { setTimeout( function(){ try{win.focus();}catch(e){} }, 100); } this.removePluginWin(win); this._whtPluginWin.add(this.getCorrectKey(this._whtPlugin, op.oApp), win); return win; }; this.getCorrectKey = function(whtData, oCompare) { var key = null; whtData.forEach(function(v,k){ if (v == oCompare) { key = k; return; } }); return key; }; this.removePluginWin = function(vValue) { var list = this._whtPluginWin.search(vValue); if (list) { this._whtPluginWin.remove(list); this.removePluginWin(vValue); } } })(); } this._instance.addPlugin("plugin_" + (this._pluginKeyCnt++), oApp); return nhn.husky.PopUpManager._instance; }; /** * @description opener 연동 interface * @public * @param {Object} oOpenWin 팝업 페이지의 window 객체 * @param {Object} sMsg 플러그인 메시지명 * @param {Object} oData 응답 데이타 */ nhn.husky.PopUpManager.setCallback = function(oOpenWin, sMsg, oData) { if (this._instance.getPluginWin().hasValue(oOpenWin)) { var key = this._instance.getCorrectKey(this._instance.getPluginWin(), oOpenWin); if (key) { this._instance.getPlugin().$(key).exec(sMsg, oData); } } }; /** * @description opener에 허스키 함수를 실행시키고 데이터 값을 리턴 받음. * @param */ nhn.husky.PopUpManager.getFunc = function(oOpenWin, sFunc) { if (this._instance.getPluginWin().hasValue(oOpenWin)) { var key = this._instance.getCorrectKey(this._instance.getPluginWin(), oOpenWin); if (key) { return this._instance.getPlugin().$(key)[sFunc](); } } }; nhn.husky.SE2M_ImgSizeRatioKeeper = jindo.$Class({ name : "SE2M_ImgSizeRatioKeeper", $init : function(elAppContainer){ this.elAppContainer = elAppContainer; }, $LOCAL_BEFORE_FIRST : function(){ this.wfnResizeEnd = jindo.$Fn(this._onResizeEnd, this); this.bIE = jindo.$Agent().navigator().ie; this.elCheckImgAutoAdjust = jindo.$$.getSingle(".se2_srate", this.elAppContainer); if(!this.bIE){ this.$ON_EVENT_EDITING_AREA_KEYDOWN = undefined; this.$ON_EVENT_EDITING_AREA_MOUSEUP = undefined; } }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(){ this._detachResizeEnd(); }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(wev){ this._detachResizeEnd(); if(!wev.element || wev.element.tagName != "IMG"){return;} this.oApp.exec("SET_RESIZE_TARGET_IMG", [wev.element]); }, $ON_SET_RESIZE_TARGET_IMG : function(elImg){ if(elImg == this.elImg){return;} this._detachResizeEnd(); this._attachResizeEnd(elImg); }, _attachResizeEnd : function(elImg){ this.elImg = elImg; this.wfnResizeEnd.attach(this.elImg, "resizeend"); this.elBorderSize = (elImg.border || 0); this.nWidth = this.elImg.clientWidth ; this.nHeight = this.elImg.clientHeight ; }, _detachResizeEnd : function(){ if(!this.elImg){return;} this.wfnResizeEnd.detach(this.elImg, "resizeend"); this.elImg = null; }, _onResizeEnd : function(wev){ if(wev.element != this.elImg){return;} var nRatio, nAfterWidth, nAfterheight, nWidthDiff, nHeightDiff, nborder; nborder = this.elImg.border || 0; nAfterWidth = this.elImg.clientWidth - (nborder*2); nAfterheight = this.elImg.clientHeight - (nborder*2); if(this.elCheckImgAutoAdjust.checked){ nWidthDiff = nAfterWidth - this.nWidth; //미세한 차이에 크기 변화는 무시. if( -1 <= nWidthDiff && nWidthDiff <= 1){ nRatio = this.nWidth/this.nHeight; nAfterWidth = nRatio * nAfterheight; }else{ nRatio = this.nHeight/this.nWidth; nAfterheight = nRatio * nAfterWidth; } } this.elImg.style.width = nAfterWidth + "px"; this.elImg.style.height = nAfterheight + "px"; this.elImg.setAttribute("width", nAfterWidth ); this.elImg.setAttribute("height", nAfterheight); // [SMARTEDITORSUS-299] 마우스 Drag로 이미지 크기 리사이즈 시, 삽입할 때의 저장 사이즈(rwidth/rheight)도 변경해 줌 this.elImg.style.rwidth = this.elImg.style.width; this.elImg.style.rheight = this.elImg.style.height; this.elImg.setAttribute("rwidth", this.elImg.getAttribute("width")); this.elImg.setAttribute("rheight", this.elImg.getAttribute("height")); // 아래의 부분은 추후 hp_SE2M_ImgSizeAdjustUtil.js 를 생성하여 분리한다. var bAdjustpossible = this._isAdjustPossible(this.elImg.offsetWidth); if(!bAdjustpossible){ this.elImg.style.width = this.nWidth; this.elImg.style.height = this.nHeight; this.elImg.style.rwidth = this.elImg.style.width; this.elImg.style.rheight = this.elImg.style.height; this.elImg.setAttribute("width", this.nWidth); this.elImg.setAttribute("height", this.nHeight); this.elImg.setAttribute("rwidth", this.elImg.getAttribute("width")); this.elImg.setAttribute("rheight", this.elImg.getAttribute("height")); } this.oApp.delayedExec("SET_RESIZE_TARGET_IMG", [this.elImg], 0); }, _isAdjustPossible : function(width){ var bPossible = true; // 가로폭 적용하는 경우에만 에디터 본문 안에 보이는 이미지 사이즈를 조절함 var bRulerUse = (this.oApp.htOptions['SE2M_EditingAreaRuler']) ? this.oApp.htOptions['SE2M_EditingAreaRuler'].bUse : false; if(bRulerUse){ var welWysiwygBody = jindo.$Element(this.oApp.getWYSIWYGDocument().body); if(welWysiwygBody){ var nEditorWidth = welWysiwygBody.width(); if(width > nEditorWidth){ bPossible = false; alert(this.oApp.$MSG("SE2M_ImgSizeRatioKeeper.exceedMaxWidth").replace("#EditorWidth#", nEditorWidth)); } } } return bPossible; } }); if(typeof window.nhn == 'undefined') { window.nhn = {}; } if(!nhn.husky) { nhn.husky = {}; } nhn.husky.SE2M_UtilPlugin = jindo.$Class({ name : "SE2M_UtilPlugin", $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["oAgent", jindo.$Agent()]); this.oApp.exec("ADD_APP_PROPERTY", ["oNavigator", jindo.$Agent().navigator()]); this.oApp.exec("ADD_APP_PROPERTY", ["oUtils", this]); }, $ON_REGISTER_HOTKEY : function(sHotkey, sCMD, aArgs, elTarget) { this.oApp.exec("ADD_HOTKEY", [sHotkey, sCMD, aArgs, (elTarget || this.oApp.getWYSIWYGDocument())]); }, $ON_SE2_ATTACH_HOVER_EVENTS : function(aElms){ this.oApp.exec("ATTACH_HOVER_EVENTS", [aElms, {fnElmToSrc: this._elm2Src, fnElmToTarget: this._elm2Target}]); }, _elm2Src : function(el){ if(el.tagName == "LI" && el.firstChild && el.firstChild.tagName == "BUTTON"){ return el.firstChild; }else{ return el; } }, _elm2Target : function(el){ if(el.tagName == "BUTTON" && el.parentNode.tagName == "LI"){ return el.parentNode; }else{ return el; } }, getScrollXY : function(){ var scrollX,scrollY; var oAppWindow = this.oApp.getWYSIWYGWindow(); if(typeof oAppWindow.scrollX == "undefined"){ scrollX = oAppWindow.document.documentElement.scrollLeft; scrollY = oAppWindow.document.documentElement.scrollTop; }else{ scrollX = oAppWindow.scrollX; scrollY = oAppWindow.scrollY; } return {x:scrollX, y:scrollY}; } }); nhn.husky.SE2M_Utils = { sURLPattern : '(http|https|ftp|mailto):(?:\\/\\/)?((:?\\w|-)+(:?\\.(:?\\w|-)+)+)([^ <>]+)?', /** * 사용자 클래스 정보를 추출한다. * @param {String} sStr 추출 String * @param {rx} rxValue rx type 형식의 값 * @param {String} sDivision value의 split 형식 * @return {Array} */ getCustomCSS : function(sStr, rxValue, sDivision) { var ret = []; if('undefined' == typeof(sStr) || 'undefined' == typeof(rxValue) || !sStr || !rxValue) { return ret; } var aMatch = sStr.match(rxValue); if(aMatch && aMatch[0]&&aMatch[1]) { if(sDivision) { ret = aMatch[1].split(sDivision); } else { ret[0] = aMatch[1]; } } return ret; }, /** * HashTable로 구성된 Array의 같은 프로퍼티를 sSeperator 로 구분된 String 값으로 변환 * @param {Object} v * @param {Object} sKey * @author senxation * @example a = [{ b : "1" }, { b : "2" }] toStringSamePropertiesOfArray(a, "b", ", "); ==> "1, 2" */ toStringSamePropertiesOfArray : function(v, sKey, sSeperator) { if (v instanceof Array) { var a = []; for (var i = 0; i < v.length; i++) { a.push(v[i][sKey]); } return a.join(",").replace(/,/g, sSeperator); } else { if (typeof v[sKey] == "undefined") { return ""; } if (typeof v[sKey] == "string") { return v[sKey]; } } }, /** * 단일 객체를 배열로 만들어줌 * @param {Object} v * @return {Array} * @author senxation * @example makeArray("test"); ==> ["test"] */ makeArray : function(v) { if (v === null || typeof v === "undefined"){ return []; } if (v instanceof Array) { return v; } var a = []; a.push(v); return a; }, /** * 말줄임을 할때 줄일 내용과 컨테이너가 다를 경우 처리 * 컨테이너의 css white-space값이 "normal"이어야한다. (컨테이너보다 텍스트가 길면 여러행으로 표현되는 상태) * @param {HTMLElement} elText 말줄임할 엘리먼트 * @param {HTMLElement} elContainer 말줄임할 엘리먼트를 감싸는 컨테이너 * @param {String} sStringTail 말줄임을 표현할 문자열 (미지정시 ...) * @param {Number} nLine 최대 라인수 (미지정시 1) * @author senxation * @example //div가 2줄 이하가 되도록 strong 내부의 내용을 줄임 <div> <strong id="a">말줄임을적용할내용말줄임을적용할내용말줄임을적용할내용</strong><span>상세보기</span> <div> ellipsis(jindo.$("a"), jindo.$("a").parentNode, "...", 2); */ ellipsis : function(elText, elContainer, sStringTail, nLine) { sStringTail = sStringTail || "..."; if (typeof nLine == "undefined") { nLine = 1; } var welText = jindo.$Element(elText); var welContainer = jindo.$Element(elContainer); var sText = welText.html(); var nLength = sText.length; var nCurrentHeight = welContainer.height(); var nIndex = 0; welText.html('A'); var nHeight = welContainer.height(); if (nCurrentHeight < nHeight * (nLine + 0.5)) { return welText.html(sText); } /** * 지정된 라인보다 커질때까지 전체 남은 문자열의 절반을 더해나감 */ nCurrentHeight = nHeight; while(nCurrentHeight < nHeight * (nLine + 0.5)) { nIndex += Math.max(Math.ceil((nLength - nIndex)/2), 1); welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentHeight = welContainer.height(); } /** * 지정된 라인이 될때까지 한글자씩 잘라냄 */ while(nCurrentHeight > nHeight * (nLine + 0.5)) { nIndex--; welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentHeight = welContainer.height(); } }, /** * 최대 가로사이즈를 지정하여 말줄임한다. * elText의 css white-space값이 "nowrap"이어야한다. (컨테이너보다 텍스트가 길면 행변환되지않고 가로로 길게 표현되는 상태) * @param {HTMLElement} elText 말줄임할 엘리먼트 * @param {String} sStringTail 말줄임을 표현할 문자열 (미지정시 ...) * @param {Function} fCondition 조건 함수. 내부에서 true를 리턴하는 동안에만 말줄임을 진행한다. * @author senxation * @example //150픽셀 이하가 되도록 strong 내부의 내용을 줄임 <strong id="a">말줄임을적용할내용말줄임을적용할내용말줄임을적용할내용</strong>> ellipsisByPixel(jindo.$("a"), "...", 150); */ ellipsisByPixel : function(elText, sStringTail, nPixel, fCondition) { sStringTail = sStringTail || "..."; var welText = jindo.$Element(elText); var nCurrentWidth = welText.width(); if (nCurrentWidth < nPixel) { return; } var sText = welText.html(); var nLength = sText.length; var nIndex = 0; if (typeof fCondition == "undefined") { var nWidth = welText.html('A').width(); nCurrentWidth = nWidth; while(nCurrentWidth < nPixel) { nIndex += Math.max(Math.ceil((nLength - nIndex)/2), 1); welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentWidth = welText.width(); } fCondition = function() { return true; }; } nIndex = welText.html().length - sStringTail.length; while(nCurrentWidth > nPixel) { if (!fCondition()) { break; } nIndex--; welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentWidth = welText.width(); } }, /** * 여러개의 엘리먼트를 각각의 지정된 최대너비로 말줄임한다. * 말줄임할 엘리먼트의 css white-space값이 "nowrap"이어야한다. (컨테이너보다 텍스트가 길면 행변환되지않고 가로로 길게 표현되는 상태) * @param {Array} aElement 말줄임할 엘리먼트의 배열. 지정된 순서대로 말줄임한다. * @param {String} sStringTail 말줄임을 표현할 문자열 (미지정시 ...) * @param {Array} aMinWidth 말줄임할 너비의 배열. * @param {Function} fCondition 조건 함수. 내부에서 true를 리턴하는 동안에만 말줄임을 진행한다. * @example //#a #b #c의 너비를 각각 100, 50, 50픽셀로 줄임 (div#parent 가 200픽셀 이하이면 중단) //#c의 너비를 줄이는 동안 fCondition에서 false를 리턴하면 b, a는 말줄임 되지 않는다. <div id="parent"> <strong id="a">말줄임을적용할내용</strong> <strong id="b">말줄임을적용할내용</strong> <strong id="c">말줄임을적용할내용</strong> <div> ellipsisElementsToDesinatedWidth([jindo.$("c"), jindo.$("b"), jindo.$("a")], "...", [100, 50, 50], function(){ if (jindo.$Element("parent").width() > 200) { return true; } return false; }); */ ellipsisElementsToDesinatedWidth : function(aElement, sStringTail, aMinWidth, fCondition) { jindo.$A(aElement).forEach(function(el, i){ if (!el) { jindo.$A.Continue(); } nhn.husky.SE2M_Utils.ellipsisByPixel(el, sStringTail, aMinWidth[i], fCondition); }); }, /** * 숫자를 입력받아 정해진 길이만큼 앞에 "0"이 추가된 문자열을 구한다. * @param {Number} nNumber * @param {Number} nLength * @return {String} * @example paddingZero(10, 5); ==> "00010" (String) */ paddingZero : function(nNumber, nLength) { var sResult = nNumber.toString(); while (sResult.length < nLength) { sResult = ("0" + sResult); } return sResult; }, /** * string을 byte 단위로 짤라서 tail를 붙힌다. * @param {String} sString * @param {Number} nByte * @param {String} sTail * @example cutStringToByte('일이삼사오육', 6, '...') ==> '일이삼...' (string) */ cutStringToByte : function(sString, nByte, sTail){ if(sString === null || sString.length === 0) { return sString; } sString = sString.replace(/ +/g, " "); if (!sTail && sTail != "") { sTail = "..."; } var maxByte = nByte; var n=0; var nLen = sString.length; for(var i=0; i<nLen;i++){ n += this.getCharByte(sString.charAt(i)); if(n == maxByte){ if(i == nLen-1) { return sString; } else { return sString.substring(0,i)+sTail; } } else if( n > maxByte ) { return sString.substring(0, i)+sTail; } } return sString; }, /** * 입력받은 문자의 byte 구한다. * @param {String} ch * */ getCharByte : function(ch){ if (ch === null || ch.length < 1) { return 0; } var byteSize = 0; var str = escape(ch); if ( str.length == 1 ) { // when English then 1byte byteSize ++; } else if ( str.indexOf("%u") != -1 ) { // when Korean then 2byte byteSize += 2; } else if ( str.indexOf("%") != -1 ) { // else 3byte byteSize += str.length/3; } return byteSize; }, /** * Hash Table에서 원하는 키값만을 가지는 필터된 새로운 Hash Table을 구한다. * @param {HashTable} htUnfiltered * @param {Array} aKey * @return {HashTable} * @author senxation * @example getFilteredHashTable({ a : 1, b : 2, c : 3, d : 4 }, ["a", "c"]); ==> { a : 1, c : 3 } */ getFilteredHashTable : function(htUnfiltered, vKey) { if (!(vKey instanceof Array)) { return arguments.callee.call(this, htUnfiltered, [ vKey ]); } var waKey = jindo.$A(vKey); return jindo.$H(htUnfiltered).filter(function(vValue, sKey){ if (waKey.has(sKey) && vValue) { return true; } else { return false; } }).$value(); }, isBlankNode : function(elNode){ var isBlankTextNode = this.isBlankTextNode; var bEmptyContent = function(elNode){ if(!elNode) { return true; } if(isBlankTextNode(elNode)){ return true; } if(elNode.tagName == "BR") { return true; } if(elNode.innerHTML == "&nbsp;" || elNode.innerHTML == "") { return true; } return false; }; var bEmptyP = function(elNode){ if(elNode.tagName == "IMG" || elNode.tagName == "IFRAME"){ return false; } if(bEmptyContent(elNode)){ return true; } if(elNode.tagName == "P"){ for(var i=elNode.childNodes.length-1; i>=0; i--){ var elTmp = elNode.childNodes[i]; if(isBlankTextNode(elTmp)){ elTmp.parentNode.removeChild(elTmp); } } if(elNode.childNodes.length == 1){ if(elNode.firstChild.tagName == "IMG" || elNode.firstChild.tagName == "IFRAME"){ return false; } if(bEmptyContent(elNode.firstChild)){ return true; } } } return false; }; if(bEmptyP(elNode)){ return true; } for(var i=0, nLen=elNode.childNodes.length; i<nLen; i++){ var elTmp = elNode.childNodes[i]; if(!bEmptyP(elTmp)){ return false; } } return true; }, isBlankTextNode : function(oNode){ var sText; if(oNode.nodeType == 3){ sText = oNode.nodeValue; sText = sText.replace(unescape("%uFEFF"), ''); if(sText == "") { return true; } } return false; }, isFirstChildOfNode : function(sTagName, sParentTagName, elNode){ if(!elNode){ return false; } if(elNode.tagName == sParentTagName && elNode.firstChild.tagName == sTagName){ return true; } return false; }, /** * elNode의 상위 노드 중 태그명이 sTagName과 일치하는 것이 있다면 반환. * @param {String} sTagName 검색 할 태그명 * @param {HTMLElement} elNode 검색 시작점으로 사용 할 노드 * @return {HTMLElement} 부모 노드 중 태그명이 sTagName과 일치하는 노드. 없을 경우 null 반환 */ findAncestorByTagName : function(sTagName, elNode){ while(elNode && elNode.tagName != sTagName) { elNode = elNode.parentNode; } return elNode; }, loadCSS : function(url, fnCallback){ var oDoc = document; var elHead = oDoc.getElementsByTagName("HEAD")[0]; var elStyle = oDoc.createElement ("LINK"); elStyle.setAttribute("type", "text/css"); elStyle.setAttribute("rel", "stylesheet"); elStyle.setAttribute("href", url); if(fnCallback){ if ('onload' in elStyle) { elStyle.onload = function(){ fnCallback(); }; } else { elStyle.onreadystatechange = function(){ if(elStyle.readyState != "complete"){ return; } // [SMARTEDITORSUS-308] [IE9] 응답이 304인 경우 // onreadystatechage 핸들러에서 readyState 가 complete 인 경우가 두 번 발생 // LINK 엘리먼트의 속성으로 콜백 실행 여부를 플래그로 남겨놓아 처리함 if(elStyle.getAttribute("_complete")){ return; } elStyle.setAttribute("_complete", true); fnCallback(); }; } } elHead.appendChild (elStyle); }, getUniqueId : function(sPrefix) { return (sPrefix || '') + jindo.$Date().time() + (Math.random() * 100000).toFixed(); }, /** * @param {Object} oSrc value copy할 object * @return {Object} * @example * var oSource = [1, 3, 4, { a:1, b:2, c: { a:1 }}]; var oTarget = oSource; // call by reference oTarget = nhn.husky.SE2M_Utils.clone(oSource); oTarget[1] = 2; oTarget[3].a = 100; console.log(oSource); // check for deep copy console.log(oTarget, oTarget instanceof Object); // check instance type! */ clone : function(oSrc, oChange) { if ('undefined' != typeof(oSrc) && !!oSrc && (oSrc.constructor == Array || oSrc.constructor == Object)) { var oCopy = (oSrc.constructor == Array ? [] : {} ); for (var property in oSrc) { if ('undefined' != typeof(oChange) && !!oChange[property]) { oCopy[property] = arguments.callee(oChange[property]); } else { oCopy[property] = arguments.callee(oSrc[property]); } } return oCopy; } return oSrc; }, getHtmlTagAttr : function(sHtmlTag, sAttr) { var rx = new RegExp('\\s' + sAttr + "=('([^']*)'|\"([^\"]*)\"|([^\"' >]*))", 'i'); var aResult = rx.exec(sHtmlTag); if (!aResult) { return ''; } var sAttrTmp = (aResult[1] || aResult[2] || aResult[3]); // for chrome 5.x bug! if (!!sAttrTmp) { sAttrTmp = sAttrTmp.replace(/[\"]/g, ''); } return sAttrTmp; }, /** * iframe 영역의 aling 정보를 다시 세팅하는 부분. * iframe 형태의 산출물을 에디터에 삽입 이후에 에디터 정렬기능을 추가 하였을때 ir_to_db 이전 시점에서 div태그에 정렬을 넣어주는 로직임. * 브라우저 형태에 따라 정렬 태그가 iframe을 감싸는 div 혹은 p 태그에 정렬이 추가된다. * @param {HTMLElement} el iframe의 parentNode * @param {Document} oDoc document */ // [COM-1151] SE2M_PreStringConverter 에서 수정하도록 변경 iframeAlignConverter : function(el, oDoc){ var sTagName = el.tagName.toUpperCase(); if(sTagName == "DIV" || sTagName == 'P'){ //irToDbDOM 에서 최상위 노드가 div 엘리먼트 이므로 parentNode가 없으면 최상의 div 노드 이므로 리턴한다. if(el.parentNode === null ){ return; } var elWYSIWYGDoc = oDoc; var wel = jindo.$Element(el); var sHtml = wel.html(); //현재 align을 얻어오기. var sAlign = jindo.$Element(el).attr('align') || jindo.$Element(el).css('text-align'); //if(!sAlign){ // P > DIV의 경우 문제 발생, 수정 화면에 들어 왔을 때 태그 깨짐 // return; //} //새로운 div 노드 생성한다. var welAfter = jindo.$Element(jindo.$('<div></div>', elWYSIWYGDoc)); welAfter.html(sHtml).attr('align', sAlign); wel.replace(welAfter); } }, /** * jindo.$JSON.fromXML을 변환한 메서드. * 소숫점이 있는 경우의 처리 시에 숫자로 변환하지 않도록 함(parseFloat 사용 안하도록 수정) * 관련 BTS : [COM-1093] * @param {String} sXML XML 형태의 문자열 * @return {jindo.$JSON} */ getJsonDatafromXML : function(sXML) { var o = {}; var re = /\s*<(\/?[\w:\-]+)((?:\s+[\w:\-]+\s*=\s*(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'))*)\s*((?:\/>)|(?:><\/\1>|\s*))|\s*<!\[CDATA\[([\w\W]*?)\]\]>\s*|\s*>?([^<]*)/ig; var re2= /^[0-9]+(?:\.[0-9]+)?$/; var re3= /^\s+$/g; var ec = {"&amp;":"&","&nbsp;":" ","&quot;":"\"","&lt;":"<","&gt;":">"}; var fg = {tags:["/"],stack:[o]}; var es = function(s){ if (typeof s == "undefined") { return ""; } return s.replace(/&[a-z]+;/g, function(m){ return (typeof ec[m] == "string")?ec[m]:m; }); }; var at = function(s,c) { s.replace(/([\w\:\-]+)\s*=\s*(?:"((?:\\"|[^"])*)"|'((?:\\'|[^'])*)')/g, function($0,$1,$2,$3) { c[$1] = es(($2?$2.replace(/\\"/g,'"'):undefined)||($3?$3.replace(/\\'/g,"'"):undefined)); }); }; var em = function(o) { for(var x in o){ if (o.hasOwnProperty(x)) { if(Object.prototype[x]) { continue; } return false; } } return true; }; // $0 : 전체 // $1 : 태그명 // $2 : 속성문자열 // $3 : 닫는태그 // $4 : CDATA바디값 // $5 : 그냥 바디값 var cb = function($0,$1,$2,$3,$4,$5) { var cur, cdata = ""; var idx = fg.stack.length - 1; if (typeof $1 == "string" && $1) { if ($1.substr(0,1) != "/") { var has_attr = (typeof $2 == "string" && $2); var closed = (typeof $3 == "string" && $3); var newobj = (!has_attr && closed)?"":{}; cur = fg.stack[idx]; if (typeof cur[$1] == "undefined") { cur[$1] = newobj; cur = fg.stack[idx+1] = cur[$1]; } else if (cur[$1] instanceof Array) { var len = cur[$1].length; cur[$1][len] = newobj; cur = fg.stack[idx+1] = cur[$1][len]; } else { cur[$1] = [cur[$1], newobj]; cur = fg.stack[idx+1] = cur[$1][1]; } if (has_attr) { at($2,cur); } fg.tags[idx+1] = $1; if (closed) { fg.tags.length--; fg.stack.length--; } } else { fg.tags.length--; fg.stack.length--; } } else if (typeof $4 == "string" && $4) { cdata = $4; } else if (typeof $5 == "string" && $5.replace(re3, "")) { // [SMARTEDITORSUS-1525] 닫는 태그인데 공백문자가 들어있어 cdata 값을 덮어쓰는 경우 방지 cdata = es($5); } if (cdata.length > 0) { var par = fg.stack[idx-1]; var tag = fg.tags[idx]; if (re2.test(cdata)) { //cdata = parseFloat(cdata); }else if (cdata == "true" || cdata == "false"){ cdata = new Boolean(cdata); } if(typeof par =='undefined') { return; } if (par[tag] instanceof Array) { var o = par[tag]; if (typeof o[o.length-1] == "object" && !em(o[o.length-1])) { o[o.length-1].$cdata = cdata; o[o.length-1].toString = function(){ return cdata; }; } else { o[o.length-1] = cdata; } } else { if (typeof par[tag] == "object" && !em(par[tag])) { par[tag].$cdata = cdata; par[tag].toString = function() { return cdata; }; } else { par[tag] = cdata; } } } }; sXML = sXML.replace(/<(\?|\!-)[^>]*>/g, ""); sXML.replace(re, cb); return jindo.$Json(o); } }; /** * nhn.husky.AutoResizer * HTML모드와 TEXT 모드의 편집 영역인 TEXTAREA에 대한 자동확장 처리 */ nhn.husky.AutoResizer = jindo.$Class({ welHiddenDiv : null, welCloneDiv : null, elContainer : null, $init : function(el, htOption){ var aCopyStyle = [ 'lineHeight', 'textDecoration', 'letterSpacing', 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust', 'paddingTop', 'paddingLeft', 'paddingBottom', 'paddingRight', 'width' ], i = aCopyStyle.length, oCss = { "position" : "absolute", "top" : -9999, "left" : -9999, "opacity": 0, "overflow": "hidden", "wordWrap" : "break-word" }; this.nMinHeight = htOption.nMinHeight; this.wfnCallback = htOption.wfnCallback; this.elContainer = el.parentNode; this.welTextArea = jindo.$Element(el); // autoresize를 적용할 TextArea this.welHiddenDiv = jindo.$Element('<div>'); this.wfnResize = jindo.$Fn(this._resize, this); this.sOverflow = this.welTextArea.css("overflow"); this.welTextArea.css("overflow", "hidden"); while(i--){ oCss[aCopyStyle[i]] = this.welTextArea.css(aCopyStyle[i]); } this.welHiddenDiv.css(oCss); this.nLastHeight = this.welTextArea.height(); }, bind : function(){ this.welCloneDiv = jindo.$Element(this.welHiddenDiv.$value().cloneNode(false)); this.wfnResize.attach(this.welTextArea, "keyup"); this.welCloneDiv.appendTo(this.elContainer); this._resize(); }, unbind : function(){ this.wfnResize.detach(this.welTextArea, "keyup"); this.welTextArea.css("overflow", this.sOverflow); if(this.welCloneDiv){ this.welCloneDiv.leave(); } }, _resize : function(){ var sContents = this.welTextArea.$value().value, bExpand = false, nHeight; if(sContents === this.sContents){ return; } this.sContents = sContents.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;').replace(/\n/g, '<br>'); this.sContents += "<br>"; // 마지막 개행 뒤에 <br>을 더 붙여주어야 늘어나는 높이가 동일함 this.welCloneDiv.html(this.sContents); nHeight = this.welCloneDiv.height(); if(nHeight < this.nMinHeight){ nHeight = this.nMinHeight; } this.welTextArea.css("height", nHeight + "px"); this.elContainer.style.height = nHeight + "px"; if(this.nLastHeight < nHeight){ bExpand = true; } this.wfnCallback(bExpand); } }); /** * 문자를 연결하는 '+' 대신에 java와 유사하게 처리하도록 문자열 처리하도록 만드는 object * @author nox * @example var sTmp1 = new StringBuffer(); sTmp1.append('1').append('2').append('3'); var sTmp2 = new StringBuffer('1'); sTmp2.append('2').append('3'); var sTmp3 = new StringBuffer('1').append('2').append('3'); */ if ('undefined' != typeof(StringBuffer)) { StringBuffer = {}; } StringBuffer = function(str) { this._aString = []; if ('undefined' != typeof(str)) { this.append(str); } }; StringBuffer.prototype.append = function(str) { this._aString.push(str); return this; }; StringBuffer.prototype.toString = function() { return this._aString.join(''); }; StringBuffer.prototype.setLength = function(nLen) { if('undefined' == typeof(nLen) || 0 >= nLen) { this._aString.length = 0; } else { this._aString.length = nLen; } }; /** * Installed Font Detector * @author hooriza * * @see http://remysharp.com/2008/07/08/how-to-detect-if-a-font-is-installed-only-using-javascript/ */ (function() { var oDummy = null, rx = /,/gi; IsInstalledFont = function(sFont) { var sDefFont = sFont == 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; if (!oDummy) { oDummy = document.createElement('div'); } var sStyle = 'position:absolute !important; font-size:200px !important; left:-9999px !important; top:-9999px !important;'; oDummy.innerHTML = 'mmmmiiiii'+unescape('%uD55C%uAE00'); oDummy.style.cssText = sStyle + 'font-family:"' + sDefFont + '" !important'; var elBody = document.body || document.documentElement; if(elBody.firstChild){ elBody.insertBefore(oDummy, elBody.firstChild); }else{ document.body.appendChild(oDummy); } var sOrg = oDummy.offsetWidth + '-' + oDummy.offsetHeight; oDummy.style.cssText = sStyle + 'font-family:"' + sFont.replace(rx, '","') + '", "' + sDefFont + '" !important'; var bInstalled = sOrg != (oDummy.offsetWidth + '-' + oDummy.offsetHeight); document.body.removeChild(oDummy); return bInstalled; }; })(); //{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to string conversion. Ususally used to convert the IR value. * @name hp_StringConverterManager.js */ nhn.husky.StringConverterManager = jindo.$Class({ name : "StringConverterManager", oConverters : null, $init : function(){ this.oConverters = {}; this.oConverters_DOM = {}; this.oAgent = jindo.$Agent().navigator(); }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["applyConverter", jindo.$Fn(this.applyConverter, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["addConverter", jindo.$Fn(this.addConverter, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["addConverter_DOM", jindo.$Fn(this.addConverter_DOM, this).bind()]); }, applyConverter : function(sRuleName, sContents, oDocument){ //string을 넣는 이유:IE의 경우,본문 앞에 있는 html 주석이 삭제되는 경우가 있기때문에 임시 string을 추가해준것임. var sTmpStr = "@"+(new Date()).getTime()+"@"; var rxTmpStr = new RegExp(sTmpStr, "g"); var oRes = {sContents:sTmpStr+sContents}; oDocument = oDocument || document; this.oApp.exec("MSG_STRING_CONVERTER_STARTED", [sRuleName, oRes]); // this.oApp.exec("MSG_STRING_CONVERTER_STARTED_"+sRuleName, [oRes]); var aConverters; sContents = oRes.sContents; aConverters = this.oConverters_DOM[sRuleName]; if(aConverters){ var elContentsHolder = oDocument.createElement("DIV"); elContentsHolder.innerHTML = sContents; for(var i=0; i<aConverters.length; i++){ aConverters[i](elContentsHolder); } sContents = elContentsHolder.innerHTML; // 내용물에 EMBED등이 있을 경우 IE에서 페이지 나갈 때 권한 오류 발생 할 수 있어 명시적으로 노드 삭제. if(!!elContentsHolder.parentNode){ elContentsHolder.parentNode.removeChild(elContentsHolder); } elContentsHolder = null; //IE의 경우, sContents를 innerHTML로 넣는 경우 string과 <p>tag 사이에 '\n\'개행문자를 넣어준다. if( jindo.$Agent().navigator().ie ){ sTmpStr = sTmpStr +'(\r\n)?'; //ie+win에서는 개행이 \r\n로 들어감. rxTmpStr = new RegExp(sTmpStr , "g"); } } aConverters = this.oConverters[sRuleName]; if(aConverters){ for(var i=0; i<aConverters.length; i++){ var sTmpContents = aConverters[i](sContents); if(typeof sTmpContents != "undefined"){ sContents = sTmpContents; } } } oRes = {sContents:sContents}; this.oApp.exec("MSG_STRING_CONVERTER_ENDED", [sRuleName, oRes]); oRes.sContents = oRes.sContents.replace(rxTmpStr, ""); return oRes.sContents; }, $ON_ADD_CONVERTER : function(sRuleName, funcConverter){ var aCallerStack = this.oApp.aCallerStack; funcConverter.sPluginName = aCallerStack[aCallerStack.length-2].name; this.addConverter(sRuleName, funcConverter); }, $ON_ADD_CONVERTER_DOM : function(sRuleName, funcConverter){ var aCallerStack = this.oApp.aCallerStack; funcConverter.sPluginName = aCallerStack[aCallerStack.length-2].name; this.addConverter_DOM(sRuleName, funcConverter); }, addConverter : function(sRuleName, funcConverter){ var aConverters = this.oConverters[sRuleName]; if(!aConverters){ this.oConverters[sRuleName] = []; } this.oConverters[sRuleName][this.oConverters[sRuleName].length] = funcConverter; }, addConverter_DOM : function(sRuleName, funcConverter){ var aConverters = this.oConverters_DOM[sRuleName]; if(!aConverters){ this.oConverters_DOM[sRuleName] = []; } this.oConverters_DOM[sRuleName][this.oConverters_DOM[sRuleName].length] = funcConverter; } }); //} /*[ * ATTACH_HOVER_EVENTS * * 주어진 HTML엘리먼트에 Hover 이벤트 발생시 특정 클래스가 할당 되도록 설정 * * aElms array Hover 이벤트를 걸 HTML Element 목록 * sHoverClass string Hover 시에 할당 할 클래스 * ---------------------------------------------------------------------------]*/ /** * @pluginDesc Husky Framework에서 자주 사용되는 유틸성 메시지를 처리하는 플러그인 */ nhn.husky.Utils = jindo.$Class({ name : "Utils", $init : function(){ var oAgentInfo = jindo.$Agent(); var oNavigatorInfo = oAgentInfo.navigator(); if(oNavigatorInfo.ie && oNavigatorInfo.version == 6){ try{ document.execCommand('BackgroundImageCache', false, true); }catch(e){} } }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["htBrowser", jindo.$Agent().navigator()]); }, $ON_ATTACH_HOVER_EVENTS : function(aElms, htOptions){ htOptions = htOptions || []; var sHoverClass = htOptions.sHoverClass || "hover"; var fnElmToSrc = htOptions.fnElmToSrc || function(el){return el}; var fnElmToTarget = htOptions.fnElmToTarget || function(el){return el}; if(!aElms) return; var wfAddClass = jindo.$Fn(function(wev){ jindo.$Element(fnElmToTarget(wev.currentElement)).addClass(sHoverClass); }, this); var wfRemoveClass = jindo.$Fn(function(wev){ jindo.$Element(fnElmToTarget(wev.currentElement)).removeClass(sHoverClass); }, this); for(var i=0, len = aElms.length; i<len; i++){ var elSource = fnElmToSrc(aElms[i]); wfAddClass.attach(elSource, "mouseover"); wfRemoveClass.attach(elSource, "mouseout"); wfAddClass.attach(elSource, "focus"); wfRemoveClass.attach(elSource, "blur"); } } }); /*[ * SE_FIT_IFRAME * * 스마트에디터 사이즈에 맞게 iframe사이즈를 조절한다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc 에디터를 싸고 있는 iframe 사이즈 조절을 담당하는 플러그인 */ nhn.husky.SE_OuterIFrameControl = $Class({ name : "SE_OuterIFrameControl", oResizeGrip : null, $init : function(oAppContainer){ // page up, page down, home, end, left, up, right, down this.aHeightChangeKeyMap = [-100, 100, 500, -500, -1, -10, 1, 10]; this._assignHTMLObjects(oAppContainer); //키보드 이벤트 this.$FnKeyDown = $Fn(this._keydown, this); if(this.oResizeGrip){ this.$FnKeyDown.attach(this.oResizeGrip, "keydown"); } //마우스 이벤트 if(!!jindo.$Agent().navigator().ie){ this.$FnMouseDown = $Fn(this._mousedown, this); this.$FnMouseMove = $Fn(this._mousemove, this); this.$FnMouseMove_Parent = $Fn(this._mousemove_parent, this); this.$FnMouseUp = $Fn(this._mouseup, this); if(this.oResizeGrip){ this.$FnMouseDown.attach(this.oResizeGrip, "mousedown"); } } }, _assignHTMLObjects : function(oAppContainer){ oAppContainer = $(oAppContainer) || document; this.oResizeGrip = cssquery.getSingle(".husky_seditor_editingArea_verticalResizer", oAppContainer); this.elIFrame = window.frameElement; this.welIFrame = $Element(this.elIFrame); }, $ON_MSG_APP_READY : function(){ this.oApp.exec("SE_FIT_IFRAME", []); }, $ON_MSG_EDITING_AREA_SIZE_CHANGED : function(){ this.oApp.exec("SE_FIT_IFRAME", []); }, $ON_SE_FIT_IFRAME : function(){ this.elIFrame.style.height = document.body.offsetHeight+"px"; }, $AFTER_RESIZE_EDITING_AREA_BY : function(ipWidthChange, ipHeightChange){ this.oApp.exec("SE_FIT_IFRAME", []); }, _keydown : function(oEvent){ var oKeyInfo = oEvent.key(); // 33, 34: page up/down, 35,36: end/home, 37,38,39,40: left, up, right, down if(oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40){ this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED", []); this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, this.aHeightChangeKeyMap[oKeyInfo.keyCode-33]]); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED", []); oEvent.stop(); } }, _mousedown : function(oEvent){ this.iStartHeight = oEvent.pos().clientY; this.iStartHeightOffset = oEvent.pos().layerY; this.$FnMouseMove.attach(document, "mousemove"); this.$FnMouseMove_Parent.attach(parent.document, "mousemove"); this.$FnMouseUp.attach(document, "mouseup"); this.$FnMouseUp.attach(parent.document, "mouseup"); this.iStartHeight = oEvent.pos().clientY; this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); }, _mousemove : function(oEvent){ var iHeightChange = oEvent.pos().clientY - this.iStartHeight; this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, iHeightChange]); }, _mousemove_parent : function(oEvent){ var iHeightChange = oEvent.pos().pageY - (this.welIFrame.offset().top + this.iStartHeight); this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, iHeightChange]); }, _mouseup : function(oEvent){ this.$FnMouseMove.detach(document, "mousemove"); this.$FnMouseMove_Parent.detach(parent.document, "mousemove"); this.$FnMouseUp.detach(document, "mouseup"); this.$FnMouseUp.detach(parent.document, "mouseup"); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); } }); // Sample plugin. Use CTRL+T to toggle the toolbar nhn.husky.SE_ToolbarToggler = $Class({ name : "SE_ToolbarToggler", bUseToolbar : true, $init : function(oAppContainer, bUseToolbar){ this._assignHTMLObjects(oAppContainer, bUseToolbar); }, _assignHTMLObjects : function(oAppContainer, bUseToolbar){ oAppContainer = $(oAppContainer) || document; this.toolbarArea = cssquery.getSingle(".se2_tool", oAppContainer); //설정이 없거나, 사용하겠다고 표시한 경우 block 처리 if( typeof(bUseToolbar) == 'undefined' || bUseToolbar === true){ this.toolbarArea.style.display = "block"; }else{ this.toolbarArea.style.display = "none"; } }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_HOTKEY", ["ctrl+t", "SE_TOGGLE_TOOLBAR", []]); }, $ON_SE_TOGGLE_TOOLBAR : function(){ this.toolbarArea.style.display = (this.toolbarArea.style.display == "none")?"block":"none"; this.oApp.exec("MSG_EDITING_AREA_SIZE_CHANGED", []); } }); //{ /** * @fileOverview This file contains Husky plugin that takes care of loading css files dynamically * @name hp_SE2B_CSSLoader.js */ nhn.husky.SE2B_CSSLoader = jindo.$Class({ name : "SE2B_CSSLoader", bCssLoaded : false, // load & continue with the message right away. aInstantLoadTrigger : ["OPEN_QE_LAYER", "SHOW_ACTIVE_LAYER", "SHOW_DIALOG_LAYER"], // if a rendering bug occurs in IE, give some delay before continue processing the message. aDelayedLoadTrigger : ["MSG_SE_OBJECT_EDIT_REQUESTED", "OBJECT_MODIFY", "MSG_SE_DUMMY_OBJECT_EDIT_REQUESTED", "TOGGLE_TOOLBAR_ACTIVE_LAYER", "SHOW_TOOLBAR_ACTIVE_LAYER"], $init : function(){ this.htOptions = nhn.husky.SE2M_Configuration.SE2B_CSSLoader; // only IE's slow if(!jindo.$Agent().navigator().ie){ this.loadSE2CSS(); }else{ for(var i=0, nLen = this.aInstantLoadTrigger.length; i<nLen; i++){ this["$BEFORE_"+this.aInstantLoadTrigger[i]] = jindo.$Fn(function(){ this.loadSE2CSS(); }, this).bind(); } for(var i=0, nLen = this.aDelayedLoadTrigger.length; i<nLen; i++){ var sMsg = this.aDelayedLoadTrigger[i]; this["$BEFORE_"+this.aDelayedLoadTrigger[i]] = jindo.$Fn(function(sMsg){ var aArgs = jindo.$A(arguments).$value(); aArgs = aArgs.splice(1, aArgs.length-1); return this.loadSE2CSS(sMsg, aArgs); }, this).bind(sMsg); } } }, /* $BEFORE_REEDIT_ITEM_ACTION : function(){ return this.loadSE2CSS("REEDIT_ITEM_ACTION", arguments); }, $BEFORE_OBJECT_MODIFY : function(){ return this.loadSE2CSS("OBJECT_MODIFY", arguments); }, $BEFORE_MSG_SE_DUMMY_OBJECT_EDIT_REQUESTED : function(){ return this.loadSE2CSS("MSG_SE_DUMMY_OBJECT_EDIT_REQUESTED", arguments); }, $BEFORE_TOGGLE_DBATTACHMENT_LAYER : function(){ return this.loadSE2CSS("TOGGLE_DBATTACHMENT_LAYER", arguments); }, $BEFORE_SHOW_WRITE_REVIEW_DESIGN_SELECT_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_OPEN_QE_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_TOGGLE_TOOLBAR_ACTIVE_LAYER : function(){ return this.loadSE2CSS("TOGGLE_TOOLBAR_ACTIVE_LAYER", arguments); }, $BEFORE_SHOW_TOOLBAR_ACTIVE_LAYER : function(){ return this.loadSE2CSS("SHOW_TOOLBAR_ACTIVE_LAYER", arguments); }, $BEFORE_SHOW_ACTIVE_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_SHOW_DIALOG_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_TOGGLE_ITEM_LAYER : function(){ return this.loadSE2CSS("TOGGLE_ITEM_LAYER", arguments); }, */ // if a rendering bug occurs in IE, pass sMsg and oArgs to give some delay before the message is processed. loadSE2CSS : function(sMsg, oArgs){ if(this.bCssLoaded){return true;} this.bCssLoaded = true; var fnCallback = null; if(sMsg){ fnCallback = jindo.$Fn(this.oApp.exec, this.oApp).bind(sMsg, oArgs); } //nhn.husky.SE2M_Utils.loadCSS("css/smart_editor2.css"); nhn.husky.SE2M_Utils.loadCSS(this.htOptions.sCSSBaseURI+"/smart_editor2_items.css", fnCallback); return false; } }); //} /** * @name nhn.husky.SE2B_Customize_ToolBar * @description 메일 전용 커스터마이즈 툴바로 더보기 레이어 관리만을 담당하고 있음. * @class * @author HyeKyoung,NHN AjaxUI Lab, CMD Division * @version 0.1.0 * @since */ nhn.husky.SE2B_Customize_ToolBar = jindo.$Class(/** @lends nhn.husky.SE2B_Customize_ToolBar */{ name : "SE2B_Customize_ToolBar", /** * @constructs * @param {Object} oAppContainer 에디터를 구성하는 컨테이너 */ $init : function(oAppContainer) { this._assignHTMLElements(oAppContainer); }, $BEFORE_MSG_APP_READY : function(){ this._addEventMoreButton(); }, /** * @private * @description DOM엘리먼트를 수집하는 메소드 * @param {Object} oAppContainer 툴바 포함 에디터를 감싸고 있는 div 엘리먼트 */ _assignHTMLElements : function(oAppContainer) { this.oAppContainer = oAppContainer; this.elTextToolBarArea = jindo.$$.getSingle("div.se2_tool"); this.elTextMoreButton = jindo.$$.getSingle("button.se2_text_tool_more", this.elTextToolBarArea); this.elTextMoreButtonParent = this.elTextMoreButton.parentNode; this.welTextMoreButtonParent = jindo.$Element(this.elTextMoreButtonParent); this.elMoreLayer = jindo.$$.getSingle("div.se2_sub_text_tool"); }, _addEventMoreButton : function (){ this.oApp.registerBrowserEvent(this.elTextMoreButton, "click", "EVENT_CLICK_EXPAND_VIEW"); this.oApp.registerBrowserEvent(this.elMoreLayer, "click", "EVENT_CLICK_EXPAND_VIEW"); }, $ON_EVENT_CLICK_EXPAND_VIEW : function(weEvent){ this.oApp.exec("TOGGLE_EXPAND_VIEW", [this.elTextMoreButton]); weEvent.stop(); }, $ON_TOGGLE_EXPAND_VIEW : function(){ if(!this.welTextMoreButtonParent.hasClass("active")){ this.oApp.exec("SHOW_EXPAND_VIEW"); } else { this.oApp.exec("HIDE_EXPAND_VIEW"); } }, $ON_CHANGE_EDITING_MODE : function(sMode){ if(sMode != "WYSIWYG"){ this.elTextMoreButton.disabled =true; this.welTextMoreButtonParent.removeClass("active"); this.oApp.exec("HIDE_EXPAND_VIEW"); }else{ this.elTextMoreButton.disabled =false; } }, $AFTER_SHOW_ACTIVE_LAYER : function(){ this.oApp.exec("HIDE_EXPAND_VIEW"); }, $AFTER_SHOW_DIALOG_LAYER : function(){ this.oApp.exec("HIDE_EXPAND_VIEW"); }, $ON_SHOW_EXPAND_VIEW : function(){ this.welTextMoreButtonParent.addClass("active"); this.elMoreLayer.style.display = "block"; }, $ON_HIDE_EXPAND_VIEW : function(){ this.welTextMoreButtonParent.removeClass("active"); this.elMoreLayer.style.display = "none"; }, /** * CHANGE_EDITING_MODE모드 이후에 호출되어야 함. * WYSIWYG 모드가 활성화되기 전에 호출이 되면 APPLY_FONTCOLOR에서 에러 발생. */ $ON_RESET_TOOLBAR : function(){ if(this.oApp.getEditingMode() !== "WYSIWYG"){ return; } //스펠체크 닫기 this.oApp.exec("END_SPELLCHECK"); //열린 팝업을 닫기 위해서 this.oApp.exec("DISABLE_ALL_UI"); this.oApp.exec("ENABLE_ALL_UI"); //글자색과 글자 배경색을 제외한 세팅 this.oApp.exec("RESET_STYLE_STATUS"); this.oApp.exec("CHECK_STYLE_CHANGE"); //최근 사용한 글자색 셋팅. this.oApp.exec("APPLY_FONTCOLOR", ["#000000"]); //더보기 영역 닫기. this.oApp.exec("HIDE_EXPAND_VIEW"); } }); if(typeof window.nhn=='undefined'){window.nhn = {};} /** * @fileOverview This file contains a message mapping(Korean), which is used to map the message code to the actual message * @name husky_SE2B_Lang_ko_KR.js * @ unescape */ var oMessageMap = { 'SE_EditingAreaManager.onExit' : '내용이 변경되었습니다.', 'SE_Color.invalidColorCode' : '색상 코드를 올바르게 입력해 주세요. \n\n 예) #000000, #FF0000, #FFFFFF, #ffffff, ffffff', 'SE_Hyperlink.invalidURL' : '입력하신 URL이 올바르지 않습니다.', 'SE_FindReplace.keywordMissing' : '찾으실 단어를 입력해 주세요.', 'SE_FindReplace.keywordNotFound' : '찾으실 단어가 없습니다.', 'SE_FindReplace.replaceAllResultP1' : '일치하는 내용이 총 ', 'SE_FindReplace.replaceAllResultP2' : '건 바뀌었습니다.', 'SE_FindReplace.notSupportedBrowser' : '현재 사용하고 계신 브라우저에서는 사용하실수 없는 기능입니다.\n\n이용에 불편을 드려 죄송합니다.', 'SE_FindReplace.replaceKeywordNotFound' : '바뀔 단어가 없습니다', 'SE_LineHeight.invalidLineHeight' : '잘못된 값입니다.', 'SE_Footnote.defaultText' : '각주내용을 입력해 주세요', 'SE.failedToLoadFlash' : '플래시가 차단되어 있어 해당 기능을 사용할 수 없습니다.', 'SE2M_EditingModeChanger.confirmTextMode' : '텍스트 모드로 전환하면 작성된 내용은 유지되나, \n\n글꼴 등의 편집효과와 이미지 등의 첨부내용이 모두 사라지게 됩니다.\n\n전환하시겠습니까?', 'SE2M_FontNameWithLayerUI.sSampleText' : '가나다라' };
31.628775
938
0.650552
1e04ad96e2ae99e0b6e2bc9e1f6ab82f4e886042
652
js
JavaScript
rollup.config.js
zss1004504439/npm-test
ebb8d8b222cee0e89458cdf82095cadecb9a24a4
[ "MIT" ]
1
2021-12-21T01:08:18.000Z
2021-12-21T01:08:18.000Z
rollup.config.js
zss1004504439/npm-test
ebb8d8b222cee0e89458cdf82095cadecb9a24a4
[ "MIT" ]
null
null
null
rollup.config.js
zss1004504439/npm-test
ebb8d8b222cee0e89458cdf82095cadecb9a24a4
[ "MIT" ]
1
2021-12-21T01:08:02.000Z
2021-12-21T01:08:02.000Z
import babel from "rollup-plugin-babel" // 压缩 import { terser } from "rollup-plugin-terser" // 输出文件夹清除 import del from 'rollup-plugin-delete' const path = require('path') const resolve = function (filePath) { return path.join(__dirname, filePath) } export default { input: resolve('/src/index.js'), // 入口文件 output: [{ // 出口文件 file: resolve('dist/index.min.js'), format: 'umd', name: 'npm-lib', }], plugins: [ del({ targets: ["dist"] }), babel({ exclude: 'node_modules/**', runtimeHelpers: true }), terser() ], external: [] }
19.757576
44
0.544479
1e04bbb2899b1b58843ed2c8c059964787d387c9
233
js
JavaScript
src/internal/bindings/bindingArguments/bindingArgument.js
TimHambourger/superinject
42b8edf927bd9596f253fe8c7576b50e0658de05
[ "MIT" ]
null
null
null
src/internal/bindings/bindingArguments/bindingArgument.js
TimHambourger/superinject
42b8edf927bd9596f253fe8c7576b50e0658de05
[ "MIT" ]
null
null
null
src/internal/bindings/bindingArguments/bindingArgument.js
TimHambourger/superinject
42b8edf927bd9596f253fe8c7576b50e0658de05
[ "MIT" ]
null
null
null
module.exports = BindingArgument; function BindingArgument() { } // Abstract. Subclasses MUST override. // scope -- {Scope} BindingArgument.prototype.activate = function (scope) { throw new Error('Method not implemented.'); };
23.3
55
0.725322
1e052d421fe17ba8bf642c77676f61b44fd70f0a
904
js
JavaScript
client/tests/controllers/ProductController.test.js
davidnadeau/shopping-cart
4939eabceb9eab8c8a074e40b8d5c589a7fb93a7
[ "MIT" ]
1
2015-04-06T14:29:11.000Z
2015-04-06T14:29:11.000Z
client/tests/controllers/ProductController.test.js
davidnadeau/shopping-cart
4939eabceb9eab8c8a074e40b8d5c589a7fb93a7
[ "MIT" ]
null
null
null
client/tests/controllers/ProductController.test.js
davidnadeau/shopping-cart
4939eabceb9eab8c8a074e40b8d5c589a7fb93a7
[ "MIT" ]
null
null
null
describe("Product Controller", function() { var $rootScope, $scope, $controller; beforeEach(module('dnStore.shoppingCart')); beforeEach(inject(function(_$rootScope_, _$controller_){ $rootScope = _$rootScope_; $scope = $rootScope.$new(); $controller = _$controller_; $controller('ProductController', {'$rootScope' : $rootScope, '$scope': $scope}); })); describe("When initializing", function() { it("should have no items", function () { expect($scope.products).toEqual( [] ); }); it("should hide the back button", function () { expect($scope.$parent.backButtonVisible).toEqual( false ); }); }); describe("When loaded", function() { it("should only allow valid quantities", function () { expect($scope.isValidQuantity("aaa")).toEqual( false ); expect($scope.isValidQuantity(0)).toEqual( false ); expect($scope.isValidQuantity(1)).toEqual( true ); }); }); });
30.133333
82
0.668142
1e05ed8d5ebf62cc80c8e391d64c7519336be092
555
js
JavaScript
modules/SinglePostsDisplay.js
KnottStudios/ReactBlogExample
cea8cc7068c692faad8eddfde15893ac4cc02574
[ "MIT" ]
null
null
null
modules/SinglePostsDisplay.js
KnottStudios/ReactBlogExample
cea8cc7068c692faad8eddfde15893ac4cc02574
[ "MIT" ]
null
null
null
modules/SinglePostsDisplay.js
KnottStudios/ReactBlogExample
cea8cc7068c692faad8eddfde15893ac4cc02574
[ "MIT" ]
null
null
null
import React from 'react'; import { SinglePost } from './SinglePost'; export class SinglePostsDisplay extends React.Component { render(){ var ids = []; var i; for(i = 1; i < 3; i++){ ids.push(i) } var blogs = ids.map(function(id, index){ return <div key={ index }><SinglePost id={id}/></div>; }) return ( <div className="content box"> <h3>Single Blogs</h3> {blogs} </div> ) }; }
25.227273
67
0.443243
1e062e2c65350e0ce789df5d0145e0dddc864997
3,056
js
JavaScript
src/js/src/Emitter.js
movinliao/movin-events
e2241cfa9577ab4e13ce18bbff93c6be54032638
[ "Apache-2.0" ]
null
null
null
src/js/src/Emitter.js
movinliao/movin-events
e2241cfa9577ab4e13ce18bbff93c6be54032638
[ "Apache-2.0" ]
null
null
null
src/js/src/Emitter.js
movinliao/movin-events
e2241cfa9577ab4e13ce18bbff93c6be54032638
[ "Apache-2.0" ]
null
null
null
/** * Expose `Emitter`. * https://github.com/npmcomponent/component-emitter */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; };
18.521212
60
0.625327
1e06339c0388e996b5259b2992142b5d5936272e
4,472
js
JavaScript
config/http.js
ValiantLucatero/PFSails
dd21ddf26bdd598471d2adf1421f1bd0570dc44c
[ "MIT" ]
1
2020-08-07T15:46:50.000Z
2020-08-07T15:46:50.000Z
config/http.js
ValiantLucatero/PFSails
dd21ddf26bdd598471d2adf1421f1bd0570dc44c
[ "MIT" ]
2
2017-07-03T04:53:06.000Z
2021-08-31T23:26:29.000Z
config/http.js
ValiantLucatero/PFSails
dd21ddf26bdd598471d2adf1421f1bd0570dc44c
[ "MIT" ]
1
2020-09-11T03:20:57.000Z
2020-09-11T03:20:57.000Z
/** * HTTP Server Settings * (sails.config.http) * * Configuration for the underlying HTTP server in Sails. * Only applies to HTTP requests (not WebSockets) * * For more information on configuration, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.http.html */ module.exports.http = { /**************************************************************************** * * * Express middleware to use for every Sails request. To add custom * * middleware to the mix, add a function to the middleware config object and * * add its key to the "order" array. The $custom key is reserved for * * backwards-compatibility with Sails v0.9.x apps that use the * * `customMiddleware` config option. * * * ****************************************************************************/ middleware: { passportInit : require('passport').initialize(), passportSession : require('passport').session(), /*************************************************************************** * * * The order in which middleware should be run for HTTP request. (the Sails * * router is invoked by the "router" middleware below.) * * * ***************************************************************************/ order: [ 'startRequestTimer', 'cookieParser', 'session', 'passportInit', 'passportSession', 'myRequestLogger', 'bodyParser', 'handleBodyParserError', 'compress', 'methodOverride', 'poweredBy', '$custom', 'router', 'www', 'favicon', '404', '500' ], /**************************************************************************** * * * Example custom middleware; logs each request to the console. * * * ****************************************************************************/ // myRequestLogger: function (req, res, next) { // console.log("Requested :: ", req.method, req.url); // return next(); // } /*************************************************************************** * * * The body parser that will handle incoming multipart HTTP requests. By * * default as of v0.10, Sails uses * * [skipper](http://github.com/balderdashy/skipper). See * * http://www.senchalabs.org/connect/multipart.html for other options. * * * * Note that Sails uses an internal instance of Skipper by default; to * * override it and specify more options, make sure to "npm install skipper" * * in your project first. You can also specify a different body parser or * * a custom function with req, res and next parameters (just like any other * * middleware function). * * * ***************************************************************************/ // bodyParser: require('skipper')({strict: true}) }, /*************************************************************************** * * * The number of seconds to cache flat files on disk being served by * * Express static middleware (by default, these files are in `.tmp/public`) * * * * The HTTP static cache is only active in a 'production' environment, * * since that's the only time Express will cache flat-files. * * * ***************************************************************************/ // cache: 31557600000 };
45.632653
84
0.368068
1e069ec4e0c676056dc518705e6e4fb8831eea10
29,955
js
JavaScript
hackCu/core/gesture.js
AM-Mahon/HackCU-EC
354e6e49ac1f09eff7c61f3815630361bda1ba5a
[ "Unlicense", "MIT" ]
16
2016-11-16T08:56:14.000Z
2021-04-30T02:49:26.000Z
core/gesture.js
JBBlunderbuss/blockly
d5834c5b785e920f1116c193c0c053bd42179fcb
[ "Apache-2.0" ]
9
2017-05-15T12:20:48.000Z
2021-03-13T17:45:12.000Z
core/gesture.js
JBBlunderbuss/blockly
d5834c5b785e920f1116c193c0c053bd42179fcb
[ "Apache-2.0" ]
9
2017-01-29T10:44:10.000Z
2021-12-06T08:52:16.000Z
/** * @license * Copyright 2017 Google LLC * * 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. */ /** * @fileoverview The class representing an in-progress gesture, usually a drag * or a tap. * @author fenichel@google.com (Rachel Fenichel) */ 'use strict'; goog.provide('Blockly.Gesture'); goog.require('Blockly.ASTNode'); goog.require('Blockly.blockAnimations'); goog.require('Blockly.BlockDragger'); goog.require('Blockly.BubbleDragger'); goog.require('Blockly.constants'); goog.require('Blockly.Events'); goog.require('Blockly.Events.Ui'); goog.require('Blockly.FlyoutDragger'); goog.require('Blockly.navigation'); goog.require('Blockly.Tooltip'); goog.require('Blockly.Touch'); goog.require('Blockly.utils'); goog.require('Blockly.utils.Coordinate'); goog.require('Blockly.WorkspaceDragger'); /** * Note: In this file "start" refers to touchstart, mousedown, and pointerstart * events. "End" refers to touchend, mouseup, and pointerend events. */ // TODO: Consider touchcancel/pointercancel. /** * Class for one gesture. * @param {!Event} e The event that kicked off this gesture. * @param {!Blockly.WorkspaceSvg} creatorWorkspace The workspace that created * this gesture and has a reference to it. * @constructor */ Blockly.Gesture = function(e, creatorWorkspace) { /** * The position of the mouse when the gesture started. Units are CSS pixels, * with (0, 0) at the top left of the browser window (mouseEvent clientX/Y). * @type {Blockly.utils.Coordinate} * @private */ this.mouseDownXY_ = null; /** * How far the mouse has moved during this drag, in pixel units. * (0, 0) is at this.mouseDownXY_. * @type {!Blockly.utils.Coordinate} * @private */ this.currentDragDeltaXY_ = new Blockly.utils.Coordinate(0, 0); /** * The bubble that the gesture started on, or null if it did not start on a * bubble. * @type {Blockly.Bubble} * @private */ this.startBubble_ = null; /** * The field that the gesture started on, or null if it did not start on a * field. * @type {Blockly.Field} * @private */ this.startField_ = null; /** * The block that the gesture started on, or null if it did not start on a * block. * @type {Blockly.BlockSvg} * @private */ this.startBlock_ = null; /** * The block that this gesture targets. If the gesture started on a * shadow block, this is the first non-shadow parent of the block. If the * gesture started in the flyout, this is the root block of the block group * that was clicked or dragged. * @type {Blockly.BlockSvg} * @private */ this.targetBlock_ = null; /** * The workspace that the gesture started on. There may be multiple * workspaces on a page; this is more accurate than using * Blockly.getMainWorkspace(). * @type {Blockly.WorkspaceSvg} * @protected */ this.startWorkspace_ = null; /** * The workspace that created this gesture. This workspace keeps a reference * to the gesture, which will need to be cleared at deletion. * This may be different from the start workspace. For instance, a flyout is * a workspace, but its parent workspace manages gestures for it. * @type {!Blockly.WorkspaceSvg} * @private */ this.creatorWorkspace_ = creatorWorkspace; /** * Whether the pointer has at any point moved out of the drag radius. * A gesture that exceeds the drag radius is a drag even if it ends exactly * at its start point. * @type {boolean} * @private */ this.hasExceededDragRadius_ = false; /** * Whether the workspace is currently being dragged. * @type {boolean} * @private */ this.isDraggingWorkspace_ = false; /** * Whether the block is currently being dragged. * @type {boolean} * @private */ this.isDraggingBlock_ = false; /** * Whether the bubble is currently being dragged. * @type {boolean} * @private */ this.isDraggingBubble_ = false; /** * The event that most recently updated this gesture. * @type {!Event} * @private */ this.mostRecentEvent_ = e; /** * A handle to use to unbind a mouse move listener at the end of a drag. * Opaque data returned from Blockly.bindEventWithChecks_. * @type {?Blockly.EventData} * @protected */ this.onMoveWrapper_ = null; /** * A handle to use to unbind a mouse up listener at the end of a drag. * Opaque data returned from Blockly.bindEventWithChecks_. * @type {?Blockly.EventData} * @protected */ this.onUpWrapper_ = null; /** * The object tracking a bubble drag, or null if none is in progress. * @type {Blockly.BubbleDragger} * @private */ this.bubbleDragger_ = null; /** * The object tracking a block drag, or null if none is in progress. * @type {Blockly.BlockDragger} * @private */ this.blockDragger_ = null; /** * The object tracking a workspace or flyout workspace drag, or null if none * is in progress. * @type {Blockly.WorkspaceDragger} * @private */ this.workspaceDragger_ = null; /** * The flyout a gesture started in, if any. * @type {Blockly.Flyout} * @private */ this.flyout_ = null; /** * Boolean for sanity-checking that some code is only called once. * @type {boolean} * @private */ this.calledUpdateIsDragging_ = false; /** * Boolean for sanity-checking that some code is only called once. * @type {boolean} * @private */ this.hasStarted_ = false; /** * Boolean used internally to break a cycle in disposal. * @type {boolean} * @protected */ this.isEnding_ = false; /** * Boolean used to indicate whether or not to heal the stack after * disconnecting a block. * @type {boolean} * @private */ this.healStack_ = !Blockly.DRAG_STACK; }; /** * Sever all links from this object. * @package */ Blockly.Gesture.prototype.dispose = function() { Blockly.Touch.clearTouchIdentifier(); Blockly.Tooltip.unblock(); // Clear the owner's reference to this gesture. this.creatorWorkspace_.clearGesture(); if (this.onMoveWrapper_) { Blockly.unbindEvent_(this.onMoveWrapper_); } if (this.onUpWrapper_) { Blockly.unbindEvent_(this.onUpWrapper_); } if (this.blockDragger_) { this.blockDragger_.dispose(); } if (this.workspaceDragger_) { this.workspaceDragger_.dispose(); } if (this.bubbleDragger_) { this.bubbleDragger_.dispose(); } }; /** * Update internal state based on an event. * @param {!Event} e The most recent mouse or touch event. * @private */ Blockly.Gesture.prototype.updateFromEvent_ = function(e) { var currentXY = new Blockly.utils.Coordinate(e.clientX, e.clientY); var changed = this.updateDragDelta_(currentXY); // Exceeded the drag radius for the first time. if (changed) { this.updateIsDragging_(); Blockly.longStop_(); } this.mostRecentEvent_ = e; }; /** * DO MATH to set currentDragDeltaXY_ based on the most recent mouse position. * @param {!Blockly.utils.Coordinate} currentXY The most recent mouse/pointer * position, in pixel units, with (0, 0) at the window's top left corner. * @return {boolean} True if the drag just exceeded the drag radius for the * first time. * @private */ Blockly.Gesture.prototype.updateDragDelta_ = function(currentXY) { this.currentDragDeltaXY_ = Blockly.utils.Coordinate.difference(currentXY, /** @type {!Blockly.utils.Coordinate} */ (this.mouseDownXY_)); if (!this.hasExceededDragRadius_) { var currentDragDelta = Blockly.utils.Coordinate.magnitude( this.currentDragDeltaXY_); // The flyout has a different drag radius from the rest of Blockly. var limitRadius = this.flyout_ ? Blockly.FLYOUT_DRAG_RADIUS : Blockly.DRAG_RADIUS; this.hasExceededDragRadius_ = currentDragDelta > limitRadius; return this.hasExceededDragRadius_; } return false; }; /** * Update this gesture to record whether a block is being dragged from the * flyout. * This function should be called on a mouse/touch move event the first time the * drag radius is exceeded. It should be called no more than once per gesture. * If a block should be dragged from the flyout this function creates the new * block on the main workspace and updates targetBlock_ and startWorkspace_. * @return {boolean} True if a block is being dragged from the flyout. * @private */ Blockly.Gesture.prototype.updateIsDraggingFromFlyout_ = function() { if (!this.targetBlock_) { return false; } if (!this.flyout_.isBlockCreatable_(this.targetBlock_)) { return false; } if (!this.flyout_.isScrollable() || this.flyout_.isDragTowardWorkspace(this.currentDragDeltaXY_)) { this.startWorkspace_ = this.flyout_.targetWorkspace_; this.startWorkspace_.updateScreenCalculationsIfScrolled(); // Start the event group now, so that the same event group is used for block // creation and block dragging. if (!Blockly.Events.getGroup()) { Blockly.Events.setGroup(true); } // The start block is no longer relevant, because this is a drag. this.startBlock_ = null; this.targetBlock_ = this.flyout_.createBlock(this.targetBlock_); this.targetBlock_.select(); return true; } return false; }; /** * Update this gesture to record whether a bubble is being dragged. * This function should be called on a mouse/touch move event the first time the * drag radius is exceeded. It should be called no more than once per gesture. * If a bubble should be dragged this function creates the necessary * BubbleDragger and starts the drag. * @return {boolean} True if a bubble is being dragged. * @private */ Blockly.Gesture.prototype.updateIsDraggingBubble_ = function() { if (!this.startBubble_) { return false; } this.isDraggingBubble_ = true; this.startDraggingBubble_(); return true; }; /** * Update this gesture to record whether a block is being dragged. * This function should be called on a mouse/touch move event the first time the * drag radius is exceeded. It should be called no more than once per gesture. * If a block should be dragged, either from the flyout or in the workspace, * this function creates the necessary BlockDragger and starts the drag. * @return {boolean} True if a block is being dragged. * @private */ Blockly.Gesture.prototype.updateIsDraggingBlock_ = function() { if (!this.targetBlock_) { return false; } if (this.flyout_) { this.isDraggingBlock_ = this.updateIsDraggingFromFlyout_(); } else if (this.targetBlock_.isMovable()) { this.isDraggingBlock_ = true; } if (this.isDraggingBlock_) { this.startDraggingBlock_(); return true; } return false; }; /** * Update this gesture to record whether a workspace is being dragged. * This function should be called on a mouse/touch move event the first time the * drag radius is exceeded. It should be called no more than once per gesture. * If a workspace is being dragged this function creates the necessary * WorkspaceDragger or FlyoutDragger and starts the drag. * @private */ Blockly.Gesture.prototype.updateIsDraggingWorkspace_ = function() { var wsMovable = this.flyout_ ? this.flyout_.isScrollable() : this.startWorkspace_ && this.startWorkspace_.isDraggable(); if (!wsMovable) { return; } if (this.flyout_) { this.workspaceDragger_ = new Blockly.FlyoutDragger(this.flyout_); } else { this.workspaceDragger_ = new Blockly.WorkspaceDragger( /** @type {!Blockly.WorkspaceSvg} */ (this.startWorkspace_)); } this.isDraggingWorkspace_ = true; this.workspaceDragger_.startDrag(); }; /** * Update this gesture to record whether anything is being dragged. * This function should be called on a mouse/touch move event the first time the * drag radius is exceeded. It should be called no more than once per gesture. * @private */ Blockly.Gesture.prototype.updateIsDragging_ = function() { // Sanity check. if (this.calledUpdateIsDragging_) { throw Error('updateIsDragging_ should only be called once per gesture.'); } this.calledUpdateIsDragging_ = true; // First check if it was a bubble drag. Bubbles always sit on top of blocks. if (this.updateIsDraggingBubble_()) { return; } // Then check if it was a block drag. if (this.updateIsDraggingBlock_()) { return; } // Then check if it's a workspace drag. this.updateIsDraggingWorkspace_(); }; /** * Create a block dragger and start dragging the selected block. * @private */ Blockly.Gesture.prototype.startDraggingBlock_ = function() { this.blockDragger_ = new Blockly.BlockDragger( /** @type {!Blockly.BlockSvg} */ (this.targetBlock_), /** @type {!Blockly.WorkspaceSvg} */ (this.startWorkspace_)); this.blockDragger_.startBlockDrag(this.currentDragDeltaXY_, this.healStack_); this.blockDragger_.dragBlock(this.mostRecentEvent_, this.currentDragDeltaXY_); }; /** * Create a bubble dragger and start dragging the selected bubble. * @private */ // TODO (fenichel): Possibly combine this and startDraggingBlock_. Blockly.Gesture.prototype.startDraggingBubble_ = function() { this.bubbleDragger_ = new Blockly.BubbleDragger( /** @type {!Blockly.Bubble} */ (this.startBubble_), /** @type {!Blockly.WorkspaceSvg} */ (this.startWorkspace_)); this.bubbleDragger_.startBubbleDrag(); this.bubbleDragger_.dragBubble(this.mostRecentEvent_, this.currentDragDeltaXY_); }; /** * Start a gesture: update the workspace to indicate that a gesture is in * progress and bind mousemove and mouseup handlers. * @param {!Event} e A mouse down or touch start event. * @package */ Blockly.Gesture.prototype.doStart = function(e) { if (Blockly.utils.isTargetInput(e)) { this.cancel(); return; } this.hasStarted_ = true; Blockly.blockAnimations.disconnectUiStop(); this.startWorkspace_.updateScreenCalculationsIfScrolled(); if (this.startWorkspace_.isMutator) { // Mutator's coordinate system could be out of date because the bubble was // dragged, the block was moved, the parent workspace zoomed, etc. this.startWorkspace_.resize(); } // Hide chaff also hides the flyout, so don't do it if the click is in a // flyout. Blockly.hideChaff(!!this.flyout_); this.startWorkspace_.markFocused(); this.mostRecentEvent_ = e; Blockly.Tooltip.block(); if (this.targetBlock_) { if (!this.targetBlock_.isInFlyout && e.shiftKey && this.targetBlock_.workspace.keyboardAccessibilityMode) { this.creatorWorkspace_.getCursor().setCurNode( Blockly.navigation.getTopNode(this.targetBlock_)); } else { this.targetBlock_.select(); } } if (Blockly.utils.isRightButton(e)) { this.handleRightClick(e); return; } if ((e.type.toLowerCase() == 'touchstart' || e.type.toLowerCase() == 'pointerdown') && e.pointerType != 'mouse') { Blockly.longStart(e, this); } this.mouseDownXY_ = new Blockly.utils.Coordinate(e.clientX, e.clientY); this.healStack_ = e.altKey || e.ctrlKey || e.metaKey; this.bindMouseEvents(e); }; /** * Bind gesture events. * @param {!Event} e A mouse down or touch start event. * @package */ Blockly.Gesture.prototype.bindMouseEvents = function(e) { this.onMoveWrapper_ = Blockly.bindEventWithChecks_( document, 'mousemove', null, this.handleMove.bind(this)); this.onUpWrapper_ = Blockly.bindEventWithChecks_( document, 'mouseup', null, this.handleUp.bind(this)); e.preventDefault(); e.stopPropagation(); }; /** * Handle a mouse move or touch move event. * @param {!Event} e A mouse move or touch move event. * @package */ Blockly.Gesture.prototype.handleMove = function(e) { this.updateFromEvent_(e); if (this.isDraggingWorkspace_) { this.workspaceDragger_.drag(this.currentDragDeltaXY_); } else if (this.isDraggingBlock_) { this.blockDragger_.dragBlock(this.mostRecentEvent_, this.currentDragDeltaXY_); } else if (this.isDraggingBubble_) { this.bubbleDragger_.dragBubble(this.mostRecentEvent_, this.currentDragDeltaXY_); } e.preventDefault(); e.stopPropagation(); }; /** * Handle a mouse up or touch end event. * @param {!Event} e A mouse up or touch end event. * @package */ Blockly.Gesture.prototype.handleUp = function(e) { this.updateFromEvent_(e); Blockly.longStop_(); if (this.isEnding_) { console.log('Trying to end a gesture recursively.'); return; } this.isEnding_ = true; // The ordering of these checks is important: drags have higher priority than // clicks. Fields have higher priority than blocks; blocks have higher // priority than workspaces. // The ordering within drags does not matter, because the three types of // dragging are exclusive. if (this.isDraggingBubble_) { this.bubbleDragger_.endBubbleDrag(e, this.currentDragDeltaXY_); } else if (this.isDraggingBlock_) { this.blockDragger_.endBlockDrag(e, this.currentDragDeltaXY_); } else if (this.isDraggingWorkspace_) { this.workspaceDragger_.endDrag(this.currentDragDeltaXY_); } else if (this.isBubbleClick_()) { // Bubbles are in front of all fields and blocks. this.doBubbleClick_(); } else if (this.isFieldClick_()) { this.doFieldClick_(); } else if (this.isBlockClick_()) { this.doBlockClick_(); } else if (this.isWorkspaceClick_()) { this.doWorkspaceClick_(e); } e.preventDefault(); e.stopPropagation(); this.dispose(); }; /** * Cancel an in-progress gesture. If a workspace or block drag is in progress, * end the drag at the most recent location. * @package */ Blockly.Gesture.prototype.cancel = function() { // Disposing of a block cancels in-progress drags, but dragging to a delete // area disposes of a block and leads to recursive disposal. Break that cycle. if (this.isEnding_) { return; } Blockly.longStop_(); if (this.isDraggingBubble_) { this.bubbleDragger_.endBubbleDrag(this.mostRecentEvent_, this.currentDragDeltaXY_); } else if (this.isDraggingBlock_) { this.blockDragger_.endBlockDrag(this.mostRecentEvent_, this.currentDragDeltaXY_); } else if (this.isDraggingWorkspace_) { this.workspaceDragger_.endDrag(this.currentDragDeltaXY_); } this.dispose(); }; /** * Handle a real or faked right-click event by showing a context menu. * @param {!Event} e A mouse move or touch move event. * @package */ Blockly.Gesture.prototype.handleRightClick = function(e) { if (this.targetBlock_) { this.bringBlockToFront_(); Blockly.hideChaff(!!this.flyout_); this.targetBlock_.showContextMenu(e); } else if (this.startBubble_) { this.startBubble_.showContextMenu(e); } else if (this.startWorkspace_ && !this.flyout_) { Blockly.hideChaff(); this.startWorkspace_.showContextMenu(e); } // TODO: Handle right-click on a bubble. e.preventDefault(); e.stopPropagation(); this.dispose(); }; /** * Handle a mousedown/touchstart event on a workspace. * @param {!Event} e A mouse down or touch start event. * @param {!Blockly.WorkspaceSvg} ws The workspace the event hit. * @package */ Blockly.Gesture.prototype.handleWsStart = function(e, ws) { if (this.hasStarted_) { throw Error('Tried to call gesture.handleWsStart, ' + 'but the gesture had already been started.'); } this.setStartWorkspace_(ws); this.mostRecentEvent_ = e; this.doStart(e); if (this.startWorkspace_.keyboardAccessibilityMode) { Blockly.navigation.setState(Blockly.navigation.STATE_WS); } }; /** * Handle a mousedown/touchstart event on a flyout. * @param {!Event} e A mouse down or touch start event. * @param {!Blockly.Flyout} flyout The flyout the event hit. * @package */ Blockly.Gesture.prototype.handleFlyoutStart = function(e, flyout) { if (this.hasStarted_) { throw Error('Tried to call gesture.handleFlyoutStart, ' + 'but the gesture had already been started.'); } this.setStartFlyout_(flyout); this.handleWsStart(e, flyout.getWorkspace()); }; /** * Handle a mousedown/touchstart event on a block. * @param {!Event} e A mouse down or touch start event. * @param {!Blockly.BlockSvg} block The block the event hit. * @package */ Blockly.Gesture.prototype.handleBlockStart = function(e, block) { if (this.hasStarted_) { throw Error('Tried to call gesture.handleBlockStart, ' + 'but the gesture had already been started.'); } this.setStartBlock(block); this.mostRecentEvent_ = e; }; /** * Handle a mousedown/touchstart event on a bubble. * @param {!Event} e A mouse down or touch start event. * @param {!Blockly.Bubble} bubble The bubble the event hit. * @package */ Blockly.Gesture.prototype.handleBubbleStart = function(e, bubble) { if (this.hasStarted_) { throw Error('Tried to call gesture.handleBubbleStart, ' + 'but the gesture had already been started.'); } this.setStartBubble(bubble); this.mostRecentEvent_ = e; }; /* Begin functions defining what actions to take to execute clicks on each type * of target. Any developer wanting to add behaviour on clicks should modify * only this code. */ /** * Execute a bubble click. * @private */ Blockly.Gesture.prototype.doBubbleClick_ = function() { // TODO (#1673): Consistent handling of single clicks. this.startBubble_.setFocus && this.startBubble_.setFocus(); this.startBubble_.select && this.startBubble_.select(); }; /** * Execute a field click. * @private */ Blockly.Gesture.prototype.doFieldClick_ = function() { this.startField_.showEditor(this.mostRecentEvent_); this.bringBlockToFront_(); }; /** * Execute a block click. * @private */ Blockly.Gesture.prototype.doBlockClick_ = function() { // Block click in an autoclosing flyout. if (this.flyout_ && this.flyout_.autoClose) { if (this.targetBlock_.isEnabled()) { if (!Blockly.Events.getGroup()) { Blockly.Events.setGroup(true); } var newBlock = this.flyout_.createBlock(this.targetBlock_); newBlock.scheduleSnapAndBump(); } } else { // Clicks events are on the start block, even if it was a shadow. Blockly.Events.fire( new Blockly.Events.Ui(this.startBlock_, 'click', undefined, undefined)); } this.bringBlockToFront_(); Blockly.Events.setGroup(false); }; /** * Execute a workspace click. Shift clicking puts the workspace in accessibility * mode. * @param {!Event} e A mouse up or touch end event. * @private */ Blockly.Gesture.prototype.doWorkspaceClick_ = function(e) { var ws = this.creatorWorkspace_; if (e.shiftKey && ws.keyboardAccessibilityMode) { var screenCoord = new Blockly.utils.Coordinate(e.clientX, e.clientY); var wsCoord = Blockly.utils.screenToWsCoordinates(ws, screenCoord); var wsNode = Blockly.ASTNode.createWorkspaceNode(ws, wsCoord); ws.getCursor().setCurNode(wsNode); } else if (Blockly.selected) { Blockly.selected.unselect(); } }; /* End functions defining what actions to take to execute clicks on each type * of target. */ // TODO (fenichel): Move bubbles to the front. /** * Move the dragged/clicked block to the front of the workspace so that it is * not occluded by other blocks. * @private */ Blockly.Gesture.prototype.bringBlockToFront_ = function() { // Blocks in the flyout don't overlap, so skip the work. if (this.targetBlock_ && !this.flyout_) { this.targetBlock_.bringToFront(); } }; /* Begin functions for populating a gesture at mouse down. */ /** * Record the field that a gesture started on. * @param {Blockly.Field} field The field the gesture started on. * @package */ Blockly.Gesture.prototype.setStartField = function(field) { if (this.hasStarted_) { throw Error('Tried to call gesture.setStartField, ' + 'but the gesture had already been started.'); } if (!this.startField_) { this.startField_ = field; } }; /** * Record the bubble that a gesture started on * @param {Blockly.Bubble} bubble The bubble the gesture started on. * @package */ Blockly.Gesture.prototype.setStartBubble = function(bubble) { if (!this.startBubble_) { this.startBubble_ = bubble; } }; /** * Record the block that a gesture started on, and set the target block * appropriately. * @param {Blockly.BlockSvg} block The block the gesture started on. * @package */ Blockly.Gesture.prototype.setStartBlock = function(block) { // If the gesture already went through a bubble, don't set the start block. if (!this.startBlock_ && !this.startBubble_) { this.startBlock_ = block; if (block.isInFlyout && block != block.getRootBlock()) { this.setTargetBlock_(block.getRootBlock()); } else { this.setTargetBlock_(block); } } }; /** * Record the block that a gesture targets, meaning the block that will be * dragged if this turns into a drag. If this block is a shadow, that will be * its first non-shadow parent. * @param {Blockly.BlockSvg} block The block the gesture targets. * @private */ Blockly.Gesture.prototype.setTargetBlock_ = function(block) { if (block.isShadow()) { this.setTargetBlock_(block.getParent()); } else { this.targetBlock_ = block; } }; /** * Record the workspace that a gesture started on. * @param {Blockly.WorkspaceSvg} ws The workspace the gesture started on. * @private */ Blockly.Gesture.prototype.setStartWorkspace_ = function(ws) { if (!this.startWorkspace_) { this.startWorkspace_ = ws; } }; /** * Record the flyout that a gesture started on. * @param {Blockly.Flyout} flyout The flyout the gesture started on. * @private */ Blockly.Gesture.prototype.setStartFlyout_ = function(flyout) { if (!this.flyout_) { this.flyout_ = flyout; } }; /* End functions for populating a gesture at mouse down. */ /* Begin helper functions defining types of clicks. Any developer wanting * to change the definition of a click should modify only this code. */ /** * Whether this gesture is a click on a bubble. This should only be called when * ending a gesture (mouse up, touch end). * @return {boolean} Whether this gesture was a click on a bubble. * @private */ Blockly.Gesture.prototype.isBubbleClick_ = function() { // A bubble click starts on a bubble and never escapes the drag radius. var hasStartBubble = !!this.startBubble_; return hasStartBubble && !this.hasExceededDragRadius_; }; /** * Whether this gesture is a click on a block. This should only be called when * ending a gesture (mouse up, touch end). * @return {boolean} Whether this gesture was a click on a block. * @private */ Blockly.Gesture.prototype.isBlockClick_ = function() { // A block click starts on a block, never escapes the drag radius, and is not // a field click. var hasStartBlock = !!this.startBlock_; return hasStartBlock && !this.hasExceededDragRadius_ && !this.isFieldClick_(); }; /** * Whether this gesture is a click on a field. This should only be called when * ending a gesture (mouse up, touch end). * @return {boolean} Whether this gesture was a click on a field. * @private */ Blockly.Gesture.prototype.isFieldClick_ = function() { var fieldClickable = this.startField_ ? this.startField_.isClickable() : false; return fieldClickable && !this.hasExceededDragRadius_ && (!this.flyout_ || !this.flyout_.autoClose); }; /** * Whether this gesture is a click on a workspace. This should only be called * when ending a gesture (mouse up, touch end). * @return {boolean} Whether this gesture was a click on a workspace. * @private */ Blockly.Gesture.prototype.isWorkspaceClick_ = function() { var onlyTouchedWorkspace = !this.startBlock_ && !this.startBubble_ && !this.startField_; return onlyTouchedWorkspace && !this.hasExceededDragRadius_; }; /* End helper functions defining types of clicks. */ /** * Whether this gesture is a drag of either a workspace or block. * This function is called externally to block actions that cannot be taken * mid-drag (e.g. using the keyboard to delete the selected blocks). * @return {boolean} True if this gesture is a drag of a workspace or block. * @package */ Blockly.Gesture.prototype.isDragging = function() { return this.isDraggingWorkspace_ || this.isDraggingBlock_ || this.isDraggingBubble_; }; /** * Whether this gesture has already been started. In theory every mouse down * has a corresponding mouse up, but in reality it is possible to lose a * mouse up, leaving an in-process gesture hanging. * @return {boolean} Whether this gesture was a click on a workspace. * @package */ Blockly.Gesture.prototype.hasStarted = function() { return this.hasStarted_; }; /** * Get a list of the insertion markers that currently exist. Block drags have * 0, 1, or 2 insertion markers. * @return {!Array.<!Blockly.BlockSvg>} A possibly empty list of insertion * marker blocks. * @package */ Blockly.Gesture.prototype.getInsertionMarkers = function() { if (this.blockDragger_) { return this.blockDragger_.getInsertionMarkers(); } return []; }; /** * Is a drag or other gesture currently in progress on any workspace? * @return {boolean} True if gesture is occurring. */ Blockly.Gesture.inProgress = function() { var workspaces = Blockly.Workspace.getAll(); for (var i = 0, workspace; (workspace = workspaces[i]); i++) { if (workspace.currentGesture_) { return true; } } return false; };
30.380325
80
0.701786
1e06a8bee7921d1802fbf9aaca8df296b9705eab
1,518
js
JavaScript
js/components/nglViewerControls.js
ricgillams/fragalysis-frontend
404950248f7f2298e2dc41d7ff2ec71350984643
[ "MIT" ]
null
null
null
js/components/nglViewerControls.js
ricgillams/fragalysis-frontend
404950248f7f2298e2dc41d7ff2ec71350984643
[ "MIT" ]
1
2018-12-18T15:39:53.000Z
2018-12-18T15:39:53.000Z
js/components/nglViewerControls.js
ricgillams/fragalysis-frontend
404950248f7f2298e2dc41d7ff2ec71350984643
[ "MIT" ]
null
null
null
/** * Created by ricgillams on 28/06/2018. */ import React from "react"; import {connect} from "react-redux"; import * as nglLoadActions from "../actions/nglLoadActions"; import {Button} from "react-bootstrap"; class NglViewerControls extends React.Component { constructor(props) { super(props) this.handleStageColor = this.handleStageColor.bind(this); this.handleNglProtStyle = this.handleNglProtStyle.bind(this); } handleStageColor() { if (this.props.stageColor === 'white') { this.props.setStageColor('black'); } else { this.props.setStageColor('white'); } } handleNglProtStyle() { if (this.props.nglProtStyle === 'cartoon') { this.props.setNglProtStyle('hyperball') } else if (this.props.nglProtStyle === 'hyperball') { this.props.setNglProtStyle('cartoon') } } render() { return <div> <h3>Viewer controls</h3> <Button bsSize="sm" bsStyle="success" onClick={this.handleStageColor}>Change background colour</Button> </div> } } function mapStateToProps(state) { return { stageColor: state.nglReducers.present.stageColor, nglProtStyle: state.nglReducers.present.nglProtStyle } } const mapDispatchToProps = { setStageColor: nglLoadActions.setStageColor, setNglProtStyle: nglLoadActions.setNglProtStyle } export default connect(mapStateToProps, mapDispatchToProps)(NglViewerControls)
27.6
115
0.652174
1e06b74ac36550ff626e4f39fad2e20e76f7240a
621
js
JavaScript
src/components/MonsterMakerCode.js
TibiaJS/otmonstermaker
0b13a86cde6619295d8673a85d2c7a37414801f7
[ "MIT" ]
2
2020-03-20T10:22:43.000Z
2020-06-02T23:50:12.000Z
src/components/MonsterMakerCode.js
TibiaJS/otmonstermaker
0b13a86cde6619295d8673a85d2c7a37414801f7
[ "MIT" ]
null
null
null
src/components/MonsterMakerCode.js
TibiaJS/otmonstermaker
0b13a86cde6619295d8673a85d2c7a37414801f7
[ "MIT" ]
1
2020-01-13T06:26:10.000Z
2020-01-13T06:26:10.000Z
import React from 'react'; const containerStyle = { maxHeight: 250, width: '100%', margin: 5, overflow: 'auto', //textAlign: 'center', backgroundColor: '#000000', color: '#FFFFFF', whiteSpace: 'pre' } const textContainerStyle = { margin: 'auto', display: 'table' } class MonsterMakerCode extends React.Component { render() { return( <div style={ containerStyle } > <div style={ textContainerStyle } > { this.props.text } </div> </div> ); } } export default MonsterMakerCode;
18.264706
51
0.536232
1e06f3013d34f5cc2c58c4d4cc0be3e4cc32970e
6,025
js
JavaScript
src/pages/Home/index.js
lijifa/LggWeb
9570c2e161f2a38e38e19e63763c42458c305ad3
[ "MIT" ]
null
null
null
src/pages/Home/index.js
lijifa/LggWeb
9570c2e161f2a38e38e19e63763c42458c305ad3
[ "MIT" ]
null
null
null
src/pages/Home/index.js
lijifa/LggWeb
9570c2e161f2a38e38e19e63763c42458c305ad3
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import Link from 'umi/link'; import { Row, Col, Form, Icon, Badge } from 'antd'; import { connect } from 'dva'; import { formatTime, covertMoney2Yuan} from '@/utils/utils'; import { getAuthority } from '@/utils/authority'; import indexStyle from './styles.less'; const namespace = 'home'; @connect(({ home }) => ({ result: home.data.data, })) export default class Home extends Component { state = { queryParam: {}, isOpen: false }; componentDidMount() { this.searchList() } searchList() { const { dispatch } = this.props; const { queryParam } = this.state dispatch({ type: `${namespace}/search`, payload: queryParam }); } renderNotice(noticeList) { if(noticeList) { const noticeTitleList = noticeList.map((item) => { return item.noticeTitle }) let html = [] for(let i = 0; i < noticeTitleList.length; i++) { html.push(<p key={i}>{noticeTitleList[i]}</p>) } return html } } disTotalBox(){ const {isOpen} = this.state this.setState({ isOpen: !isOpen }) } checkPower(path) { let allPower = getAuthority() if (allPower.indexOf(path) >= 0) { return true; }else{ return false } } render() { const { totalUser, toatlDayMeal, totalUserAcct, totalDaySale, noticeList} = this.props.result const { isOpen } = this.state const disTotalCss = {background: '#00a65d', padding: '10px', textAlign:'center', cursor: 'pointer'} return ( <div style={{background:'#fff'}}> <Row className={indexStyle.indexTag} style={{display: isOpen ? 'block' : 'none'}}> <Col md={6} sm={24} className={indexStyle.moneyTagRight}> <div style={{background:'#00a65d'}}> <p className={indexStyle.title}>员工总数</p> <p className={String(totalUser).length > 8 ? indexStyle.longcontent : indexStyle.content}>{totalUser} <span className={indexStyle.unit}>人</span></p> </div> </Col> <Col md={6} sm={24} className={indexStyle.moneyTagRight}> <div style={{background:'#00aff2'}}> <p className={indexStyle.title}>昨日就餐次数</p> <p className={String(toatlDayMeal).length > 8 ? indexStyle.longcontent : indexStyle.content}>{toatlDayMeal} <span className={indexStyle.unit}>人</span></p> </div> </Col> <Col md={6} sm={24} className={indexStyle.moneyTagRight}> <div style={{background:'#6e66dd'}}> <p className={indexStyle.title}>账户余额</p> <p className={String(totalUserAcct).length > 8 ? indexStyle.longcontent : indexStyle.content}>{covertMoney2Yuan(totalUserAcct)} <span className={indexStyle.unit}>元</span></p> </div> </Col> <Col md={6} sm={24} className={indexStyle.moneyTagRight}> <div style={{background:'#fe5c60'}}> <p className={indexStyle.title}>昨日消费总额</p> <p className={String(totalDaySale).length > 8 ? indexStyle.longcontent : indexStyle.content}>{covertMoney2Yuan(totalDaySale)} <span className={indexStyle.unit}>元</span></p> </div> </Col> </Row> <Row className={indexStyle.indexTag}> <Col md={24} sm={24} className={indexStyle.moneyTagRight}> <div style={disTotalCss} onClick={()=>{this.disTotalBox()}}> { isOpen ? <span>点击收起统计数据 <Icon type='caret-up' /></span> : <span>点击展开统计数据 <Icon type='caret-down' /></span>} </div> </Col> </Row> <Row className={indexStyle.indexTitle}> 未处理事件 </Row> <Row className={indexStyle.indexTitle}> <Link to={'/system/notice'} style={{float: 'left', display: this.checkPower('/system/notice') ? 'block' : 'none'}}> <Badge><div className={indexStyle.eventBtn}>通知审核</div></Badge> </Link> <Link to={'/restaurant/menu-notice'} style={{float: 'left', display: this.checkPower('/restaurant/menu-notice') ? 'block' : 'none'}}> <Badge><div className={indexStyle.eventBtn} style={{marginLeft:'30px'}}>菜单预告</div></Badge> </Link> </Row> <Row> <Col span={12}> <div className={indexStyle.indexTitle} style={{borderRight:'1px solid #eee'}}> 快捷操作 </div> <div className={indexStyle.indexContent} style={{borderRight:'1px solid #eee', float:'left',paddingLeft:'10px', width: '100%'}}> <Link to={'/vipcard/accountrecharge'} style={{display: this.checkPower('/vipcard/accountrecharge') ? 'block' : 'none'}}> <div className={indexStyle.quickBtnBlue}><Icon type="idcard" theme="outlined" style={{marginRight:10}}/>批量充值</div> </Link> <Link to={'/system/notice'} style={{display: this.checkPower('/system/notice') ? 'block' : 'none'}}> <div className={indexStyle.quickBtnYellow}><Icon type="message" theme="outlined" style={{marginRight:10}}/>通知审核</div> </Link> <Link to={'/vipcard/tempcardauth'} style={{display: this.checkPower('/vipcard/tempcardauth') ? 'block' : 'none'}}> <div className={indexStyle.quickBtnGreen}><Icon type="safety-certificate" theme="outlined" style={{marginRight:10}}/>临时授权</div> </Link> <Link to={'/system/item'} style={{display: this.checkPower('/system/item') ? 'block' : 'none'}}> <div className={indexStyle.quickBtnPurple}><Icon type="shopping" theme="outlined" style={{marginRight:10}}/>商品管理</div> </Link> </div> </Col> <Col span={12}> <div className={indexStyle.indexTitle}> 最新公告 </div> <div className={indexStyle.indexContent}> {this.renderNotice(noticeList)} </div> </Col> </Row> </div> ); } }
40.709459
188
0.573776
1e0868c2651eff6a560b0f31af7d9ae4aac2ccc8
736
js
JavaScript
API/api/server/routes/EquipmentRoutes.js
Worldten/dofus-helper-api
30ab510016587d65c20e1401e7418658cc3b950b
[ "MIT" ]
null
null
null
API/api/server/routes/EquipmentRoutes.js
Worldten/dofus-helper-api
30ab510016587d65c20e1401e7418658cc3b950b
[ "MIT" ]
2
2021-05-11T10:50:03.000Z
2021-09-02T12:55:57.000Z
API/api/server/routes/EquipmentRoutes.js
Worldten/dofus-helper-api
30ab510016587d65c20e1401e7418658cc3b950b
[ "MIT" ]
null
null
null
import { Router } from 'express'; import EquipmentController from '../controllers/EquipmentController'; var authController = require("../controllers/AuthController") const router = Router(); router.get('/', authController.verifyToken, EquipmentController.getAllEquipments); router.post('/', authController.verifyToken, EquipmentController.addEquipment); router.get('/:id', authController.verifyToken, EquipmentController.getAEquipment); router.put('/:id', authController.verifyToken, EquipmentController.updatedEquipment); router.delete('/:id', authController.verifyToken, EquipmentController.deleteEquipment); router.get('/player/:id', authController.verifyToken, EquipmentController.getEquipmentsByPlayer); export default router;
46
97
0.809783
1e08dff562524970a95b03d9f0bd7d978d289d33
4,830
js
JavaScript
public/convassets/plugins/table/sticky-table-header/jquery.stickyheader.js
Franciscobvb/ConvocatoriaNY2020
4db5283bffb71d7f103f1f7850e086561e10c3ac
[ "MIT" ]
null
null
null
public/convassets/plugins/table/sticky-table-header/jquery.stickyheader.js
Franciscobvb/ConvocatoriaNY2020
4db5283bffb71d7f103f1f7850e086561e10c3ac
[ "MIT" ]
null
null
null
public/convassets/plugins/table/sticky-table-header/jquery.stickyheader.js
Franciscobvb/ConvocatoriaNY2020
4db5283bffb71d7f103f1f7850e086561e10c3ac
[ "MIT" ]
null
null
null
$(function(){ $('table').each(function() { if($(this).find('thead').length > 0 && $(this).find('th').length > 0) { // Clone <thead> var $w = $(window), $t = $(this), $thead = $t.find('thead').clone(), $col = $t.find('thead, tbody').clone(); // Add class, remove margins, reset width and wrap table $t .addClass('sticky-enabled') .css({ margin: 0, width: '100%' }).wrap('<div class="sticky-wrap" />'); if($t.hasClass('overflow-y')) $t.removeClass('overflow-y').parent().addClass('overflow-y'); // Create new sticky table head (basic) $t.after('<table class="sticky-thead" />'); // If <tbody> contains <th>, then we create sticky column and intersect (advanced) if($t.find('tbody th').length > 0) { $t.after('<table class="sticky-col" /><table class="sticky-intersect" />'); } // Create shorthand for things var $stickyHead = $(this).siblings('.sticky-thead'), $stickyCol = $(this).siblings('.sticky-col'), $stickyInsct = $(this).siblings('.sticky-intersect'), $stickyWrap = $(this).parent('.sticky-wrap'); $stickyHead.append($thead); $stickyCol .append($col) .find('thead th:gt(0)').remove() .end() .find('tbody td').remove(); $stickyInsct.html('<thead><tr><th>'+$t.find('thead th:first-child').html()+'</th></tr></thead>'); // Set widths var setWidths = function () { $t .find('thead th').each(function (i) { $stickyHead.find('th').eq(i).width($(this).width()); }) .end() .find('tr').each(function (i) { $stickyCol.find('tr').eq(i).height($(this).height()); }); // Set width of sticky table head $stickyHead.width($t.width()); // Set width of sticky table col $stickyCol.find('th').add($stickyInsct.find('th')).width($t.find('thead th').width()) }, repositionStickyHead = function () { // Return value of calculated allowance var allowance = calcAllowance(); // Check if wrapper parent is overflowing along the y-axis if($t.height() > $stickyWrap.height()) { // If it is overflowing (advanced layout) // Position sticky header based on wrapper scrollTop() if($stickyWrap.scrollTop() > 0) { // When top of wrapping parent is out of view $stickyHead.add($stickyInsct).css({ opacity: 1, top: $stickyWrap.scrollTop() }); } else { // When top of wrapping parent is in view $stickyHead.add($stickyInsct).css({ opacity: 0, top: 0 }); } } else { // If it is not overflowing (basic layout) // Position sticky header based on viewport scrollTop if($w.scrollTop() > $t.offset().top && $w.scrollTop() < $t.offset().top + $t.outerHeight() - allowance) { // When top of viewport is in the table itself if ($(window).width() >= 992 ) { $stickyHead.add($stickyInsct).css({ opacity: 1, top: $w.scrollTop() - $t.offset().top + 171 // top: $w.scrollTop() - $t.offset().top + 103 }); } else if($(window).width() <= 991) { $stickyHead.add($stickyInsct).css({ opacity: 1, // top: $w.scrollTop() - $t.offset().top + 57 top: $w.scrollTop() - $t.offset().top + 157 }); } console.log($w.scrollTop() - $t.offset().top + 103); } else { // When top of viewport is above or below table $stickyHead.add($stickyInsct).css({ opacity: 0, top: 0 }); } } }, repositionStickyCol = function () { if($stickyWrap.scrollLeft() > 0) { // When left of wrapping parent is out of view $stickyCol.add($stickyInsct).css({ opacity: 1, left: $stickyWrap.scrollLeft() }); } else { // When left of wrapping parent is in view $stickyCol .css({ opacity: 0 }) .add($stickyInsct).css({ left: 0 }); } }, calcAllowance = function () { var a = 0; // Calculate allowance $t.find('tbody tr:lt(3)').each(function () { a += $(this).height(); }); // Set fail safe limit (last three row might be too tall) // Set arbitrary limit at 0.25 of viewport height, or you can use an arbitrary pixel value if(a > $w.height()*0.25) { a = $w.height()*0.25; } // Add the height of sticky header a += $stickyHead.height(); return a; }; setWidths(); $t.parent('.sticky-wrap').scroll($.throttle(250, function() { repositionStickyHead(); repositionStickyCol(); })); $w .on('load',setWidths) .resize($.debounce(250, function () { setWidths(); repositionStickyHead(); repositionStickyCol(); })) .scroll($.throttle(250, repositionStickyHead)); } }); });
30
111
0.55383
1e08f9a77b144f977b3dbc58f1207bf90309dbf4
46,888
js
JavaScript
dist/9.00a10cf23e83403814a5.js
pauloedsr/usDoc-ng
6d93efafe881260080f293a43ea7324937262411
[ "Apache-2.0" ]
null
null
null
dist/9.00a10cf23e83403814a5.js
pauloedsr/usDoc-ng
6d93efafe881260080f293a43ea7324937262411
[ "Apache-2.0" ]
null
null
null
dist/9.00a10cf23e83403814a5.js
pauloedsr/usDoc-ng
6d93efafe881260080f293a43ea7324937262411
[ "Apache-2.0" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[9],{"9It4":function(t,e,i){"use strict";i.d(e,"c",function(){return d}),i.d(e,"b",function(){return c}),i.d(e,"a",function(){return u});var n=i("mrSG"),r=i("n6gG"),a=i("CcnG"),o=(i("gIcY"),i("Wf4p")),l=0,s=function(t,e){this.source=t,this.value=e},c=function(t){function e(e){var i=t.call(this)||this;return i._changeDetector=e,i._value=null,i._name="mat-radio-group-"+l++,i._selected=null,i._isInitialized=!1,i._labelPosition="after",i._disabled=!1,i._required=!1,i._controlValueAccessorChangeFn=function(){},i.onTouched=function(){},i.change=new a.EventEmitter,i}return Object(n.__extends)(e,t),Object.defineProperty(e.prototype,"name",{get:function(){return this._name},set:function(t){this._name=t,this._updateRadioButtonNames()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"labelPosition",{get:function(){return this._labelPosition},set:function(t){this._labelPosition="before"===t?"before":"after",this._markRadiosForCheck()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._value},set:function(t){this._value!==t&&(this._value=t,this._updateSelectedRadioFromValue(),this._checkSelectedRadioButton())},enumerable:!0,configurable:!0}),e.prototype._checkSelectedRadioButton=function(){this._selected&&!this._selected.checked&&(this._selected.checked=!0)},Object.defineProperty(e.prototype,"selected",{get:function(){return this._selected},set:function(t){this._selected=t,this.value=t?t.value:null,this._checkSelectedRadioButton()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"disabled",{get:function(){return this._disabled},set:function(t){this._disabled=Object(r.c)(t),this._markRadiosForCheck()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"required",{get:function(){return this._required},set:function(t){this._required=Object(r.c)(t),this._markRadiosForCheck()},enumerable:!0,configurable:!0}),e.prototype.ngAfterContentInit=function(){this._isInitialized=!0},e.prototype._touch=function(){this.onTouched&&this.onTouched()},e.prototype._updateRadioButtonNames=function(){var t=this;this._radios&&this._radios.forEach(function(e){e.name=t.name})},e.prototype._updateSelectedRadioFromValue=function(){var t=this;this._radios&&(null===this._selected||this._selected.value!==this._value)&&(this._selected=null,this._radios.forEach(function(e){e.checked=t.value===e.value,e.checked&&(t._selected=e)}))},e.prototype._emitChangeEvent=function(){this._isInitialized&&this.change.emit(new s(this._selected,this._value))},e.prototype._markRadiosForCheck=function(){this._radios&&this._radios.forEach(function(t){return t._markForCheck()})},e.prototype.writeValue=function(t){this.value=t,this._changeDetector.markForCheck()},e.prototype.registerOnChange=function(t){this._controlValueAccessorChangeFn=t},e.prototype.registerOnTouched=function(t){this.onTouched=t},e.prototype.setDisabledState=function(t){this.disabled=t,this._changeDetector.markForCheck()},e}(Object(o.F)(function(){})),u=function(t){function e(e,i,n,r,o){var s=t.call(this,i)||this;return s._changeDetector=n,s._focusMonitor=r,s._radioDispatcher=o,s._uniqueId="mat-radio-"+ ++l,s.id=s._uniqueId,s.change=new a.EventEmitter,s._checked=!1,s._value=null,s._removeUniqueSelectionListener=function(){},s.radioGroup=e,s._removeUniqueSelectionListener=o.listen(function(t,e){t!==s.id&&e===s.name&&(s.checked=!1)}),s}return Object(n.__extends)(e,t),Object.defineProperty(e.prototype,"checked",{get:function(){return this._checked},set:function(t){var e=Object(r.c)(t);this._checked!==e&&(this._checked=e,e&&this.radioGroup&&this.radioGroup.value!==this.value?this.radioGroup.selected=this:!e&&this.radioGroup&&this.radioGroup.value===this.value&&(this.radioGroup.selected=null),e&&this._radioDispatcher.notify(this.id,this.name),this._changeDetector.markForCheck())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return this._value},set:function(t){this._value!==t&&(this._value=t,null!==this.radioGroup&&(this.checked||(this.checked=this.radioGroup.value===t),this.checked&&(this.radioGroup.selected=this)))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"labelPosition",{get:function(){return this._labelPosition||this.radioGroup&&this.radioGroup.labelPosition||"after"},set:function(t){this._labelPosition=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"disabled",{get:function(){return this._disabled||null!==this.radioGroup&&this.radioGroup.disabled},set:function(t){this._disabled=Object(r.c)(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"required",{get:function(){return this._required||this.radioGroup&&this.radioGroup.required},set:function(t){this._required=Object(r.c)(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputId",{get:function(){return(this.id||this._uniqueId)+"-input"},enumerable:!0,configurable:!0}),e.prototype.focus=function(){this._focusMonitor.focusVia(this._inputElement.nativeElement,"keyboard")},e.prototype._markForCheck=function(){this._changeDetector.markForCheck()},e.prototype.ngOnInit=function(){this.radioGroup&&(this.checked=this.radioGroup.value===this._value,this.name=this.radioGroup.name)},e.prototype.ngAfterViewInit=function(){var t=this;this._focusMonitor.monitor(this._inputElement.nativeElement).subscribe(function(e){return t._onInputFocusChange(e)})},e.prototype.ngOnDestroy=function(){this._focusMonitor.stopMonitoring(this._inputElement.nativeElement),this._removeUniqueSelectionListener()},e.prototype._emitChangeEvent=function(){this.change.emit(new s(this,this._value))},e.prototype._isRippleDisabled=function(){return this.disableRipple||this.disabled},e.prototype._onInputClick=function(t){t.stopPropagation()},e.prototype._onInputChange=function(t){t.stopPropagation();var e=this.radioGroup&&this.value!==this.radioGroup.value;this.checked=!0,this._emitChangeEvent(),this.radioGroup&&(this.radioGroup._controlValueAccessorChangeFn(this.value),this.radioGroup._touch(),e&&this.radioGroup._emitChangeEvent())},e.prototype._onInputFocusChange=function(t){this._focusRipple||"keyboard"!==t?t||(this.radioGroup&&this.radioGroup._touch(),this._focusRipple&&(this._focusRipple.fadeOut(),this._focusRipple=null)):this._focusRipple=this._ripple.launch(0,0,{persistent:!0})},e}(Object(o.D)(Object(o.E)(Object(o.I)(function(t){this._elementRef=t})),"accent")),d=function(){}},FVSy:function(t,e,i){"use strict";i.d(e,"d",function(){return n}),i.d(e,"i",function(){return r}),i.d(e,"h",function(){return a}),i.d(e,"b",function(){return o}),i.d(e,"f",function(){return l}),i.d(e,"c",function(){return s}),i.d(e,"a",function(){return c}),i.d(e,"e",function(){return u}),i.d(e,"j",function(){return d}),i.d(e,"g",function(){return h});var n=function(){},r=function(){},a=function(){},o=function(){this.align="start"},l=function(){},s=function(){},c=function(){},u=function(){},d=function(){},h=function(){}},Ourk:function(t,e,i){"use strict";i.d(e,"a",function(){return o}),i.d(e,"b",function(){return l});var n=i("CcnG"),r=(i("9It4"),i("Ip0R"),i("Fzqc"),i("Wf4p")),a=i("dWZg"),o=(i("lLAP"),i("YlbQ"),n["\u0275crt"]({encapsulation:2,styles:[".mat-radio-button{display:inline-block}.mat-radio-label{cursor:pointer;display:inline-flex;align-items:center;white-space:nowrap;vertical-align:middle}.mat-radio-container{box-sizing:border-box;display:inline-block;position:relative;width:20px;height:20px;flex-shrink:0}.mat-radio-outer-circle{box-sizing:border-box;height:20px;left:0;position:absolute;top:0;transition:border-color ease 280ms;width:20px;border-width:2px;border-style:solid;border-radius:50%}.mat-radio-inner-circle{border-radius:50%;box-sizing:border-box;height:20px;left:0;position:absolute;top:0;transition:transform ease 280ms,background-color ease 280ms;width:20px;transform:scale(.001)}.mat-radio-checked .mat-radio-inner-circle{transform:scale(.5)}@media screen and (-ms-high-contrast:active){.mat-radio-checked .mat-radio-inner-circle{border:solid 10px}}.mat-radio-label-content{display:inline-block;order:0;line-height:inherit;padding-left:8px;padding-right:0}[dir=rtl] .mat-radio-label-content{padding-right:8px;padding-left:0}.mat-radio-label-content.mat-radio-label-before{order:-1;padding-left:0;padding-right:8px}[dir=rtl] .mat-radio-label-content.mat-radio-label-before{padding-right:0;padding-left:8px}.mat-radio-disabled,.mat-radio-disabled .mat-radio-label{cursor:default}.mat-radio-ripple{position:absolute;left:calc(50% - 25px);top:calc(50% - 25px);height:50px;width:50px;z-index:1;pointer-events:none}"],data:{}}));function l(t){return n["\u0275vid"](2,[n["\u0275qud"](402653184,1,{_ripple:0}),n["\u0275qud"](402653184,2,{_inputElement:0}),(t()(),n["\u0275eld"](2,0,[["label",1]],null,11,"label",[["class","mat-radio-label"]],[[1,"for",0]],null,null,null,null)),(t()(),n["\u0275eld"](3,0,null,null,5,"div",[["class","mat-radio-container"]],null,null,null,null,null)),(t()(),n["\u0275eld"](4,0,null,null,0,"div",[["class","mat-radio-outer-circle"]],null,null,null,null,null)),(t()(),n["\u0275eld"](5,0,null,null,0,"div",[["class","mat-radio-inner-circle"]],null,null,null,null,null)),(t()(),n["\u0275eld"](6,0,null,null,2,"div",[["class","mat-radio-ripple mat-ripple"],["mat-ripple",""]],[[2,"mat-ripple-unbounded",null]],null,null,null,null)),n["\u0275did"](7,212992,[[1,4]],0,r.x,[n.ElementRef,n.NgZone,a.a,[2,r.m]],{centered:[0,"centered"],radius:[1,"radius"],animation:[2,"animation"],disabled:[3,"disabled"],trigger:[4,"trigger"]},null),n["\u0275pod"](8,{enterDuration:0}),(t()(),n["\u0275eld"](9,0,[[2,0],["input",1]],null,0,"input",[["class","mat-radio-input cdk-visually-hidden"],["type","radio"]],[[8,"id",0],[8,"checked",0],[8,"disabled",0],[8,"tabIndex",0],[1,"name",0],[8,"required",0],[1,"aria-label",0],[1,"aria-labelledby",0],[1,"aria-describedby",0]],[[null,"change"],[null,"click"]],function(t,e,i){var n=!0,r=t.component;return"change"===e&&(n=!1!==r._onInputChange(i)&&n),"click"===e&&(n=!1!==r._onInputClick(i)&&n),n},null,null)),(t()(),n["\u0275eld"](10,0,null,null,3,"div",[["class","mat-radio-label-content"]],[[2,"mat-radio-label-before",null]],null,null,null,null)),(t()(),n["\u0275eld"](11,0,null,null,1,"span",[["style","display:none"]],null,null,null,null,null)),(t()(),n["\u0275ted"](-1,null,["\xa0"])),n["\u0275ncd"](null,0)],function(t,e){var i=e.component;t(e,7,0,!0,23,t(e,8,0,150),i._isRippleDisabled(),n["\u0275nov"](e,2))},function(t,e){var i=e.component;t(e,2,0,i.inputId),t(e,6,0,n["\u0275nov"](e,7).unbounded),t(e,9,0,i.inputId,i.checked,i.disabled,i.tabIndex,i.name,i.required,i.ariaLabel,i.ariaLabelledby,i.ariaDescribedby),t(e,10,0,"before"==i.labelPosition)})}},lzlj:function(t,e,i){"use strict";i.d(e,"a",function(){return r}),i.d(e,"d",function(){return a}),i.d(e,"b",function(){return o}),i.d(e,"c",function(){return l});var n=i("CcnG"),r=(i("FVSy"),i("Fzqc"),i("Wf4p"),n["\u0275crt"]({encapsulation:2,styles:[".mat-card{transition:box-shadow 280ms cubic-bezier(.4,0,.2,1);display:block;position:relative;padding:24px;border-radius:2px}.mat-card:not([class*=mat-elevation-z]){box-shadow:0 3px 1px -2px rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 1px 5px 0 rgba(0,0,0,.12)}.mat-card .mat-divider{position:absolute;left:0;width:100%}[dir=rtl] .mat-card .mat-divider{left:auto;right:0}.mat-card .mat-divider.mat-divider-inset{position:static;margin:0}.mat-card.mat-card-flat{box-shadow:none}@media screen and (-ms-high-contrast:active){.mat-card{outline:solid 1px}}.mat-card-actions,.mat-card-content,.mat-card-subtitle,.mat-card-title{display:block;margin-bottom:16px}.mat-card-actions{margin-left:-16px;margin-right:-16px;padding:8px 0}.mat-card-actions-align-end{display:flex;justify-content:flex-end}.mat-card-image{width:calc(100% + 48px);margin:0 -24px 16px -24px}.mat-card-xl-image{width:240px;height:240px;margin:-8px}.mat-card-footer{display:block;margin:0 -24px -24px -24px}.mat-card-actions .mat-button,.mat-card-actions .mat-raised-button{margin:0 4px}.mat-card-header{display:flex;flex-direction:row}.mat-card-header-text{margin:0 8px}.mat-card-avatar{height:40px;width:40px;border-radius:50%;flex-shrink:0}.mat-card-lg-image,.mat-card-md-image,.mat-card-sm-image{margin:-8px 0}.mat-card-title-group{display:flex;justify-content:space-between;margin:0 -8px}.mat-card-sm-image{width:80px;height:80px}.mat-card-md-image{width:112px;height:112px}.mat-card-lg-image{width:152px;height:152px}@media (max-width:599px){.mat-card{padding:24px 16px}.mat-card-actions{margin-left:-8px;margin-right:-8px}.mat-card-image{width:calc(100% + 32px);margin:16px -16px}.mat-card-title-group{margin:0}.mat-card-xl-image{margin-left:0;margin-right:0}.mat-card-header{margin:-8px 0 0 0}.mat-card-footer{margin-left:-16px;margin-right:-16px}}.mat-card-content>:first-child,.mat-card>:first-child{margin-top:0}.mat-card-content>:last-child:not(.mat-card-footer),.mat-card>:last-child:not(.mat-card-footer){margin-bottom:0}.mat-card-image:first-child{margin-top:-24px}.mat-card>.mat-card-actions:last-child{margin-bottom:-16px;padding-bottom:0}.mat-card-actions .mat-button:first-child,.mat-card-actions .mat-raised-button:first-child{margin-left:0;margin-right:0}.mat-card-subtitle:not(:first-child),.mat-card-title:not(:first-child){margin-top:-4px}.mat-card-header .mat-card-subtitle:not(:first-child){margin-top:-8px}.mat-card>.mat-card-xl-image:first-child{margin-top:-8px}.mat-card>.mat-card-xl-image:last-child{margin-bottom:-8px}"],data:{}}));function a(t){return n["\u0275vid"](2,[n["\u0275ncd"](null,0),n["\u0275ncd"](null,1)],null,null)}var o=n["\u0275crt"]({encapsulation:2,styles:[],data:{}});function l(t){return n["\u0275vid"](2,[n["\u0275ncd"](null,0),(t()(),n["\u0275eld"](1,0,null,null,1,"div",[["class","mat-card-header-text"]],null,null,null,null,null)),n["\u0275ncd"](null,1),n["\u0275ncd"](null,2)],null,null)}},o3x0:function(t,e,i){"use strict";i.d(e,"j",function(){return E}),i.d(e,"a",function(){return y}),i.d(e,"b",function(){return x}),i.d(e,"c",function(){return k}),i.d(e,"d",function(){return C}),i.d(e,"e",function(){return w}),i.d(e,"h",function(){return g}),i.d(e,"g",function(){return D}),i.d(e,"l",function(){return S}),i.d(e,"i",function(){return j}),i.d(e,"f",function(){return P}),i.d(e,"k",function(){return v}),i("ihYY");var n=i("mrSG"),r=i("CcnG"),a=i("4c35"),o=i("YSh2"),l=i("K9Ia"),s=i("pugT"),c=i("lYZG"),u=i("F/XL"),d=i("VnD/"),h=i("t9fZ"),p=i("p0Sj"),m=i("Fzqc"),f=i("eDkP");function b(){throw Error("Attempting to attach dialog content after content is already attached")}var g=function(t){function e(e,i,n,a){var o=t.call(this)||this;return o._elementRef=e,o._focusTrapFactory=i,o._changeDetectorRef=n,o._document=a,o._elementFocusedBeforeDialogWasOpened=null,o._state="enter",o._animationStateChanged=new r.EventEmitter,o._ariaLabelledBy=null,o}return Object(n.__extends)(e,t),e.prototype.attachComponentPortal=function(t){return this._portalOutlet.hasAttached()&&b(),this._savePreviouslyFocusedElement(),this._portalOutlet.attachComponentPortal(t)},e.prototype.attachTemplatePortal=function(t){return this._portalOutlet.hasAttached()&&b(),this._savePreviouslyFocusedElement(),this._portalOutlet.attachTemplatePortal(t)},e.prototype._trapFocus=function(){this._focusTrap||(this._focusTrap=this._focusTrapFactory.create(this._elementRef.nativeElement)),this._config.autoFocus&&this._focusTrap.focusInitialElementWhenReady()},e.prototype._restoreFocus=function(){var t=this._elementFocusedBeforeDialogWasOpened;t&&"function"==typeof t.focus&&t.focus(),this._focusTrap&&this._focusTrap.destroy()},e.prototype._savePreviouslyFocusedElement=function(){var t=this;this._document&&(this._elementFocusedBeforeDialogWasOpened=this._document.activeElement,this._elementRef.nativeElement.focus&&Promise.resolve().then(function(){return t._elementRef.nativeElement.focus()}))},e.prototype._onAnimationDone=function(t){"enter"===t.toState?this._trapFocus():"exit"===t.toState&&this._restoreFocus(),this._animationStateChanged.emit(t)},e.prototype._onAnimationStart=function(t){this._animationStateChanged.emit(t)},e.prototype._startExitAnimation=function(){this._state="exit",this._changeDetectorRef.markForCheck()},e}(a.a),_=0,v=function(){function t(t,e,i,n){void 0===n&&(n="mat-dialog-"+_++);var r=this;this._overlayRef=t,this._containerInstance=e,this.id=n,this.disableClose=this._containerInstance._config.disableClose,this._afterOpen=new l.a,this._afterClosed=new l.a,this._beforeClose=new l.a,this._locationChanges=s.a.EMPTY,e._id=n,e._animationStateChanged.pipe(Object(d.a)(function(t){return"done"===t.phaseName&&"enter"===t.toState}),Object(h.a)(1)).subscribe(function(){r._afterOpen.next(),r._afterOpen.complete()}),e._animationStateChanged.pipe(Object(d.a)(function(t){return"done"===t.phaseName&&"exit"===t.toState}),Object(h.a)(1)).subscribe(function(){r._overlayRef.dispose(),r._locationChanges.unsubscribe(),r._afterClosed.next(r._result),r._afterClosed.complete(),r.componentInstance=null}),t.keydownEvents().pipe(Object(d.a)(function(t){return t.keyCode===o.e&&!r.disableClose})).subscribe(function(){return r.close()}),i&&(this._locationChanges=i.subscribe(function(){r._containerInstance._config.closeOnNavigation&&r.close()}))}return t.prototype.close=function(t){var e=this;this._result=t,this._containerInstance._animationStateChanged.pipe(Object(d.a)(function(t){return"start"===t.phaseName}),Object(h.a)(1)).subscribe(function(){e._beforeClose.next(t),e._beforeClose.complete(),e._overlayRef.detachBackdrop()}),this._containerInstance._startExitAnimation()},t.prototype.afterOpen=function(){return this._afterOpen.asObservable()},t.prototype.afterClosed=function(){return this._afterClosed.asObservable()},t.prototype.beforeClose=function(){return this._beforeClose.asObservable()},t.prototype.backdropClick=function(){return this._overlayRef.backdropClick()},t.prototype.keydownEvents=function(){return this._overlayRef.keydownEvents()},t.prototype.updatePosition=function(t){var e=this._getPositionStrategy();return t&&(t.left||t.right)?t.left?e.left(t.left):e.right(t.right):e.centerHorizontally(),t&&(t.top||t.bottom)?t.top?e.top(t.top):e.bottom(t.bottom):e.centerVertically(),this._overlayRef.updatePosition(),this},t.prototype.updateSize=function(t,e){return void 0===t&&(t="auto"),void 0===e&&(e="auto"),this._getPositionStrategy().width(t).height(e),this._overlayRef.updatePosition(),this},t.prototype._getPositionStrategy=function(){return this._overlayRef.getConfig().positionStrategy},t}(),y=new r.InjectionToken("MatDialogData"),x=new r.InjectionToken("mat-dialog-default-options"),k=new r.InjectionToken("mat-dialog-scroll-strategy",{providedIn:"root",factory:function(){var t=Object(r.inject)(f.c);return function(){return t.scrollStrategies.block()}}});function C(t){return function(){return t.scrollStrategies.block()}}var w=function(){function t(t,e,i,n,r,a,o){var s=this;this._overlay=t,this._injector=e,this._location=i,this._defaultOptions=n,this._scrollStrategy=r,this._parentDialog=a,this._overlayContainer=o,this._openDialogsAtThisLevel=[],this._afterAllClosedAtThisLevel=new l.a,this._afterOpenAtThisLevel=new l.a,this._ariaHiddenElements=new Map,this.afterAllClosed=Object(c.a)(function(){return s.openDialogs.length?s._afterAllClosed:s._afterAllClosed.pipe(Object(p.a)(void 0))})}return Object.defineProperty(t.prototype,"openDialogs",{get:function(){return this._parentDialog?this._parentDialog.openDialogs:this._openDialogsAtThisLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"afterOpen",{get:function(){return this._parentDialog?this._parentDialog.afterOpen:this._afterOpenAtThisLevel},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_afterAllClosed",{get:function(){var t=this._parentDialog;return t?t._afterAllClosed:this._afterAllClosedAtThisLevel},enumerable:!0,configurable:!0}),t.prototype.open=function(t,e){var i=this;if((e=function(t,e){return Object(n.__assign)({},e,t)}(e,this._defaultOptions||new function(){this.role="dialog",this.panelClass="",this.hasBackdrop=!0,this.backdropClass="",this.disableClose=!1,this.width="",this.height="",this.maxWidth="80vw",this.data=null,this.ariaDescribedBy=null,this.ariaLabel=null,this.autoFocus=!0,this.closeOnNavigation=!0})).id&&this.getDialogById(e.id))throw Error('Dialog with id "'+e.id+'" exists already. The dialog id must be unique.');var r=this._createOverlay(e),a=this._attachDialogContainer(r,e),o=this._attachDialogContent(t,a,r,e);return this.openDialogs.length||this._hideNonDialogContentFromAssistiveTechnology(),this.openDialogs.push(o),o.afterClosed().subscribe(function(){return i._removeOpenDialog(o)}),this.afterOpen.next(o),o},t.prototype.closeAll=function(){for(var t=this.openDialogs.length;t--;)this.openDialogs[t].close()},t.prototype.getDialogById=function(t){return this.openDialogs.find(function(e){return e.id===t})},t.prototype._createOverlay=function(t){var e=this._getOverlayConfig(t);return this._overlay.create(e)},t.prototype._getOverlayConfig=function(t){var e=new f.d({positionStrategy:this._overlay.position().global(),scrollStrategy:t.scrollStrategy||this._scrollStrategy(),panelClass:t.panelClass,hasBackdrop:t.hasBackdrop,direction:t.direction,minWidth:t.minWidth,minHeight:t.minHeight,maxWidth:t.maxWidth,maxHeight:t.maxHeight});return t.backdropClass&&(e.backdropClass=t.backdropClass),e},t.prototype._attachDialogContainer=function(t,e){var i=new a.c(g,e.viewContainerRef),n=t.attach(i);return n.instance._config=e,n.instance},t.prototype._attachDialogContent=function(t,e,i,n){var o=new v(i,e,this._location,n.id);if(n.hasBackdrop&&i.backdropClick().subscribe(function(){o.disableClose||o.close()}),t instanceof r.TemplateRef)e.attachTemplatePortal(new a.g(t,null,{$implicit:n.data,dialogRef:o}));else{var l=this._createInjector(n,o,e),s=e.attachComponentPortal(new a.c(t,void 0,l));o.componentInstance=s.instance}return o.updateSize(n.width,n.height).updatePosition(n.position),o},t.prototype._createInjector=function(t,e,i){var n=t&&t.viewContainerRef&&t.viewContainerRef.injector,r=new WeakMap;return r.set(g,i).set(y,t.data).set(v,e),n&&n.get(m.b,null)||r.set(m.b,{value:t.direction,change:Object(u.a)()}),new a.e(n||this._injector,r)},t.prototype._removeOpenDialog=function(t){var e=this.openDialogs.indexOf(t);e>-1&&(this.openDialogs.splice(e,1),this.openDialogs.length||(this._ariaHiddenElements.forEach(function(t,e){t?e.setAttribute("aria-hidden",t):e.removeAttribute("aria-hidden")}),this._ariaHiddenElements.clear(),this._afterAllClosed.next()))},t.prototype._hideNonDialogContentFromAssistiveTechnology=function(){var t=this._overlayContainer.getContainerElement();if(t.parentElement)for(var e=t.parentElement.children,i=e.length-1;i>-1;i--){var n=e[i];n===t||"SCRIPT"===n.nodeName||"STYLE"===n.nodeName||n.hasAttribute("aria-live")||(this._ariaHiddenElements.set(n,n.getAttribute("aria-hidden")),n.setAttribute("aria-hidden","true"))}},t}(),O=0,D=function(){function t(t,e,i){this.dialogRef=t,this._elementRef=e,this._dialog=i,this.ariaLabel="Close dialog"}return t.prototype.ngOnInit=function(){this.dialogRef||(this.dialogRef=R(this._elementRef,this._dialog.openDialogs))},t.prototype.ngOnChanges=function(t){var e=t._matDialogClose||t._matDialogCloseResult;e&&(this.dialogResult=e.currentValue)},t}(),S=function(){function t(t,e,i){this._dialogRef=t,this._elementRef=e,this._dialog=i,this.id="mat-dialog-title-"+O++}return t.prototype.ngOnInit=function(){var t=this;this._dialogRef||(this._dialogRef=R(this._elementRef,this._dialog.openDialogs)),this._dialogRef&&Promise.resolve().then(function(){var e=t._dialogRef._containerInstance;e&&!e._ariaLabelledBy&&(e._ariaLabelledBy=t.id)})},t}(),j=function(){},P=function(){};function R(t,e){for(var i=t.nativeElement.parentElement;i&&!i.classList.contains("mat-dialog-container");)i=i.parentElement;return i?e.find(function(t){return t.id===i.id}):null}var E=function(){}},t68o:function(t,e,i){"use strict";i.d(e,"a",function(){return d});var n=i("CcnG"),r=i("o3x0"),a=i("Ip0R"),o=(i("eDkP"),i("Fzqc"),i("4c35")),l=(i("dWZg"),i("qAlS"),i("Wf4p"),i("lLAP")),s=n["\u0275crt"]({encapsulation:2,styles:[".mat-dialog-container{box-shadow:0 11px 15px -7px rgba(0,0,0,.2),0 24px 38px 3px rgba(0,0,0,.14),0 9px 46px 8px rgba(0,0,0,.12);display:block;padding:24px;border-radius:2px;box-sizing:border-box;overflow:auto;outline:0;width:100%;height:100%}@media screen and (-ms-high-contrast:active){.mat-dialog-container{outline:solid 1px}}.mat-dialog-content{display:block;margin:0 -24px;padding:0 24px;max-height:65vh;overflow:auto;-webkit-overflow-scrolling:touch}.mat-dialog-title{margin:0 0 20px;display:block}.mat-dialog-actions{padding:12px 0;display:flex;flex-wrap:wrap;margin-bottom:-24px}.mat-dialog-actions[align=end]{justify-content:flex-end}.mat-dialog-actions[align=center]{justify-content:center}.mat-dialog-actions .mat-button+.mat-button,.mat-dialog-actions .mat-button+.mat-raised-button,.mat-dialog-actions .mat-raised-button+.mat-button,.mat-dialog-actions .mat-raised-button+.mat-raised-button{margin-left:8px}[dir=rtl] .mat-dialog-actions .mat-button+.mat-button,[dir=rtl] .mat-dialog-actions .mat-button+.mat-raised-button,[dir=rtl] .mat-dialog-actions .mat-raised-button+.mat-button,[dir=rtl] .mat-dialog-actions .mat-raised-button+.mat-raised-button{margin-left:0;margin-right:8px}"],data:{animation:[{type:7,name:"slideDialog",definitions:[{type:0,name:"enter",styles:{type:6,styles:{transform:"none",opacity:1},offset:null},options:void 0},{type:0,name:"void",styles:{type:6,styles:{transform:"translate3d(0, 25%, 0) scale(0.9)",opacity:0},offset:null},options:void 0},{type:0,name:"exit",styles:{type:6,styles:{transform:"translate3d(0, 25%, 0)",opacity:0},offset:null},options:void 0},{type:1,expr:"* => *",animation:{type:4,styles:null,timings:"400ms cubic-bezier(0.25, 0.8, 0.25, 1)"},options:null}],options:{}}]}});function c(t){return n["\u0275vid"](0,[(t()(),n["\u0275and"](0,null,null,0))],null,null)}function u(t){return n["\u0275vid"](0,[n["\u0275qud"](402653184,1,{_portalOutlet:0}),(t()(),n["\u0275and"](16777216,null,null,1,null,c)),n["\u0275did"](2,212992,[[1,4]],0,o.b,[n.ComponentFactoryResolver,n.ViewContainerRef],{portal:[0,"portal"]},null)],function(t,e){t(e,2,0,"")},null)}var d=n["\u0275ccf"]("mat-dialog-container",r.h,function(t){return n["\u0275vid"](0,[(t()(),n["\u0275eld"](0,0,null,null,1,"mat-dialog-container",[["class","mat-dialog-container"],["tabindex","-1"]],[[1,"id",0],[1,"role",0],[1,"aria-labelledby",0],[1,"aria-label",0],[1,"aria-describedby",0],[40,"@slideDialog",0]],[["component","@slideDialog.start"],["component","@slideDialog.done"]],function(t,e,i){var r=!0;return"component:@slideDialog.start"===e&&(r=!1!==n["\u0275nov"](t,1)._onAnimationStart(i)&&r),"component:@slideDialog.done"===e&&(r=!1!==n["\u0275nov"](t,1)._onAnimationDone(i)&&r),r},u,s)),n["\u0275did"](1,49152,null,0,r.h,[n.ElementRef,l.h,n.ChangeDetectorRef,[2,a.DOCUMENT]],null,null)],null,function(t,e){t(e,0,0,n["\u0275nov"](e,1)._id,null==n["\u0275nov"](e,1)._config?null:n["\u0275nov"](e,1)._config.role,null!=n["\u0275nov"](e,1)._config&&n["\u0275nov"](e,1)._config.ariaLabel?null:n["\u0275nov"](e,1)._ariaLabelledBy,null==n["\u0275nov"](e,1)._config?null:n["\u0275nov"](e,1)._config.ariaLabel,(null==n["\u0275nov"](e,1)._config?null:n["\u0275nov"](e,1)._config.ariaDescribedBy)||null,n["\u0275nov"](e,1)._state)})},{},{},[])},uM4N:function(t,e,i){"use strict";i.d(e,"a",function(){return a}),i.d(e,"b",function(){return o});var n=i("CcnG"),r=(i("w+lc"),i("Ip0R")),a=(i("ZYjt"),i("Wf4p"),i("Fzqc"),i("gIcY"),i("lLAP"),n["\u0275crt"]({encapsulation:2,styles:[".mat-slider{display:inline-block;position:relative;box-sizing:border-box;padding:8px;outline:0;vertical-align:middle}.mat-slider-wrapper{position:absolute}.mat-slider-track-wrapper{position:absolute;top:0;left:0;overflow:hidden}.mat-slider-track-fill{position:absolute;transform-origin:0 0;transition:transform .4s cubic-bezier(.25,.8,.25,1),background-color .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-track-background{position:absolute;transform-origin:100% 100%;transition:transform .4s cubic-bezier(.25,.8,.25,1),background-color .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-ticks-container{position:absolute;left:0;top:0;overflow:hidden}.mat-slider-ticks{background-repeat:repeat;background-clip:content-box;box-sizing:border-box;opacity:0;transition:opacity .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-thumb-container{position:absolute;z-index:1;transition:transform .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-focus-ring{position:absolute;width:30px;height:30px;border-radius:50%;transform:scale(0);opacity:0;transition:transform .4s cubic-bezier(.25,.8,.25,1),background-color .4s cubic-bezier(.25,.8,.25,1),opacity .4s cubic-bezier(.25,.8,.25,1)}.cdk-keyboard-focused .mat-slider-focus-ring,.cdk-program-focused .mat-slider-focus-ring{transform:scale(1);opacity:1}.mat-slider:not(.mat-slider-disabled) .mat-slider-thumb,.mat-slider:not(.mat-slider-disabled) .mat-slider-thumb-label{cursor:-webkit-grab;cursor:grab}.mat-slider-sliding:not(.mat-slider-disabled) .mat-slider-thumb,.mat-slider-sliding:not(.mat-slider-disabled) .mat-slider-thumb-label,.mat-slider:not(.mat-slider-disabled) .mat-slider-thumb-label:active,.mat-slider:not(.mat-slider-disabled) .mat-slider-thumb:active{cursor:-webkit-grabbing;cursor:grabbing}.mat-slider-thumb{position:absolute;right:-10px;bottom:-10px;box-sizing:border-box;width:20px;height:20px;border:3px solid transparent;border-radius:50%;transform:scale(.7);transition:transform .4s cubic-bezier(.25,.8,.25,1),background-color .4s cubic-bezier(.25,.8,.25,1),border-color .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-thumb-label{display:none;align-items:center;justify-content:center;position:absolute;width:28px;height:28px;border-radius:50%;transition:transform .4s cubic-bezier(.25,.8,.25,1),border-radius .4s cubic-bezier(.25,.8,.25,1),background-color .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-thumb-label-text{z-index:1;opacity:0;transition:opacity .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-sliding .mat-slider-thumb-container,.mat-slider-sliding .mat-slider-track-background,.mat-slider-sliding .mat-slider-track-fill{transition-duration:0s}.mat-slider-has-ticks .mat-slider-wrapper::after{content:'';position:absolute;border-width:0;border-style:solid;opacity:0;transition:opacity .4s cubic-bezier(.25,.8,.25,1)}.mat-slider-has-ticks.cdk-focused:not(.mat-slider-hide-last-tick) .mat-slider-wrapper::after,.mat-slider-has-ticks:hover:not(.mat-slider-hide-last-tick) .mat-slider-wrapper::after{opacity:1}.mat-slider-has-ticks.cdk-focused:not(.mat-slider-disabled) .mat-slider-ticks,.mat-slider-has-ticks:hover:not(.mat-slider-disabled) .mat-slider-ticks{opacity:1}.mat-slider-thumb-label-showing .mat-slider-focus-ring{transform:scale(0);opacity:0}.mat-slider-thumb-label-showing .mat-slider-thumb-label{display:flex}.mat-slider-axis-inverted .mat-slider-track-fill{transform-origin:100% 100%}.mat-slider-axis-inverted .mat-slider-track-background{transform-origin:0 0}.mat-slider:not(.mat-slider-disabled).cdk-focused.mat-slider-thumb-label-showing .mat-slider-thumb{transform:scale(0)}.mat-slider:not(.mat-slider-disabled).cdk-focused .mat-slider-thumb-label{border-radius:50% 50% 0}.mat-slider:not(.mat-slider-disabled).cdk-focused .mat-slider-thumb-label-text{opacity:1}.mat-slider:not(.mat-slider-disabled).cdk-mouse-focused .mat-slider-thumb,.mat-slider:not(.mat-slider-disabled).cdk-program-focused .mat-slider-thumb,.mat-slider:not(.mat-slider-disabled).cdk-touch-focused .mat-slider-thumb{border-width:2px;transform:scale(1)}.mat-slider-disabled .mat-slider-focus-ring{transform:scale(0);opacity:0}.mat-slider-disabled .mat-slider-thumb{border-width:4px;transform:scale(.5)}.mat-slider-disabled .mat-slider-thumb-label{display:none}.mat-slider-horizontal{height:48px;min-width:128px}.mat-slider-horizontal .mat-slider-wrapper{height:2px;top:23px;left:8px;right:8px}.mat-slider-horizontal .mat-slider-wrapper::after{height:2px;border-left-width:2px;right:0;top:0}.mat-slider-horizontal .mat-slider-track-wrapper{height:2px;width:100%}.mat-slider-horizontal .mat-slider-track-fill{height:2px;width:100%;transform:scaleX(0)}.mat-slider-horizontal .mat-slider-track-background{height:2px;width:100%;transform:scaleX(1)}.mat-slider-horizontal .mat-slider-ticks-container{height:2px;width:100%}@media screen and (-ms-high-contrast:active){.mat-slider-horizontal .mat-slider-ticks-container{height:0;outline:solid 2px;top:1px}}.mat-slider-horizontal .mat-slider-ticks{height:2px;width:100%}.mat-slider-horizontal .mat-slider-thumb-container{width:100%;height:0;top:50%}.mat-slider-horizontal .mat-slider-focus-ring{top:-15px;right:-15px}.mat-slider-horizontal .mat-slider-thumb-label{right:-14px;top:-40px;transform:translateY(26px) scale(.01) rotate(45deg)}.mat-slider-horizontal .mat-slider-thumb-label-text{transform:rotate(-45deg)}.mat-slider-horizontal.cdk-focused .mat-slider-thumb-label{transform:rotate(45deg)}.mat-slider-vertical{width:48px;min-height:128px}.mat-slider-vertical .mat-slider-wrapper{width:2px;top:8px;bottom:8px;left:23px}.mat-slider-vertical .mat-slider-wrapper::after{width:2px;border-top-width:2px;bottom:0;left:0}.mat-slider-vertical .mat-slider-track-wrapper{height:100%;width:2px}.mat-slider-vertical .mat-slider-track-fill{height:100%;width:2px;transform:scaleY(0)}.mat-slider-vertical .mat-slider-track-background{height:100%;width:2px;transform:scaleY(1)}.mat-slider-vertical .mat-slider-ticks-container{width:2px;height:100%}@media screen and (-ms-high-contrast:active){.mat-slider-vertical .mat-slider-ticks-container{width:0;outline:solid 2px;left:1px}}.mat-slider-vertical .mat-slider-focus-ring{bottom:-15px;left:-15px}.mat-slider-vertical .mat-slider-ticks{width:2px;height:100%}.mat-slider-vertical .mat-slider-thumb-container{height:100%;width:0;left:50%}.mat-slider-vertical .mat-slider-thumb{-webkit-backface-visibility:hidden;backface-visibility:hidden}.mat-slider-vertical .mat-slider-thumb-label{bottom:-14px;left:-40px;transform:translateX(26px) scale(.01) rotate(-45deg)}.mat-slider-vertical .mat-slider-thumb-label-text{transform:rotate(45deg)}.mat-slider-vertical.cdk-focused .mat-slider-thumb-label{transform:rotate(-45deg)}[dir=rtl] .mat-slider-wrapper::after{left:0;right:auto}[dir=rtl] .mat-slider-horizontal .mat-slider-track-fill{transform-origin:100% 100%}[dir=rtl] .mat-slider-horizontal .mat-slider-track-background{transform-origin:0 0}[dir=rtl] .mat-slider-horizontal.mat-slider-axis-inverted .mat-slider-track-fill{transform-origin:0 0}[dir=rtl] .mat-slider-horizontal.mat-slider-axis-inverted .mat-slider-track-background{transform-origin:100% 100%}"],data:{}}));function o(t){return n["\u0275vid"](2,[n["\u0275qud"](402653184,1,{_sliderWrapper:0}),(t()(),n["\u0275eld"](1,0,[[1,0],["sliderWrapper",1]],null,16,"div",[["class","mat-slider-wrapper"]],null,null,null,null,null)),(t()(),n["\u0275eld"](2,0,null,null,4,"div",[["class","mat-slider-track-wrapper"]],null,null,null,null,null)),(t()(),n["\u0275eld"](3,0,null,null,1,"div",[["class","mat-slider-track-background"]],null,null,null,null,null)),n["\u0275did"](4,278528,null,0,r.NgStyle,[n.KeyValueDiffers,n.ElementRef,n.Renderer2],{ngStyle:[0,"ngStyle"]},null),(t()(),n["\u0275eld"](5,0,null,null,1,"div",[["class","mat-slider-track-fill"]],null,null,null,null,null)),n["\u0275did"](6,278528,null,0,r.NgStyle,[n.KeyValueDiffers,n.ElementRef,n.Renderer2],{ngStyle:[0,"ngStyle"]},null),(t()(),n["\u0275eld"](7,0,null,null,3,"div",[["class","mat-slider-ticks-container"]],null,null,null,null,null)),n["\u0275did"](8,278528,null,0,r.NgStyle,[n.KeyValueDiffers,n.ElementRef,n.Renderer2],{ngStyle:[0,"ngStyle"]},null),(t()(),n["\u0275eld"](9,0,null,null,1,"div",[["class","mat-slider-ticks"]],null,null,null,null,null)),n["\u0275did"](10,278528,null,0,r.NgStyle,[n.KeyValueDiffers,n.ElementRef,n.Renderer2],{ngStyle:[0,"ngStyle"]},null),(t()(),n["\u0275eld"](11,0,null,null,6,"div",[["class","mat-slider-thumb-container"]],null,null,null,null,null)),n["\u0275did"](12,278528,null,0,r.NgStyle,[n.KeyValueDiffers,n.ElementRef,n.Renderer2],{ngStyle:[0,"ngStyle"]},null),(t()(),n["\u0275eld"](13,0,null,null,0,"div",[["class","mat-slider-focus-ring"]],null,null,null,null,null)),(t()(),n["\u0275eld"](14,0,null,null,0,"div",[["class","mat-slider-thumb"]],null,null,null,null,null)),(t()(),n["\u0275eld"](15,0,null,null,2,"div",[["class","mat-slider-thumb-label"]],null,null,null,null,null)),(t()(),n["\u0275eld"](16,0,null,null,1,"span",[["class","mat-slider-thumb-label-text"]],null,null,null,null,null)),(t()(),n["\u0275ted"](17,null,["",""]))],function(t,e){var i=e.component;t(e,4,0,i._trackBackgroundStyles),t(e,6,0,i._trackFillStyles),t(e,8,0,i._ticksContainerStyles),t(e,10,0,i._ticksStyles),t(e,12,0,i._thumbContainerStyles)},function(t,e){t(e,17,0,e.component.displayValue)})}},"w+lc":function(t,e,i){"use strict";i.d(e,"b",function(){return u}),i.d(e,"a",function(){return c});var n=i("mrSG"),r=i("n6gG"),a=i("YSh2"),o=i("CcnG"),l=(i("gIcY"),i("Wf4p")),s=i("pugT"),c=function(t){function e(e,i,n,r,a){var l=t.call(this,e)||this;return l._focusMonitor=i,l._changeDetectorRef=n,l._dir=r,l._invert=!1,l._max=100,l._min=0,l._step=1,l._thumbLabel=!1,l._tickInterval=0,l._value=null,l._vertical=!1,l.change=new o.EventEmitter,l.input=new o.EventEmitter,l.onTouched=function(){},l._percent=0,l._isSliding=!1,l._isActive=!1,l._tickIntervalPercent=0,l._sliderDimensions=null,l._controlValueAccessorChangeFn=function(){},l._dirChangeSubscription=s.a.EMPTY,l.tabIndex=parseInt(a)||0,l}return Object(n.__extends)(e,t),Object.defineProperty(e.prototype,"invert",{get:function(){return this._invert},set:function(t){this._invert=Object(r.c)(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},set:function(t){this._max=Object(r.e)(t,this._max),this._percent=this._calculatePercentage(this._value),this._changeDetectorRef.markForCheck()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"min",{get:function(){return this._min},set:function(t){this._min=Object(r.e)(t,this._min),null===this._value&&(this.value=this._min),this._percent=this._calculatePercentage(this._value),this._changeDetectorRef.markForCheck()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"step",{get:function(){return this._step},set:function(t){this._step=Object(r.e)(t,this._step),this._step%1!=0&&(this._roundToDecimal=this._step.toString().split(".").pop().length),this._changeDetectorRef.markForCheck()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"thumbLabel",{get:function(){return this._thumbLabel},set:function(t){this._thumbLabel=Object(r.c)(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tickInterval",{get:function(){return this._tickInterval},set:function(t){this._tickInterval="auto"===t?"auto":"number"==typeof t||"string"==typeof t?Object(r.e)(t,this._tickInterval):0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"value",{get:function(){return null===this._value&&(this.value=this._min),this._value},set:function(t){t!==this._value&&(this._value=Object(r.e)(t),this._percent=this._calculatePercentage(this._value),this._changeDetectorRef.markForCheck())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vertical",{get:function(){return this._vertical},set:function(t){this._vertical=Object(r.c)(t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"displayValue",{get:function(){return this.displayWith?this.displayWith(this.value):this._roundToDecimal&&this.value&&this.value%1!=0?this.value.toFixed(this._roundToDecimal):this.value||0},enumerable:!0,configurable:!0}),e.prototype.focus=function(){this._focusHostElement()},e.prototype.blur=function(){this._blurHostElement()},Object.defineProperty(e.prototype,"percent",{get:function(){return this._clamp(this._percent)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_invertAxis",{get:function(){return this.vertical?!this.invert:this.invert},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_isMinValue",{get:function(){return 0===this.percent},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_thumbGap",{get:function(){return this.disabled?7:this._isMinValue&&!this.thumbLabel?this._isActive?10:7:0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_trackBackgroundStyles",{get:function(){var t=this.vertical?"Y":"X";return{transform:"translate"+t+"("+(this._invertMouseCoords?"-":"")+this._thumbGap+"px) scale"+t+"("+(1-this.percent)+")"}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_trackFillStyles",{get:function(){var t=this.vertical?"Y":"X";return{transform:"translate"+t+"("+(this._invertMouseCoords?"":"-")+this._thumbGap+"px) scale"+t+"("+this.percent+")"}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_ticksContainerStyles",{get:function(){return{transform:"translate"+(this.vertical?"Y":"X")+"("+(this.vertical||"rtl"!=this._direction?"-":"")+this._tickIntervalPercent/2*100+"%)"}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_ticksStyles",{get:function(){var t=100*this._tickIntervalPercent,e={backgroundSize:this.vertical?"2px "+t+"%":t+"% 2px",transform:"translateZ(0) translate"+(this.vertical?"Y":"X")+"("+(this.vertical||"rtl"!=this._direction?"":"-")+t/2+"%)"+(this.vertical||"rtl"!=this._direction?"":" rotate(180deg)")};return this._isMinValue&&this._thumbGap&&(e["padding"+(this.vertical?this._invertAxis?"Bottom":"Top":this._invertAxis?"Right":"Left")]=this._thumbGap+"px"),e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_thumbContainerStyles",{get:function(){return{transform:"translate"+(this.vertical?"Y":"X")+"(-"+100*(("rtl"!=this._direction||this.vertical?this._invertAxis:!this._invertAxis)?this.percent:1-this.percent)+"%)"}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_invertMouseCoords",{get:function(){return"rtl"!=this._direction||this.vertical?this._invertAxis:!this._invertAxis},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_direction",{get:function(){return this._dir&&"rtl"==this._dir.value?"rtl":"ltr"},enumerable:!0,configurable:!0}),e.prototype.ngOnInit=function(){var t=this;this._focusMonitor.monitor(this._elementRef.nativeElement,!0).subscribe(function(e){t._isActive=!!e&&"keyboard"!==e,t._changeDetectorRef.detectChanges()}),this._dir&&(this._dirChangeSubscription=this._dir.change.subscribe(function(){t._changeDetectorRef.markForCheck()}))},e.prototype.ngOnDestroy=function(){this._focusMonitor.stopMonitoring(this._elementRef.nativeElement),this._dirChangeSubscription.unsubscribe()},e.prototype._onMouseenter=function(){this.disabled||(this._sliderDimensions=this._getSliderDimensions(),this._updateTickIntervalPercent())},e.prototype._onClick=function(t){if(!this.disabled){var e=this.value;this._isSliding=!1,this._focusHostElement(),this._updateValueFromPosition({x:t.clientX,y:t.clientY}),e!=this.value&&(this._emitInputEvent(),this._emitChangeEvent())}},e.prototype._onSlide=function(t){if(!this.disabled){this._isSliding||this._onSlideStart(null),t.preventDefault();var e=this.value;this._updateValueFromPosition({x:t.center.x,y:t.center.y}),e!=this.value&&this._emitInputEvent()}},e.prototype._onSlideStart=function(t){this.disabled||this._isSliding||(this._onMouseenter(),this._isSliding=!0,this._focusHostElement(),this._valueOnSlideStart=this.value,t&&(this._updateValueFromPosition({x:t.center.x,y:t.center.y}),t.preventDefault()))},e.prototype._onSlideEnd=function(){this._isSliding=!1,this._valueOnSlideStart==this.value||this.disabled||this._emitChangeEvent(),this._valueOnSlideStart=null},e.prototype._onFocus=function(){this._sliderDimensions=this._getSliderDimensions(),this._updateTickIntervalPercent()},e.prototype._onBlur=function(){this.onTouched()},e.prototype._onKeydown=function(t){if(!this.disabled){var e=this.value;switch(t.keyCode){case a.j:this._increment(10);break;case a.i:this._increment(-10);break;case a.c:this.value=this.max;break;case a.f:this.value=this.min;break;case a.g:this._increment("rtl"==this._direction?1:-1);break;case a.n:this._increment(1);break;case a.k:this._increment("rtl"==this._direction?-1:1);break;case a.b:this._increment(-1);break;default:return}e!=this.value&&(this._emitInputEvent(),this._emitChangeEvent()),this._isSliding=!0,t.preventDefault()}},e.prototype._onKeyup=function(){this._isSliding=!1},e.prototype._increment=function(t){this.value=this._clamp((this.value||0)+this.step*t,this.min,this.max)},e.prototype._updateValueFromPosition=function(t){if(this._sliderDimensions){var e=this._clamp(((this.vertical?t.y:t.x)-(this.vertical?this._sliderDimensions.top:this._sliderDimensions.left))/(this.vertical?this._sliderDimensions.height:this._sliderDimensions.width));if(this._invertMouseCoords&&(e=1-e),0===e)this.value=this.min;else if(1===e)this.value=this.max;else{var i=this._calculateValue(e),n=Math.round((i-this.min)/this.step)*this.step+this.min;this._roundToDecimal&&(n=parseFloat(n.toFixed(this._roundToDecimal))),this.value=this._clamp(n,this.min,this.max)}}},e.prototype._emitChangeEvent=function(){this._controlValueAccessorChangeFn(this.value),this.change.emit(this._createChangeEvent())},e.prototype._emitInputEvent=function(){this.input.emit(this._createChangeEvent())},e.prototype._updateTickIntervalPercent=function(){if(this.tickInterval&&this._sliderDimensions)if("auto"==this.tickInterval){var t=this.vertical?this._sliderDimensions.height:this._sliderDimensions.width,e=Math.ceil(30/(t*this.step/(this.max-this.min)));this._tickIntervalPercent=e*this.step/t}else this._tickIntervalPercent=this.tickInterval*this.step/(this.max-this.min)},e.prototype._createChangeEvent=function(t){void 0===t&&(t=this.value);var e=new function(){};return e.source=this,e.value=t,e},e.prototype._calculatePercentage=function(t){return((t||0)-this.min)/(this.max-this.min)},e.prototype._calculateValue=function(t){return this.min+t*(this.max-this.min)},e.prototype._clamp=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),Math.max(e,Math.min(t,i))},e.prototype._getSliderDimensions=function(){return this._sliderWrapper?this._sliderWrapper.nativeElement.getBoundingClientRect():null},e.prototype._focusHostElement=function(){this._elementRef.nativeElement.focus()},e.prototype._blurHostElement=function(){this._elementRef.nativeElement.blur()},e.prototype.writeValue=function(t){this.value=t},e.prototype.registerOnChange=function(t){this._controlValueAccessorChangeFn=t},e.prototype.registerOnTouched=function(t){this.onTouched=t},e.prototype.setDisabledState=function(t){this.disabled=t},e}(Object(l.I)(Object(l.D)(Object(l.F)(function(t){this._elementRef=t}),"accent"))),u=function(){}}}]);
46,888
46,888
0.755609
1e09124c3e7daaf22bbf0f0d9f6a13fece1d9039
1,548
js
JavaScript
src/content.js
RalkeyOfficial/kevinator-extension
19b966fe0c3956826d5fac9249880d04ceb1bd59
[ "MIT" ]
null
null
null
src/content.js
RalkeyOfficial/kevinator-extension
19b966fe0c3956826d5fac9249880d04ceb1bd59
[ "MIT" ]
null
null
null
src/content.js
RalkeyOfficial/kevinator-extension
19b966fe0c3956826d5fac9249880d04ceb1bd59
[ "MIT" ]
null
null
null
const images = [ "https://raw.githubusercontent.com/RalkeyOfficial/kevinator-extension/main/src/images/FaceApp_1642673262498.jpg", "https://raw.githubusercontent.com/RalkeyOfficial/kevinator-extension/main/src/images/IMG20220118164805.jpg", "https://raw.githubusercontent.com/RalkeyOfficial/kevinator-extension/main/src/images/old_kevert.jpeg" ]; setInterval(function() { let imageCollection = document.images; let divImgCollection = getDivWithBackground(); // for img tags for(img in imageCollection) { if (imageCollection[img].src == "" || imageCollection[img].src == "#") continue; if (images.includes(imageCollection[img].src) ) continue; imageCollection[img].src = chooseRandomImage(); } // for div's with background-image attribute for(divElement in divImgCollection) { const url = $(divImgCollection[divElement]).css('background-image').slice(5, $(divImgCollection[divElement]).css('background-image').length - 2); if (url == "" || url == "none") continue; if (images.includes(url ) ) continue; $(divImgCollection[divElement]).css('background-image', `url("${chooseRandomImage()}")`); } }, 300); function chooseRandomImage() { let random = Math.floor(Math.random() * images.length); return images[random]; } function getDivWithBackground() { const regex = /url\("[^"]*"\)/ let items = $('div').filter(function() { return $(this).css('background-image').match(regex); }); return items }
31.591837
153
0.667313
1e09fbc92daba209c5fbe98e1c4fc91dbcf93698
897
js
JavaScript
src/front-end/admin-main/src/api/menu.js
NeuCharFramework/Ncf
0cd815d5497bf8f18b64cdc6b487fd624e8591df
[ "Apache-2.0" ]
null
null
null
src/front-end/admin-main/src/api/menu.js
NeuCharFramework/Ncf
0cd815d5497bf8f18b64cdc6b487fd624e8591df
[ "Apache-2.0" ]
null
null
null
src/front-end/admin-main/src/api/menu.js
NeuCharFramework/Ncf
0cd815d5497bf8f18b64cdc6b487fd624e8591df
[ "Apache-2.0" ]
null
null
null
/* * 模块:Senparc.Areas.Admin:SysMenuAppService * 菜单 * */ import request from '@/utils/request' const baseUrl = "/api/Senparc.Areas.Admin/SysMenuAppService/Areas.Admin_SysMenuAppService" //创建、更新 export function createOrUpdateMenu(data) { return request({ url: `${baseUrl}.CreateOrUpdateAsync`, method: 'post', data }) } //删除 export function deleteMenu(params) { return request({ url: `${baseUrl}.DeleteMenuAsync`, method: 'delete', params }) } //列表 export function getAllMenus(params) { return request({ url: `${baseUrl}.GetAllMenusTreeAsync`, method: 'get', params }) } //列表-子项 export function getMenus(params) { return request({ url: `${baseUrl}.GetMenusAsync`, method: 'get', params }) } //详情 export function GetMenuInfo(params) { return request({ url: `${baseUrl}.GetMenuAsync`, method: 'get', params }) }
16.017857
90
0.652174
1e0a5204d657b4304e5c85a7676c9a6fe814e85a
550
js
JavaScript
php/00haizeiwangec/js/queryform.js
shifushihuaidan/op11
b16fd69b5501f914f2312fd4618fd2961cd23135
[ "MIT" ]
null
null
null
php/00haizeiwangec/js/queryform.js
shifushihuaidan/op11
b16fd69b5501f914f2312fd4618fd2961cd23135
[ "MIT" ]
null
null
null
php/00haizeiwangec/js/queryform.js
shifushihuaidan/op11
b16fd69b5501f914f2312fd4618fd2961cd23135
[ "MIT" ]
null
null
null
// JavaScript Document function queryrst(form) { var name = form.name.value; var formid = form.formid.value; if(name == '' && formid == ''){ alert('用户或订单号至少有一个不能为空'); form.name.focus(); return false; } var url = "query.php?vendee="+name+"&formid="+formid; xmlhttp.open("GET",url,true); xmlhttp.onreadystatechange = showfm; xmlhttp.send(null); } function showfm(){ if(xmlhttp.readyState == 4){ var msg = xmlhttp.responseText; if(msg == '0'){ exam.innerHTML = ''; alert('没有查询结果'); }else{ exam.innerHTML = msg; } } }
22
54
0.636364
1e0b964c7d8e8e8b4da4d0163fd78e422ad89683
2,614
js
JavaScript
test/unit/services/user-service-test.js
GrowMoi/haedus-front-end
6caef7a8c7829448bb664d85a46186db4a568986
[ "Apache-2.0" ]
null
null
null
test/unit/services/user-service-test.js
GrowMoi/haedus-front-end
6caef7a8c7829448bb664d85a46186db4a568986
[ "Apache-2.0" ]
null
null
null
test/unit/services/user-service-test.js
GrowMoi/haedus-front-end
6caef7a8c7829448bb664d85a46186db4a568986
[ "Apache-2.0" ]
null
null
null
(function() { 'use strict'; describe('UserService', function() { var service, $httpBackend, username, expectedUrl, ENV, PopupService, ModalService, $state; beforeEach(module('moi.services', function($provide) { $provide.factory('PopupService', function() { return { showModel: function() { return null; } }; }); $provide.factory('ModalService', function(){ return { showModel: function(){ return null; } }; }); })); beforeEach(angular.mock.module(function ($provide) { $provide.provider('$state', function () { return { $get: function () { return { go: function(){ return null; } }; } }; }); })); beforeEach(function() { module('config', function($provide) { $provide.constant('ENV', { name: 'development', apiHost: 'http://localhost:5000' }); $provide.constant('$ionicPopup', { alert: sinon.stub() }); }); }); beforeEach(inject( function(_$httpBackend_, _UserService_, _ENV_, _PopupService_, _$state_, _ModalService_) { $httpBackend = _$httpBackend_; service = _UserService_; ENV = _ENV_; PopupService = _PopupService_; $state = _$state_; ModalService = _ModalService_; })); afterEach(function() { $httpBackend.verifyNoOutstandingRequest(); $httpBackend.verifyNoOutstandingExpectation(); }); describe('#service', function() { beforeEach(function() { /*jshint camelcase: false */ username = 'jhondoe'; expectedUrl = ENV.apiHost + '/api/users/profile?username=' + username; }); it('should do a request to /api/users/profile', function(){ var objectToRespond = { name: 'jhon doe', city: 'loja', age: '12' }; $httpBackend.expectGET(expectedUrl) .respond(objectToRespond); service.profile(username); $httpBackend.flush(); }); it('should not call to PopupService when respond with 404', function() { var spy = sinon.spy(PopupService, 'showModel'); $httpBackend.expectGET(expectedUrl).respond(404); service.profile(username).then(function(){ chai.expect(spy.called).to.not.be.equal(true); }); $httpBackend.flush(); }); }); }); })();
24.895238
78
0.522953
1e0c265e7196a8b6b2655d7e9e952a4f5b2bb095
281
js
JavaScript
webpack.config.js
rsocket/rsocket-demo
f2444aee30f637cc6a02db40c73b5056dcedae25
[ "Apache-2.0" ]
16
2017-10-06T12:13:58.000Z
2022-03-07T06:28:42.000Z
webpack.config.js
yschimke/rsocket-demo
9f97d960b17ff58d176615078bdac0659111b8fb
[ "Apache-2.0" ]
21
2017-07-10T12:05:08.000Z
2021-03-05T17:31:13.000Z
webpack.config.js
rsocket/rsocket-demo
f2444aee30f637cc6a02db40c73b5056dcedae25
[ "Apache-2.0" ]
6
2017-12-01T19:16:55.000Z
2021-04-21T23:48:39.000Z
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: path.resolve(__dirname, './src/main/js/app.js'), output: { path: path.resolve(__dirname, './src/main/resources/static/js/'), filename: 'app.js', }, mode: 'development', };
23.416667
69
0.640569
1e0c7a20223e1ac1d2cc046c85b374bfe863662a
2,564
js
JavaScript
pc_meiduo/front_end_pc/js/order_success.js
lyq919233278/meiduo_mall
c551896ffc9bb00bb1c4ad7e15825e8e096e571b
[ "MIT" ]
1
2020-12-16T02:45:09.000Z
2020-12-16T02:45:09.000Z
pc_meiduo/front_end_pc/js/order_success.js
lyq919233278/meiduo_mall
c551896ffc9bb00bb1c4ad7e15825e8e096e571b
[ "MIT" ]
9
2021-01-06T20:09:46.000Z
2022-02-27T09:57:27.000Z
pc_meiduo/front_end_pc/js/order_success.js
lyq919233278/meiduo_mall
c551896ffc9bb00bb1c4ad7e15825e8e096e571b
[ "MIT" ]
null
null
null
var vm = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { host, username: '', user_id: sessionStorage.user_id || localStorage.user_id, token: sessionStorage.token || localStorage.token, order_id: '', amount: 0, pay_method: '', }, computed: { operate: function(){ if (this.pay_method==1){ return '继续购物'; } else { return '去支付'; } } }, mounted: function(){ this.order_id = this.get_query_string('order_id'); this.amount = this.get_query_string('amount'); this.pay_method = this.get_query_string('pay'); // 获取cookie中的用户名 this.username = getCookie('username'); }, methods: { // 退出登录按钮 logoutfunc: function () { var url = this.host + '/logout/'; axios.delete(url, { responseType: 'json', withCredentials:true, }) .then(response => { if (response.data.code == 1) { location.href = 'login.html'; } else { alert(response.data.errmsg) } }) .catch(error => { console.log(error); }) }, // 获取url路径参数 get_query_string: function(name){ var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); var r = window.location.search.substr(1).match(reg); if (r != null) { return decodeURI(r[2]); } return null; }, next_operate: function(){ if (this.pay_method == 1) { location.href = '/index.html'; } else { // 发起支付 var url = this.host+'/payment/'+this.order_id+'/' axios.get(url, { withCredentials:true, responseType: 'json' }) .then(response => { // 跳转到支付宝支付 if (response.data.code == 0) { location.href = response.data.alipay_url; } else { alert(response.data.errmsg) } }) .catch(error => { console.log(error); }) } } } });
30.52381
72
0.386895
1e0d32b0dcb5e6be4acb0c8b93ac2ce86075b3c7
65,157
js
JavaScript
doc/OPC DAAE Server Base .NET/script/dotnet2008.js
AkatorMr/opc-daae-server
7d56e4603064b53476d3c0971a4d873066fba65f
[ "Info-ZIP" ]
2
2017-08-11T16:16:36.000Z
2017-10-17T12:43:28.000Z
doc/OPC DAAE Server Base .NET/script/dotnet2008.js
AkatorMr/opc-daae-server
7d56e4603064b53476d3c0971a4d873066fba65f
[ "Info-ZIP" ]
1
2019-05-16T05:53:43.000Z
2019-05-23T01:57:20.000Z
iClient60ForWinRT/Document/API_ALL/script/dotnet2008.js
SuperMap/iClient-for-Win8
214520b0c74cf41fadcac8d02e796b03c5e1c49a
[ "Apache-2.0" ]
1
2021-04-15T01:08:29.000Z
2021-04-15T01:08:29.000Z
/* Wire up the bodyload handler (set here rather than in the body element in order to avoid a HTML Help viewer bug with printing multiple topics */ window.onload = bodyLoad; /* Set body initially hidden unless we are printing */ document.write("<style media='screen'>body {visibility: hidden}</style>"); /* Begin Common utility functions */ /* This is required for user data support in .chms */ var curURL = document.location + "."; var pos = curURL.indexOf("mk:@MSITStore"); var scrollPos = null; if (pos == 0) { curURL = "ms-its:" + curURL.substring(14, curURL.length - 1); document.location.replace(curURL); } /* Returns a document element using the Firefox friendly getElementById */ function documentElement(id) { return document.getElementById(id); } /* Returns the source element of an event */ function sourceElement(e) { if (window.event) { e = window.event; } return e.srcElement ? e.srcElement : e.target; } /* Cancels an event, preventing further bubbling and returning false to cancel default behavior */ function cancelEvent(e) { e.returnValue = false; e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } } /* Returns an elements absolute position, allowing for the non-scrolling header */ function getElementPosition(e) { var offsetLeft = 0; var offsetTop = 0; while (e) { // Allow for the scrolling body region in IE if (msieversion() > 4) { offsetLeft += (e.offsetLeft - e.scrollLeft); offsetTop += (e.offsetTop - e.scrollTop); } else { offsetLeft += e.offsetLeft; offsetTop += e.offsetTop; } e = e.offsetParent; } if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined') { offsetLeft += document.body.leftMargin; offsetTop += document.body.topMargin; } return { left: offsetLeft, top: offsetTop }; } /* Return Microsoft Internet Explorer (major) version number, or 0 for others. */ function msieversion() { var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0) // is Microsoft Internet Explorer; return version number { return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))); } else { return 0; // is other browser } } /* To hide all popup boxes */ function hideBoxes() { var divs = document.getElementsByTagName("DIV"); if (divs) { for (var idiv = 0; idiv < divs.length; idiv++) { var div = divs[idiv]; if (div.className) { if (div.className == "dxpopupbubble" || div.className == "hspopupbubble" || div.className == "hsglossaryreference") { div.style.visibility = "hidden"; } } } } } /* Show a popup box */ function showBox(Name, e, button) { if (window.event) { e = window.event; } hideBoxes(); if (!button) { button = sourceElement(e); } cancelEvent(e); var div = documentElement(Name); if (div && button) { div.style.height = ""; div.style.left = (getElementPosition(button).left) + "px"; div.style.top = (getElementPosition(button).top + button.offsetHeight) + "px"; div.style.visibility = "visible"; } } /* End Common utility functions */ /* Shows a popup parameter box */ function showParamBox(e) { if (window.event) { e = window.event; } var button = sourceElement(e); var documentWidth; var documentHeight; var boxWidth; var pixelLeft; var pixelTop; var boxHeight; var div = documentElement(button.id + "_box"); cancelEvent(e); hideBoxes(); if (div && button) { // Have the browser size the box div.style.height = ""; div.style.width = ""; // Clear any tooltip so it doesn't appear above the popup button.title = ""; pixelTop = getElementPosition(button).top + 14; // Check if the box would go off the bottom of the visible area documentHeight = document.body.clientHeight; boxHeight = div.clientHeight; if (pixelTop + boxHeight > documentHeight) { // If the box won't fit both above and below the link // using the default width then make the box wider if (boxHeight >= pixelTop) { div.style.width = "80%"; } else { pixelTop = pixelTop - 14 - boxHeight; } } div.style.top = pixelTop + "px"; documentWidth = document.body.clientWidth; boxWidth = div.clientWidth; pixelLeft = button.offsetLeft; // Check if the box would go off the edge of the visible area if (pixelLeft + boxWidth > documentWidth) { pixelLeft = documentWidth - boxWidth - 5; } div.style.left = pixelLeft + "px"; // Show the box div.style.visibility = "visible"; } } /* Begin non-scrolling region support */ var isDesignTime = false; function bodyResize() { resizeBan(); } function bodyClick(e) { if (window.event) { e = window.event; } if (sourceElement(e)) { try { if (sourceElement(e).tagName != "INPUT") { if (sourceElement(e).className != "languageFilter" && sourceElement(e).className != "membersFilter" && sourceElement(e).className != "communityFilter") { hideBoxes(); resizeBan(); }; } } catch (e) { } } } function resizeBan() { if (msieversion() > 4) { try { if (document.body.clientWidth == 0) { return; } hideBoxes(); var oBanner = documentElement("pagetop"); var oText = documentElement("pagebody"); var oFooter = documentElement("nonscrollingpagefooter"); var footerHeight = 0; if (oFooter != null) { footerHeight = oFooter.offsetHeight; } if (oText == null) { return; } var oBannerrow1 = documentElement("projectnamebanner"); var oTitleRow = documentElement("pagetitlebanner"); if (oBannerrow1 != null) { var iScrollWidth = document.body.scrollWidth; oBannerrow1.style.marginRight = 0 - iScrollWidth; } if (oTitleRow != null) { oTitleRow.style.padding = "0px 10px 0px 22px; "; } if (oBanner != null) { document.body.scroll = "no"; oText.style.overflow = "auto"; oBanner.style.width = document.body.offsetWidth - 2; oText.style.top = 0; if (document.body.offsetHeight > oBanner.offsetHeight) { oText.style.height = document.body.offsetHeight - (oBanner.offsetHeight + 4) - footerHeight; } else { oText.style.height = 0; } if (scrollPos != null) { oText.scrollTop = scrollPos; scrollPos = null; } } try { documentElement("nstext").setActive(); } catch (e) { } } catch (e) { } } } /* End non-scrolling region support */ /* Begin Document load/unload/print support */ /* Called before custom body load script */ function bodyLoadCommonBefore() { if (scrollPos == null && curURL.indexOf("#") != -1) { var oBanner = documentElement("pagetop"); scrollPos = document.body.scrollTop - oBanner.offsetHeight; } resizeBan(); document.body.onclick = bodyClick; document.body.onresize = bodyResize; window.onbeforeprint = beforePrint; window.onafterprint = afterPrint; window.onunload = windowUnload; } function findFrame(Name) { var frameObject = parent.frames[Name]; try { if ((!frameObject) && parent.parent) { frameObject = parent.parent.frames[Name]; } } catch (e) { } return frameObject; } function tocDocument() { try { return findFrame("webnavbar").document.getElementById("cntNavtoc"); } catch (e) { } } /* Called after custom body load script */ function bodyLoadCommonAfter() { wireUpEventHandlers(); loadSettings(); // make body visible, now that we're ready to render document.body.style.visibility = "visible"; // if this is web output, sync the TOC syncToc(); } /* Synchronize the web Table of Contents */ function syncToc() { if (isPostMessageEnabled()) { /* Upate the parent frames page with the new content page title */ if (top) { top.postMessage("pagetitle|" + document.title, "*"); } /* Synchronize the toc */ var navbar = findFrame("webnavbar"); if (navbar) { navbar.postMessage("synctoc|" + location.href, "*"); } } else { try { var tocDoc = tocDocument(); } catch (e) { } if (tocDoc) { try { tocDoc.contentWindow.pageLoaded(location.href); } catch (e) { setTimeout('syncToc();', 500); } } try { if (top) { if (top.notifyPageTitle) { /* Upate the parent frames page with the new content page title */ top.notifyPageTitle(document.title); } if (top.notifyPageLoaded) { /* Upate the parent frames page with the new content page url */ top.notifyPageLoaded(location.href); } } } catch (e) { } } } /* Saves the scroll position */ function windowUnload() { saveSettings(); } /* Common settings load script */ function loadSettingsCommon() { // load the expand / collapse states loadSections(); dxSetSelectedTabOnTabstrips(); } /* Common settings save script */ function saveSettingsCommon() { // save the expand / collapse states saveSections(); dxSaveSelectedTabs(); } /* Removes the non-scrolling region and ensures everything is visible for print */ function beforePrint() { var allElements; if (window.text) { document.all.text.style.height = "auto"; } allElements = document.getElementsByTagName("*"); for (var i = 0; i < allElements.length; i++) { if (allElements[i].tagName == "BODY") { allElements[i].scroll = "yes"; } if (allElements[i].id == "pagetop") { allElements[i].style.margin = "0px 0px 0px 0px"; allElements[i].style.width = "100%"; } if (allElements[i].id == "pagebody") { allElements[i].style.overflow = "visible"; allElements[i].style.top = "5px"; allElements[i].style.width = "100%"; allElements[i].style.padding = "0px 10px 0px 30px"; } if (allElements[i].id == "pagetoptable2row1" || allElements[i].id == "feedbacklink") { allElements[i].style.display = "none"; } if (allElements[i].className == "LanguageSpecific") { allElements[i].style.display = "block"; } } } /* Refresh the page after a print */ function afterPrint() { document.location.reload(); } /* End Document load/unload/print support */ /* Begin User Data support */ function getDataCache() { if (isDesignTime) { if (getWindowExternal()) { if (window.external.IsInnovasysDesigner) { return window.external; } } } return documentElement("userDataCache"); } function getWindowExternal() { try { return window.external; } catch (e) { } } function load(key) { var dataCacheObject; try { dataCacheObject = getDataCache(); if (dataCacheObject) { dataCacheObject.load("innSettings"); var value = dataCacheObject.getAttribute(key); return value; } else { var value = dxLoadCookieValue(key); if (value && value == "undefined") { return null; } else return value; } } catch (e) { } } function save(key, value) { var dataCacheObject; try { dataCacheObject = getDataCache(); if (dataCacheObject) { dataCacheObject.setAttribute(key, value); dataCacheObject.save("innSettings"); } else dxSaveCookieValue(key, value, 60, "/", "", ""); } catch (e) { } } function removeAttribute(key) { var dataCacheObject; try { dataCacheObject = getDataCache(); dataCacheObject.removeAttribute(key); dataCacheObject.save("innSettings"); } catch (e) { } } /* End User Data support */ /* Begin Expanding sections support */ var collapsedSections = new Array(); /* Wires up the expand / collapse functionality */ function wireUpEventHandlers() { var elements = document.getElementsByTagName("SPAN"); for (var i = 0; i < elements.length; i++) { var span = elements[i]; if (span.className == "expandcollapse") { span.onclick = toggleExpanded; span.onkeypress = toggleExpandedOnKey; } } if (documentElement("toggleExpandedAll")) { documentElement("toggleExpandedAll").onclick = toggleExpandedAll; documentElement("toggleExpandedAll").onkeypress = toggleExpandedAllOnKey; } } function toggleExpanded(img) { // Firefox passes in the event object from the event handler, so // we check for that and set to null if (img) { if (img.tagName == null) { e = img; img = null; } } // Find the expand & collapse image if (!img) { if (window.event) e = window.event; var img = sourceElement(e) if (img) { while (img) { if (img.className == "expandcollapse" && img.tagName == "SPAN") break; else img = img.parentNode; } if (img) img = findExpandCollapseImage(img); } } if (img) { if (isSectionCollapsed(img.id) == true) { img.src = documentElement("collapseImage").src; expandSection(img); removeCollapsedItem(img.id); if (img.id.indexOf("Family", 0) == 0) { protectedMembers = "on"; configureMembersFilterCheckboxes(); changeMembersFilterLabel(); } } else { img.src = documentElement("expandImage").src; collapseSection(img); addCollapsedSection(img.id); } setCollapseAll(); } } function findExpandCollapseImage(sourceElement) { var e; var elements; if (sourceElement.tagName == "IMG" && sourceElement.className == "toggle") { return (sourceElement); } else { if (sourceElement) { elements = sourceElement.getElementsByTagName("IMG"); for (var i = 0; i < elements.length; i++) { e = elements[i]; if (e.className == "toggle") { return (e); } } } } } function toggleExpandedAll() { var elements = document.getElementsByName("toggleSwitch"); var toggleExpandedAllImage = documentElement("toggleExpandedAllImage"); // All currently collapsed if (isSectionCollapsed(toggleExpandedAllImage.id) == true) { toggleExpandedAllImage.src = documentElement("collapseImage").src; removeCollapsedItem(toggleExpandedAllImage.id); for (var i = 0; i < elements.length; i++) { expandSection(elements[i]); elements[i].src = documentElement("collapseImage").src; removeCollapsedItem(elements[i].id); if (elements[i].id.indexOf("Protected", 0) == 0) { protectedMembers = "on"; } } setToggleExpandedAllLabel(false); } // All currently expanded else { toggleExpandedAllImage.src = documentElement("expandImage").src; addCollapsedSection(toggleExpandedAllImage.id); for (var i = 0; i < elements.length; i++) { collapseSection(elements[i]); elements[i].src = documentElement("expandImage").src; addCollapsedSection(elements[i].id); } setToggleExpandedAllLabel(true); } } function toggleExpandedAllOnKey(e) { if (window.event) { e = window.event; } if (e.keyCode == 13) { toggleExpandedAll(); } } function toggleExpandedOnKey(e) { if (window.event) { e = window.event; } if (e.keyCode == 13) { toggleExpanded(findExpandCollapseImage(e.srcElement)); } } function getNextSibling(n) { n = n.nextSibling; while (n) { if (n.nodeType == 1) return n; else n = n.nextSibling; } } function expandSection(imageItem) { if (imageItem.id != "toggleExpandedAllImage") { getNextSibling(imageItem.parentNode.parentNode).style.display = ""; } } function collapseSection(imageItem) { if (imageItem.id != "toggleExpandedAllImage") { getNextSibling(imageItem.parentNode.parentNode).style.display = "none"; } } function setCollapseAll() { var toggleElements = document.getElementsByName("toggleSwitch"); var allCollapsed = true; if (document.getElementById("expandAllLabel")) { for (var i = 0; i < toggleElements.length; i++) { allCollapsed = allCollapsed && isSectionCollapsed(toggleElements[i].id); } if (allCollapsed) { this.src = documentElement("expandAllImage").src; addCollapsedSection("toggleExpandedAllImage"); } else { this.src = documentElement("collapseAllImage").src; removeCollapsedItem("toggleExpandedAllImage"); } setToggleExpandedAllLabel(allCollapsed); } } function setToggleExpandedAllLabel(allCollapsed) { var labelElement; labelElement = document.getElementById("collapseAllLabel"); if (labelElement == null) { return; } labelElement.style.display = "none"; labelElement = document.getElementById("expandAllLabel"); labelElement.style.display = "none"; if (allCollapsed) { labelElement = document.getElementById("expandAllLabel"); labelElement.style.display = "inline"; } else { labelElement = document.getElementById("collapseAllLabel"); labelElement.style.display = "inline"; } } function isSectionCollapsed(imageId) { for (var i = 0; i < collapsedSections.length; ++i) { if (imageId == collapsedSections[i]) { return true; } } return false; } function addCollapsedSection(imageId) { if (isSectionCollapsed(imageId) == false) { collapsedSections[collapsedSections.length] = imageId; } } function removeCollapsedItem(imageId) { for (var i = 0; i < collapsedSections.length; ++i) { if (imageId == collapsedSections[i]) { collapsedSections.splice(i, 1); } } } function saveSections() { var x = 0; cleanUserDataStore(); for (var i = 0; i < collapsedSections.length; ++i) { if (shouldSave(collapsedSections[i]) == true) { save("imageValue" + x, collapsedSections[i]); x++; } } } function loadSections() { var i = 0; var imageId = load("imageValue" + i); while (imageId != null) { var imageItem = document.getElementById(imageId); if (imageItem != null) { if (imageItem.id.indexOf("Family", 0) == 0) { if (protectedMembers == "on") { toggleExpanded(imageItem); } } else { toggleExpanded(imageItem); } } else { addCollapsedSection(imageId); } i++; imageId = load("imageValue" + i); } setCollapseAll(); } function cleanUserDataStore() { var i = 0; var imageId = load("imageValue" + i); while (imageId != null) { removeAttribute("imageValue" + i); i++; imageId = load("imageValue" + i); } } function shouldSave(imageId) { var toggleName; if (imageId == "toggleExpandedAllImage") { return false; } toggleName = "procedureToggle"; if (imageId.indexOf(toggleName, 0) == 0) { return false; } toggleName = "sectionToggle"; if (imageId.indexOf(toggleName, 0) == 0) { return false; } return true; } function openSectionById(id) { var e = documentElement(id); if (e) { if (isSectionCollapsed(e.id) == true) { toggleExpanded(e); } } } /* End Expand / Collapse */ /* Begin save / Restore Scroll Position */ var scrollPos = null; function loadAll() { var historyObject = getHistoryObject(); if (historyObject) { var scrollValue = historyObject.getAttribute("Scroll"); if (scrollValue) { if (scrollValue != 0) { try { scrollPos = scrollValue; documentElement("pagebody").scrollTop = scrollPos; } catch (e) { } } } } } function saveAll() { var historyObject = getHistoryObject(); if (historyObject) { try { historyObject.setAttribute("Scroll", documentElement("pagebody").scrollTop); } catch (e) { } } } function getHistoryObject() { if (isDesignTime) { try { var externalObject = window.external; if (externalObject) { if (externalObject.IsInnovasysDesigner) { return window.external; } else { externalObject = false; } } } catch (e) { } } if (!externalObject) { return documentElement("allHistory"); } } /* End save / Restore Scroll Position */ /* Begin Copy Code */ function copyCode(key) { var trElements = getTABLE(key).getElementsByTagName("tr"); for (var i = 0; i < trElements.length; ++i) { if (getTABLE(key) == getTABLE(trElements[i]) && getTR(key) != trElements[i]) { window.clipboardData.setData("Text", trElements[i].innerText); break; } } } function getTR(obj) { while (obj) { if (obj.tagName == "TR") return obj; else obj = obj.parentNode; } } function getTABLE(obj) { while (obj) { if (obj.tagName == "TABLE") return obj; else obj = obj.parentNode; } } function changeCopyCodeIcon(key, highlight) { var imageElements = document.getElementsByName("ccImage"); for (var i = 0; i < imageElements.length; ++i) { try { if (imageElements[i].parentNode == key) { if (highlight) { imageElements[i].src = documentElement("copyHoverImage").src; } else { imageElements[i].src = documentElement("copyImage").src; } } } catch (e) { } } } function copyCode_CheckKey(key) { var e; if (window.event) { e = window.event; } if (e.keyCode == 13) { copyCode(key); } } /* End Copy Code */ /* Begin XML expand / collapse */ // Detect and switch the display of CDATA and comments from an inline view // to a block view if the comment or CDATA is multi-line. function f(e) { // if this element is an inline comment, and contains more than a single // line, turn it into a block comment. if (e.className == "ci") { if (e.children(0).innerText.indexOf("\n") > 0) { fix(e, "cb"); } } // if this element is an inline cdata, and contains more than a single // line, turn it into a block cdata. if (e.className == "di") { if (e.children(0).innerText.indexOf("\n") > 0) { fix(e, "db"); } } // remove the id since we only used it for cleanup e.id = ""; } // Fix up the element as a "block" display and enable expand/collapse on it function fix(e, cl) { var j; var k; // change the class name and display value e.className = cl; e.style.display = "block"; // mark the comment or cdata display as a expandable container j = e.parentNode.children(0); j.className = "c"; // find the +/- symbol and make it visible - the dummy link enables tabbing k = j.children(0); k.style.visibility = "visible"; k.href = "#"; } // Change the +/- symbol and hide the children. This function works on "element" // displays function ch(e) { var i; // find the +/- symbol var mark = e.children(0).children(0); // if it is already collapsed, expand it by showing the children if (mark.innerText == "+") { mark.innerText = "-"; for (i = 1; i < e.children.length; i++) { e.children(i).style.display = "block"; } } // if it is expanded, collapse it by hiding the children else if (mark.innerText == "-") { mark.innerText = "+"; for (i = 1; i < e.children.length; i++) { e.children(i).style.display = "none"; } } } // Change the +/- symbol and hide the children. This function work on "comment" // and "cdata" displays function ch2(e) { var contents; // find the +/- symbol, and the "PRE" element that contains the content var mark = e.children(0).children(0); contents = e.children(1); // if it is already collapsed, expand it by showing the children if (mark.innerText == "+") { mark.innerText = "-"; // restore the correct "block"/"inline" display type to the PRE if (contents.className == "db" || contents.className == "cb") { contents.style.display = "block"; } else { contents.style.display = "inline"; } } // if it is expanded, collapse it by hiding the children else { if (mark.innerText == "-") { mark.innerText = "+"; contents.style.display = "none"; } } } // Handle a mouse click function cl() { var e = window.event.srcElement; // make sure we are handling clicks upon expandable container elements if (e.className != "c") { e = e.parentNode; if (e.className != "c") { return; } } e = e.parentNode; // call the correct funtion to change the collapse/expand state and display if (e.className == "e") { ch(e); } if (e.className == "k") { ch2(e); } } // Dummy function for expand/collapse link navigation - trap onclick events instead function ex() { } // Erase bogus link info from the status window function h() { window.status = " "; } /* End XML Expand / Collapse */ /* .NET specific script */ // Current language var curLang = ""; // To prevent 'access denied' errors in the authoring environment function dxErrorHandler(msg, url, line) { if (url == "about:blank") { return true; } } if (window.location.href == 'about:blank') { window.onerror = dxErrorHandler; } function bodyLoad() { var i; var b; var l; bodyLoadCommonBefore(); // Check the context window for current language. try { for (i = 1; i < window.external.ContextAttributes.Count; i++) { if (window.external.ContextAttributes(i).Name.toUpperCase() == "DEVLANG") { b = window.external.ContextAttributes(i).Values.toArray(); curLang = b[0].toUpperCase(); } } } catch (e) { } if (curLang != null) { if (curLang.indexOf("VB") != -1) { curLang = "VB"; } if (curLang.indexOf("VC") != -1) { curLang = "CPP"; } if (curLang.indexOf("C++") != -1) { curLang = "CPP"; } if (curLang.indexOf("CSHARP") != -1) { curLang = "CS"; } if (curLang.indexOf("JSCRIPT") != -1) { curLang = "JScript"; } } if (curLang == null) { l = ""; var multipleLang = false; var cLang = ""; try { l = window.external.Help.FilterQuery.toUpperCase(); } catch (e) { } if (l.indexOf("VB") != -1) { cLang = "VB"; } if (l.indexOf("VC") != -1) { if (cLang != null) { multipleLang = true; } cLang = "CPP"; } if (l.indexOf("C#") != -1) { if (cLang != null) { multipleLang = true; } cLang = "CS"; } if (l.indexOf("CSHARP") != -1) { if (cLang != null) { multipleLang = true; } cLang = "CS"; } if (l.indexOf("JSCRIPT") != -1) { if (cLang != null) { multipleLang = true; } cLang = "JScript"; } if (l.indexOf("JSHARP") != -1) { if (cLang != null) { multipleLang = true; } cLang = "JSHARP"; } if (multipleLang == false) { curLang = cLang; } } bodyLoadCommonAfter(); if (parent) { /* Running in a frame - listen for commands */ if (isPostMessageEnabled()) { addMessageListener(receiveMessage); parent.postMessage("loaded", "*"); } else { parent.loaded = true; } } } function loadSettings() { // load the languages loadLanguages(); configureLanguageCheckboxes(); displayLanguages(); // load the member options loadMembersFilter(); configureMembersFilterCheckboxes(); changeMembersFilterLabel(); loadSettingsCommon(); } function saveSettings() { saveLanguages(); saveMembersFilter(); saveSettingsCommon(); } /* Begin Member Filtering */ var inheritedMembers; var protectedMembers; function configureMembersFilterCheckboxes() { var checkbox; checkbox = document.getElementById("inheritedCheckbox"); if (checkbox != null) { if (inheritedMembers == "on") { checkbox.checked = true; } else { checkbox.checked = false; } } checkbox = document.getElementById("protectedCheckbox"); if (checkbox != null) { if (protectedMembers == "on") { checkbox.checked = true; } else { checkbox.checked = false; } } } function setMembersFilter(key) { if (key.id == "inheritedCheckbox") { if (key.checked == true) { inheritedMembers = "on"; } else { inheritedMembers = "off"; } updateInheritedMembers(); } if (key.id == "protectedCheckbox") { if (key.checked == true) { protectedMembers = "on"; } else { protectedMembers = "off"; } updateProtectedMembers(); } changeMembersFilterLabel(); } function updateInheritedMembers() { var tablerows = document.getElementsByTagName("tr"); var i; if (inheritedMembers == "off") { for (i = 0; i < tablerows.length; ++i) { if (tablerows[i].id == "inheritedMember") tablerows[i].style.display = "none"; } } else { for (i = 0; i < tablerows.length; ++i) { if (tablerows[i].id == "inheritedMember") tablerows[i].style.display = ""; } } } function updateProtectedMembers() { var toggleImages = document.getElementsByName("toggleSwitch"); var i; if (protectedMembers == "off") { for (i = 0; i < toggleImages.length; ++i) { if (toggleImages[i].id.indexOf("protected", 0) == 0) { if (isSectionCollapsed(toggleImages[i].id) == false) { toggleExpanded(toggleImages[i]); } } } } else { for (i = 0; i < toggleImages.length; ++i) { if (toggleImages[i].id.indexOf("protected", 0) == 0) { if (isSectionCollapsed(toggleImages[i].id) == true) { toggleExpanded(toggleImages[i]); } } } } } function changeMembersFilterLabel() { var filtered = false; if ((inheritedMembers == "off") || (protectedMembers == "off")) { filtered = true; } var labelElement = document.getElementById("showAllMembersLabel"); if (labelElement == null) { return; } labelElement.style.display = "none"; labelElement = document.getElementById("filteredMembersLabel"); labelElement.style.display = "none"; if (filtered) { labelElement = document.getElementById("filteredMembersLabel"); labelElement.style.display = "inline"; } else { labelElement = document.getElementById("showAllMembersLabel"); labelElement.style.display = "inline"; } } function loadMembersFilter() { var value = load("inheritedMembers"); if (value == null) { inheritedMembers = "on"; } else { inheritedMembers = value; } value = load("protectedMembers"); if (value == null) { protectedMembers = "on"; } else { protectedMembers = value; } if (inheritedMembers == "off") { updateInheritedMembers(); } if (protectedMembers == "off") { updateProtectedMembers(); } } function saveMembersFilter() { save("inheritedMembers", inheritedMembers); save("protectedMembers", protectedMembers); } /* End Member Filtering */ /* Language Filtering */ var languageNames; var languageStates; function configureLanguageCheckboxes() { var checkbox; for (var i = 0; i < languageNames.length; i++) { checkbox = documentElement(languageNames[i] + "Checkbox"); if (languageStates[i] == "on") { checkbox.checked = true; } else { checkbox.checked = false; } } } function setLanguage(key) { var languageName = key.id.substring(0, key.id.indexOf("Checkbox")); if (getLanguageState(languageName) == "on") { // Always have at least one selected if (getLanguageTickedCount() == 1) { key.checked = true; return; } setLanguageState(languageName, "off"); key.checked = false; } else { setLanguageState(languageName, "on"); key.checked = true; } // Update the content to reflect the new language filter displayLanguages(); // Reset the selected tab dxRefreshSelectedTabOnTabstrips(); } function displayLanguages() { var pres = document.getElementsByTagName("DIV"); var pre; var found; var languageName; if (pres) { for (var iPre = 0; iPre < pres.length; iPre++) { pre = pres[iPre]; if (pre.id && pre.className) { if (pre.className == "LanguageSpecific" || (pre.className.indexOf("DxTab ") == 0 && pre.className.length == 5) || pre.className.lastIndexOf("DxTab") == pre.className.length - 5) { found = true; if (pre.id.substring(pre.id.length - 1, pre.id.length) != "_") { for (var i = 0; i < languageNames.length; i++) { if (languageStates[i] == "off") { languageName = languageNames[i].toUpperCase(); // For each language specific element except the Syntax, treat CPP2005 as CPP if (languageName == "CPP2005" && pre.id.toUpperCase().indexOf("SYNTAX") == -1) { languageName = "CPP"; } if (doesIdContainLanguageName(pre.id, languageName)) { found = false; break; } else if (languageName == "VB" && doesIdContainLanguageName(pre.id, "VBALL")) { found = false; break; } else if (languageName == "CS" && doesIdContainLanguageName(pre.id, "C#")) { found = false; break; } } } } if (found) { pre.style.display = "block"; } else { pre.style.display = "none"; } } } } } changeLanguageFilterLabel(); } function doesIdContainLanguageName(id, languageName) { return ((id.toUpperCase().indexOf(languageName) != -1 && id.toUpperCase().indexOf(languageName) == (id.length - languageName.length)) || (id.toUpperCase().indexOf(languageName + ".NET") != -1 && id.toUpperCase().indexOf(languageName + ".NET") == (id.length - languageName.length - 4))) } function getLanguageState(LanguageName) { for (var i = 0; i < languageNames.length; i++) { if (languageNames[i] == LanguageName) { return (languageStates[i]); } } } function getLanguageState(LanguageName) { for (var i = 0; i < languageNames.length; i++) { if (languageNames[i] == LanguageName) { return (languageStates[i]); } } } function setLanguageState(LanguageName, Value) { for (var i = 0; i < languageNames.length; i++) { if (languageNames[i] == LanguageName) { languageStates[i] = Value; } } } function getLanguageTickedCount() { var tickedCount = 0; var labelElement; for (var i = 0; i < languageNames.length; i++) { if (languageStates[i] == "on") { tickedCount++; } } return (tickedCount); } function changeLanguageFilterLabel() { var tickedCount = 0; var labelElement; var languageName; if (!document.getElementById("showAllLabel")) { return; } for (var i = 0; i < languageNames.length; i++) { if (languageStates[i] == "on") { tickedCount++; } labelElement = documentElement(languageNames[i] + "label"); if (labelElement != null) { labelElement.style.display = "none"; } } document.getElementById("showAllLabel").style.display = "none"; document.getElementById("multipleLabel").style.display = "none"; if (tickedCount == languageNames.length) { document.getElementById("showAllLabel").style.display = "inline"; } else if ((tickedCount > 1) && (tickedCount < languageNames.length)) { if ((tickedCount == 2) && (getLanguageState("VB") == "on") && (getLanguageState("vbUsage") == "on")) { document.getElementById("VBLabel").style.display = "inline"; } else { document.getElementById("multipleLabel").style.display = "inline"; } } else if (tickedCount == 1) { for (var i = 0; i < languageNames.length; i++) { if (languageStates[i] == "on") { if (languageNames[i] == "vbUsage") { languageName = "VB"; } else { languageName = languageNames[i]; } document.getElementById(languageName + "Label").style.display = "inline"; } } } } function loadLanguages() { var languageName; var language; var allNull; // Build an array of this pages language names and state languageNames = new Array(); languageStates = new Array(); var elements = document.getElementsByName("languageFilter"); allNull = true; for (var i = 0; i < elements.length; i++) { var input = elements[i]; languageNames[i] = input.id.substring(0, input.id.indexOf("Checkbox")); var value = load("lang_" + languageNames[i]); if (value == null) { languageStates[i] = "on"; } else { allNull = false; languageStates[i] = value; } } // If no language preference has been established and we have an indicator of the current // language, set the languages filtered to only the current language if (allNull && curLang.length > 0) { for (var i = 0; i < elements.length; i++) { if (languageNames[i].toUpperCase() == curLang.toUpperCase()) { languageStates[i] = "on"; } else { languageStates[i] = "off"; } } } dxSetSelectedTabOnTabstrips(); } function saveLanguages() { if (languageNames) { for (var i = 0; i < languageNames.length; i++) { var value = languageStates[i]; save("lang_" + languageNames[i], value); } } } /* End Language Filtering */ /* .NET Framework Help Topic Resolution */ // This function is Copyright 2006 Innovasys Limited. No reproduction or usage // allowed other than in documentation generated by Innovasys Document! X v5 function resolveHelp2Keyword(Keyword, OnlineKeyword) { var URL = ""; try { // Try the current namespace URL = findHelp2Keyword(getCurrentHelp2Namespace(), Keyword); if (URL == "") { // Try the likely namespaces first, most recent first URL = findHelp2Keyword("MS.VSCC.v80", Keyword); if (URL == "") { URL = findHelp2Keyword("MS.VSCC.2003", Keyword); if (URL == "") { URL = findHelp2Keyword("MS.VSCC", Keyword); } } } // URL found in one of the known VSCC namespaces if (URL != "") { return URL; } // For future proofing, try other VSCC namespaces else { var RegistryWalker = new ActiveXObject("HxDs.HxRegistryWalker"); var Namespaces = RegistryWalker.RegisteredNamespaceList("MS.VSCC"); var Namespace, NamespaceName, Session, Topics, Topic; if (Namespaces.Count > 0) { for (n = 1; n <= Namespaces.Count; n++) { Namespace = Namespaces.Item(n); NamespaceName = Namespace.Name; if (NamespaceName.substring(0, 7) == "MS.VSCC") { switch (NamespaceName) { case "MS.VSCC.v80": break; case "MS.VSCC.2003": break; case "MS.VSCC": break; default: URL = findHelp2Keyword(NamespaceName); if (URL != "") { return Topics(1).URL; } } } } } } } catch (e) { } // No match found in any applicable namespace // Msdn doesn't support links to individual overloads, only to the master page // so we trim off the brackets when directing to Msdn var BracketPosition = OnlineKeyword.indexOf("("); if (BracketPosition != -1) { OnlineKeyword = OnlineKeyword.substring(0, BracketPosition); } return "http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(" + OnlineKeyword + ")&rd=true" } function findHelp2Keyword(NamespaceName, Keyword) { var Session, Topics; if (NamespaceName.length > 0) { try { Session = new ActiveXObject("HxDs.HxSession"); Session.Initialize("ms-help://" + NamespaceName, 0); Topics = Session.Query(Keyword, "!DefaultAssociativeIndex", 0, ""); if (Topics.Count > 0) { return Topics(1).URL; } } catch (e) { } } return ""; } function navigateToHelp2Keyword(Keyword, OnlineKeyword, ReplacePage) { window.status = "Resolving link. Please wait a moment..."; var URL = resolveHelp2Keyword(Keyword, OnlineKeyword); window.status = ""; if (ReplacePage == true) { location.replace(URL); } else { location.href = URL; } } function getCurrentHelp2Namespace() { var namespace = ""; var location = window.location; if (location.protocol == "ms-help:") { namespace = location.hostname; if (namespace.substring(0, 2) == "//") namespace = namespace.substring(2); } return namespace; } /* End .NET Framework Help Topic Resolution */ /* GetSetting SaveSetting Alias */ function dxGetSetting(key) { return load(key); } function dxSaveSetting(key, value) { save(key, value) } /* End GetSetting SaveSetting Alias */ /* Tab Strip */ function dxSetSelectedTabOnTabstrips() { // Set the default tab on any tab strips var tabDivs = document.getElementsByTagName("DIV") for (var i = 0; i < tabDivs.length; i++) { var div = tabDivs[i]; if (div.className == "DxTabStripContainer") { // Load the selected tab from the session cookie var defaultTabName = dxGetSetting(div.id + "_SelectedTab"); if (defaultTabName) dxSetActiveTabById(div.id, defaultTabName); // Check that a tab is selected var selectedTabName = dxGetSelectedTabName(div); if (!selectedTabName) { var tabs = dxGetTabsFromTabContainer(div, true); if (tabs) dxSetActiveTab(div, tabs[0]); } } } } function dxRefreshSelectedTabOnTabstrips() { // Refresh the selected tab on any tab strips var tabDivs = document.getElementsByTagName("DIV") for (var i = 0; i < tabDivs.length; i++) { var div = tabDivs[i]; if (div.className == "DxTabStripContainer") { // Get the currently selected tab var selectedTabName = dxGetSelectedTabName(div); dxSetActiveTabById(div.id, selectedTabName); // Now check we have a selection var selectedTabName = dxGetSelectedTabName(div); if (!selectedTabName) { var tabs = dxGetTabsFromTabContainer(div, true); if (tabs) dxSetActiveTab(div, tabs[0]); } } } } function dxSaveSelectedTabs() { // Save the current tab on any tab strips var tabDivs = document.getElementsByTagName("DIV"); for (var i = 0; i < tabDivs.length; i++) { var div = tabDivs[i]; if (div.className == "DxTabStripContainer") { var selectedTabName = dxGetSelectedTabName(div); dxSaveSetting(div.id + "_SelectedTab", selectedTabName); } } } function dxSetActiveTabById(containerName, tabName) { if (containerName && tabName) { var container = document.getElementById(containerName); var childNodes = container.childNodes; for (var i = 0; i < childNodes.length; i++) { var childNode = childNodes[i]; if (childNode.id == tabName) { return dxSetActiveTab(container, childNode); } } } dxSaveSelectedTabs(); } function dxGetNextDiv(div) { do { if (div.nextSibling) { div = div.nextSibling; if (div.tagName && div.tagName == "DIV" && div.style.display != "none") return div; } } while (div.nextSibling); } function dxGetPreviousDiv(div) { do { if (div.previousSibling) { div = div.previousSibling; if (div.tagName && div.tagName == "DIV" && div.style.display != "none") return div; } } while (div.previousSibling); } function dxSetActiveTab(container, tab) { if (container && tab) { var childNodes = container.childNodes; for (var i = 0; i < childNodes.length; i++) { var childNode = childNodes[i]; if (childNode.tagName && childNode.tagName == "DIV" && (childNode.className == "DxTab" || childNode.className.indexOf(" DxTab") == childNode.className.length - 6)) { var isActiveTab = (childNode == tab); if (isActiveTab) childNode.className = "DxTabActive DxTab"; else childNode.className = "DxTab"; // If this tab is visible, update the adjacent left / right end if (childNode.style.display != 'none') { if (dxGetNextDiv(childNode) && dxGetNextDiv(childNode).className && dxGetNextDiv(childNode).className.indexOf("DxTabRightEnd") != -1) { /* Last tab, update right end */ var rightEnd = dxGetNextDiv(childNode); if (isActiveTab) rightEnd.className = "DxTabRightEndActive DxTabRightEnd"; else rightEnd.className = "DxTabRightEnd"; } if (dxGetPreviousDiv(childNode) && dxGetPreviousDiv(childNode).className && dxGetPreviousDiv(childNode).className.indexOf("DxTabLeftEnd") != -1) { /* First tab, update right end */ var leftEnd = dxGetPreviousDiv(childNode); if (isActiveTab) leftEnd.className = "DxTabLeftEndActive DxTabLeftEnd"; else leftEnd.className = "DxTabLeftEnd"; } } /* Find related content div and show/hide */ if (childNode.id == "SyntaxTab_VBAll") { dxShowOrHideTabContentSection("SyntaxTab_VB_Content", isActiveTab); dxShowOrHideTabContentSection("SyntaxTab_VBUsage_Content", isActiveTab); } else { dxShowOrHideTabContentSection(childNode.id + "_Content", isActiveTab); } } } } } function dxShowOrHideTabContentSection(id, isVisible) { var contentDiv = document.getElementById(id); if (contentDiv) { if (isVisible) contentDiv.style.display = "block"; else contentDiv.style.display = "none"; } } function dxGetSelectedTabName(container) { var tabs = dxGetTabsFromTabContainer(container, true); if (tabs) { for (var tabIndex = 0; tabIndex < tabs.length; tabIndex++) { var tab = tabs[tabIndex]; if (tab.className.indexOf("DxTabActive") != -1) return tab.id; } } } function dxGetTabsFromTabContainer(container, visibleOnly) { var tabs = []; var childNodes = container.childNodes; for (var i = 0; i < childNodes.length; i++) { var childNode = childNodes[i]; if (childNode.tagName && childNode.tagName == "DIV" && (childNode.className == "DxTab" || (childNode.className.indexOf(" DxTab") == childNode.className.length - 6))) { if (!visibleOnly || childNode.style.display != "none") tabs[tabs.length] = childNode; } } return tabs; } /* End Tab Strip */ /* Cookie functionality */ function dxLoadCookieValue(sName) { var CookieValues = document.cookie.split("; "); for (var i = 0; i < CookieValues.length; i++) { var aCrumb = CookieValues[i].split("="); if (sName == aCrumb[0]) return unescape(aCrumb[1]) } return null; } function dxSaveCookieValue(name, value, expiry, path, domain, secure) { var Now = new Date(); Now.setTime(Now.getTime()); if (expiry) { expiry = expiry * 1000 * 60 * 60 * 24; } var ExpiresOn = new Date(Now.getTime() + (expiry)); document.cookie = name + "=" + escape(value) + ((expiry) ? ";expires=" + ExpiresOn.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : ""); } /* End Cookie functionality */ /* Common Messaging Support */ function isPostMessageEnabled() { return (window['postMessage'] != null); } function addMessageListener(receiver) { if (isPostMessageEnabled()) { if (window['addEventListener']) { window.addEventListener("message", receiver, false); } else { window.attachEvent("onmessage", receiver); } } } function Message(messageType, messageData) { this.messageType = messageType; this.messageData = messageData; } function getMessage(data) { var separator = data.indexOf("|"); var messageType; var messageData; if (separator != -1) { messageType = data.substring(0, separator); messageData = data.substring(separator + 1); } else { messageType = data; messageData = ""; } return new Message(messageType, messageData); } /* Message Handler */ function receiveMessage(event) { var message = getMessage(event.data); switch (message.messageType) { case "print": printDocument(); break; case "addtofavorites": addToFavorites(); break; case "quicksearch": highlightText(document, message.messageData, "black", "yellow", true); break; case "resetquicksearch": removeAllHighlights(document); break; case "refresh": document.location.reload(); break; } } /* Print */ function printDocument() { window.print(); } /* Add to favorites */ function addToFavorites() { var nav = findFrame("webnavbar"); nav.postMessage("addtofavorites|" + location + "|" + document.title, "*"); } /* Highlight text in a document */ function highlightText(targetDocument, text, color, backColor, clearBefore) { if (clearBefore) { firstMatch = null; removeAllHighlights(targetDocument); } if (text != "") { HighlightTextInElement(targetDocument, targetDocument.body, text, color, backColor, firstMatch); // Scroll to the first hit if it's not already visible if (firstMatch && clearBefore) { if (getElementPosition(firstMatch).top > targetDocument.documentElement.scrollTop + targetDocument.documentElement.clientHeight || getElementPosition(firstMatch).top < targetDocument.documentElement.scrollTop) { targetDocument.documentElement.scrollTop = firstMatch.offsetTop; } } } } /* Highlight text in a specific element */ function HighlightTextInElement(targetDocument, element, text, color, backColor) { var lowerCaseText = text.toLowerCase(); var node = null; var nodeText = null; var lowerCaseNodeText = null; var highlightSpan = null; var remainingText = null; var textNode = null; var selection = null; // Traverse the document backwards otherwise the DOM returns stale objects as // we make modifications for (var x = element.childNodes.length - 1; x >= 0; x--) { node = element.childNodes[x]; // Text Node if (node.nodeType == 3) { nodeText = node.nodeValue; lowerCaseNodeText = nodeText.toLowerCase(); for (pos = lowerCaseNodeText.indexOf(lowerCaseText); pos >= 0; pos = lowerCaseNodeText.indexOf(lowerCaseText)) { // Create a span to mark up the highlight highlightSpan = targetDocument.createElement("SPAN"); highlightSpan.style.backgroundColor = backColor; highlightSpan.style.color = color; highlightSpan.className = "InnovasysSearchHighlight"; highlightSpan.appendChild(targetDocument.createTextNode(nodeText.substring(pos, pos + text.length))); // Insert the span containing the term remainingText = targetDocument.createTextNode(nodeText.substring(pos + text.length, nodeText.length)); node.nodeValue = nodeText.substring(0, pos); highlightSpan = node.parentNode.insertBefore(highlightSpan, node.nextSibling); remainingText = node.parentNode.insertBefore(remainingText, highlightSpan.nextSibling); // Store the first (last)hit so we can scroll to it firstMatch = highlightSpan; // Skip past the new nodes we've added node = node.nextSibling.nextSibling; nodeText = node.nodeValue; lowerCaseNodeText = nodeText.toLowerCase(); } } // Element node else if (node.nodeType == 1) { // To ensure we don't modify script or go over // highlights we have already applied if (node.nodeName != "SCRIPT" && !(node.nodeName == "SPAN" && node.className == "InnovasysSearchHighlight")) { HighlightTextInElement(targetDocument, node, text, color, backColor); } } } } /* Returns all highlight SPAN elements for a document */ function getHighlightSpans(targetDocument) { var spans = targetDocument.getElementsByTagName("SPAN"); var highlightSpans = new Array(); var span = null; var highlightSpanCount = 0; for (x = spans.length - 1; x >= 0; x--) { span = spans[x]; if (span.className == "InnovasysSearchHighlight") { highlightSpans[highlightSpanCount] = span; highlightSpanCount++; } } return highlightSpans; } /* Merges any adjacent text node.s The IE DOM in particular has a habit of splitting up text nodes, and also after highlighting and removing split adjacent nodes can be left */ function cleanUpTextNodes(parentNode) { var node = null; var lastNode = null; var mergeCount = null; do { mergeCount = 0; for (var x = 1; x < parentNode.childNodes.length; x++) { node = parentNode.childNodes[x]; lastNode = node.previousSibling; if (node.nodeType == 3 && lastNode.nodeType == 3) { node.nodeValue = lastNode.nodeValue + node.nodeValue; parentNode.removeChild(lastNode); mergeCount++; } } } while (mergeCount > 0) for (var x = 0; x < parentNode.childNodes.length; x++) { cleanUpTextNodes(parentNode.childNodes[x]); } } /* Removes any previously added highlight SPANs from the document */ function removeAllHighlights(targetDocument) { var spans = getHighlightSpans(targetDocument); var text = null; for (x = spans.length - 1; x >= 0; x--) { span = spans[x]; text = targetDocument.createTextNode(span.innerHTML); span.parentNode.replaceChild(text, span); } // This process may have resulted in multiple contiguous text nodes // which could cause problems with subsequent search highlight operations // So we join any continguous text nodes here cleanUpTextNodes(targetDocument.body); } /* Glossary boxes */ function hsShowGlossaryItemBox(term, definition, e) { if (window.event) e = window.event; hideBoxes(e); var button = sourceElement(e); var documentWidth; var documentHeight; var boxWidth; var pixelLeft; var pixelTop; var boxHeigt; var boxWidth; cancelEvent(e); var div = documentElement("hsglossaryitembox") if (div && button) { // Have the browser size the box div.style.height = ""; div.style.width = ""; // Clear the tooltip so it doesn't appear above the popup button.title = ""; div.innerHTML = "<p><strong>" + term + "</strong><br>" + definition + "</p>"; pixelTop = getElementPosition(button).top + 14; // Check if the box would go off the bottom of the visible area documentHeight = document.body.clientHeight; boxHeight = div.clientHeight; if (pixelTop + boxHeight > documentHeight) { // If the box won't fit both above and below the link // using the default width then make the box wider if (boxHeight >= pixelTop) div.style.width = "80%"; else pixelTop = pixelTop - 14 - boxHeight; } div.style.top = pixelTop + "px"; documentWidth = document.body.clientWidth; boxWidth = div.clientWidth; pixelLeft = getElementPosition(button).left; // Check if the box would go off the edge of the visible area if (pixelLeft + boxWidth > documentWidth) { pixelLeft = documentWidth - boxWidth - 5; } div.style.left = pixelLeft + "px"; // Show the box div.style.visibility = "visible"; } } /* End Glossary boxes */
24.303245
221
0.527418
1e0e0eb41bdf1899b205b8935195f8db1783ed41
203
js
JavaScript
chapter-07/7.8/src/router/middleware/authentication.js
msoftware/Vue.js-3.0-Cookbook
adaceb9f418f6a3af60c9dc89cd42a1d1d5d0e5a
[ "MIT" ]
1
2021-05-03T10:07:35.000Z
2021-05-03T10:07:35.000Z
chapter-07/7.8/src/router/middleware/authentication.js
rolltidehero/Vue.js-3.0-Cookbook
999692b78ee16dc78b690a08017c1b008f4c4563
[ "MIT" ]
null
null
null
chapter-07/7.8/src/router/middleware/authentication.js
rolltidehero/Vue.js-3.0-Cookbook
999692b78ee16dc78b690a08017c1b008f4c4563
[ "MIT" ]
1
2021-02-24T20:32:52.000Z
2021-02-24T20:32:52.000Z
export default (to, from, next) => { if (to.meta.authenticated && sessionStorage.getItem('auth')) { return next(); } if (!to.meta.authenticated) { return next(); } next('/login'); };
16.916667
64
0.586207
1e0e8ec6034ca64abb34a5e15de315c332c2d670
216
js
JavaScript
browser/client1/src/util/hex2dec.js
chkui/fingerprintsAuth
d4e9260d7e74d0b17aee4a4b4ad1b547c709f74f
[ "Apache-2.0" ]
null
null
null
browser/client1/src/util/hex2dec.js
chkui/fingerprintsAuth
d4e9260d7e74d0b17aee4a4b4ad1b547c709f74f
[ "Apache-2.0" ]
null
null
null
browser/client1/src/util/hex2dec.js
chkui/fingerprintsAuth
d4e9260d7e74d0b17aee4a4b4ad1b547c709f74f
[ "Apache-2.0" ]
null
null
null
export const hex2dec = function (hexStr) { let dec = ''; for (let pos = 0; pos < hexStr.length; pos = pos + 2) { const s = hexStr.substr(pos, 2); dec += parseInt(s, 16) } return dec };
27
59
0.532407
1e0e8fdda14e3af101d0fd286c77bf8c04f5dddf
2,421
js
JavaScript
src/containers/app/header.js
guillaumeAder1/portfolio
ae0bfe25bc6bfffccc27a296ee0711f8940ce459
[ "MIT" ]
null
null
null
src/containers/app/header.js
guillaumeAder1/portfolio
ae0bfe25bc6bfffccc27a296ee0711f8940ce459
[ "MIT" ]
null
null
null
src/containers/app/header.js
guillaumeAder1/portfolio
ae0bfe25bc6bfffccc27a296ee0711f8940ce459
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import style from './constant'; import PropTypes from 'prop-types'; class Header extends Component { constructor(props) { super(props); this.state = { open: false }; this.body = document.querySelector('body'); } addclassName = toggle => { if (toggle) { this.body.classList.add('is-menu-visible'); } else { this.body.classList.remove('is-menu-visible'); } }; render() { return ( <React.Fragment> <header id="header" style={{ backgroundColor: style.header }}> <a href="" className="logo"> <strong>#portfolio</strong> <span>Guillaume Ader</span> </a> <nav> <a href="#menu" onClick={e => this.addclassName(true)}> Menu </a> </nav> </header> <nav id="menu" style={{ backgroundColor: style.mainBg }}> <div className="inner"> <ul className="links"> <li> <Link to="/education" onClick={e => this.addclassName(false)}> Home </Link> </li> <li> <Link to="/works" onClick={e => this.addclassName(false)}> Works </Link> </li> <li> <Link to="/gallery" onClick={e => this.addclassName(false)}> Gallery </Link> </li> <li> <Link to="/education" onClick={e => this.addclassName(false)}> Home </Link> </li> <li> <Link to="/education" onClick={e => this.addclassName(false)}> Home </Link> </li> </ul> <ul className="actions vertical"> <li> <a href="#" className="button special fit"> Get Started </a> </li> <li> <a href="#" className="button fit"> Log In </a> </li> </ul> </div> <a className="close" onClick={e => this.addclassName(false)}> Close </a> </nav> </React.Fragment> ); } } export default Header;
27.202247
78
0.430814
1e0eaf9f4eccb46058312b7c446716a7a2e7d026
1,156
js
JavaScript
common-ui/js/components/house-plans/house-plan/house-plan.controller.js
hunterBhough/epahomeratingapp-ui
aa997c935de55c504fa6a8c330989ea4b0745de4
[ "Apache-2.0" ]
2
2019-03-21T18:00:52.000Z
2019-06-24T17:37:58.000Z
common-ui/js/components/house-plans/house-plan/house-plan.controller.js
hunterBhough/epahomeratingapp-ui
aa997c935de55c504fa6a8c330989ea4b0745de4
[ "Apache-2.0" ]
1
2022-03-01T23:50:47.000Z
2022-03-01T23:50:47.000Z
common-ui/js/components/house-plans/house-plan/house-plan.controller.js
hunterBhough/epahomeratingapp-ui
aa997c935de55c504fa6a8c330989ea4b0745de4
[ "Apache-2.0" ]
1
2019-06-24T17:38:20.000Z
2019-06-24T17:38:20.000Z
class HousePlanController { constructor (HousePlansService, S3_CONFIG) { 'ngInject'; this.HousePlansService = HousePlansService; this.s3Bucket = `${S3_CONFIG.S3_BUCKET_NAME_PREFIX}-rating-company`; } $onChanges (changes) { if (changes.housePlan && !changes.housePlan.isFirstChange()) { this.housePlan = changes.housePlan.currentValue; } this.showDownloadModal = false; } get housePlanTitle () { let title = ''; if (this.housePlan && this.housePlan.SubplanName !== undefined) { let titleDivider = (this.housePlan.SubplanName.length) ? ' - ' : ''; title = this.housePlan.Name + titleDivider + this.housePlan.SubplanName; } return title; } onDownloadRequest () { this.HousePlansService .downloadRemXml(this.housePlan) .then((response) => { this.downloadUrl = response; this.showDownloadModal = true; }); } hideModalDownload () { this.showDownloadModal = false; } } export default HousePlanController;
26.883721
85
0.58737
1e0ed8372aa815940430b075260411f63f62349a
700
js
JavaScript
build/database/repository/SupportRepo.js
ZizouAR/WeReakt---Backend
4b9f40bb1429e32f82de645b1786e5bc6d9acead
[ "Apache-2.0" ]
null
null
null
build/database/repository/SupportRepo.js
ZizouAR/WeReakt---Backend
4b9f40bb1429e32f82de645b1786e5bc6d9acead
[ "Apache-2.0" ]
null
null
null
build/database/repository/SupportRepo.js
ZizouAR/WeReakt---Backend
4b9f40bb1429e32f82de645b1786e5bc6d9acead
[ "Apache-2.0" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Support_1 = require("../model/Support"); class SupportRepo { static async create(req) { req.createdAt = new Date(); const request = await Support_1.SupportModel.create(req); return request.toObject(); } static update(support) { return Support_1.SupportModel.findByIdAndUpdate(support._id, { support }) .lean() .exec(); } static find(user) { return Support_1.SupportModel.find(user) .sort('-createdAt') .lean() .exec(); } } exports.default = SupportRepo; //# sourceMappingURL=SupportRepo.js.map
30.434783
81
0.608571
1e0f82282c632be103d33e711f790dbb6451df04
43
js
JavaScript
server.js
braintree/eslint-conf
f8538a24cfa37c8df04e0700b2e46604e1179935
[ "MIT" ]
226
2018-10-22T17:53:08.000Z
2022-02-24T05:39:06.000Z
server.js
braintree/eslint-conf
f8538a24cfa37c8df04e0700b2e46604e1179935
[ "MIT" ]
10
2016-07-07T16:03:40.000Z
2021-09-24T15:05:20.000Z
server.js
braintree/eslint-conf
f8538a24cfa37c8df04e0700b2e46604e1179935
[ "MIT" ]
7
2016-05-05T13:44:12.000Z
2021-07-20T12:02:50.000Z
module.exports = require("./dist/server");
21.5
42
0.697674
1e103a1f24843c7441cdf96b7f613b8df74d171e
1,116
js
JavaScript
src/__tests__/calc.test.js
chengjianhua/styled-fns
62b17e302293a9763038135c100838bf23f116cd
[ "MIT" ]
3
2018-04-16T14:28:39.000Z
2020-07-06T21:53:07.000Z
src/__tests__/calc.test.js
chengjianhua/styled-fns
62b17e302293a9763038135c100838bf23f116cd
[ "MIT" ]
null
null
null
src/__tests__/calc.test.js
chengjianhua/styled-fns
62b17e302293a9763038135c100838bf23f116cd
[ "MIT" ]
null
null
null
import calc from '../calc' describe('calc', () => { it('should return right result for template with variables', () => { expect(calc`(${'100px'} * 100) + ${'1px'}`).toBe('10001px') expect(calc`(${'100px'} * 100) / 1`).toBe('10000px') }) it('should throw exception if occurs more than two sort of units in expression', () => { expect(() => { // eslint-disable-next-line calc`(${'100px'} * 100) + ${'1rem'}` }).toThrowErrorMatchingSnapshot() }) it('should return right result for variables without unit, and return value is type of `Number`', () => { expect(calc`${'100'} * 100`).toBe(10000) }) it('should throw exception if input is full string without variables', () => { expect(() => { // eslint-disable-next-line calc`(1.5px * 100) + 100px` }).toThrowErrorMatchingSnapshot() }) it('should throw custom error message while input contains variables but variable has unit without being wrapped', () => { expect(() => { // eslint-disable-next-line calc`(${'1.5px'} * 100) + 100px` }).toThrowErrorMatchingSnapshot() }) })
32.823529
124
0.601254
1e10e760d53fda920dfdd5c62543ee87c6fbddfa
1,793
js
JavaScript
src/components/BehaviourViz.js
980302306/Junction2020
2e91650b893f529720f1f18a9d7551dcd70e8f90
[ "MIT" ]
null
null
null
src/components/BehaviourViz.js
980302306/Junction2020
2e91650b893f529720f1f18a9d7551dcd70e8f90
[ "MIT" ]
null
null
null
src/components/BehaviourViz.js
980302306/Junction2020
2e91650b893f529720f1f18a9d7551dcd70e8f90
[ "MIT" ]
null
null
null
import React, { useLayoutEffect } from 'react'; // import logo from './logo.svg'; // import './App.css'; import * as am4core from "@amcharts/amcharts4/core"; import * as am4charts from "@amcharts/amcharts4/charts"; import am4themes_animated from "@amcharts/amcharts4/themes/animated"; import am4themes_dataviz from "@amcharts/amcharts4/themes/dataviz" import am4themes_frozen from"@amcharts/amcharts4/themes/frozen" am4core.useTheme(am4themes_frozen); am4core.useTheme(am4themes_animated); am4core.useTheme(am4themes_dataviz); function BehaviourViz(props) { // const chart = useRef(null); useLayoutEffect(() => { let chart = am4core.create("chartdiv6", am4charts.SlicedChart); chart.data = [{ "name": "Happy mood😊", "value": 1000 }, { "name": "Relax mood😗", "value": 300 }, { "name": "Fear mood", "value": 200 }, { "name": "Frustrated mood ", "value": 180 }, { "name": "Harmful mood", "value": 50 }]; var series = chart.series.push(new am4charts.PictorialStackedSeries()); series.dataFields.value = "value"; series.dataFields.category = "name"; series.alignLabels = true; series.orientation = "vertical"; series.maskSprite.path = "M512 64c282.77 0 512 186.25 512 416 0 229.752-229.23 416-512 416-27.156 0-53.81-1.734-79.824-5.044-109.978 109.978-241.25 129.7-368.176 132.596v-26.916c68.536-33.578 128-94.74 128-164.636 0-9.754-0.758-19.33-2.164-28.696-115.796-76.264-189.836-192.754-189.836-323.304 0-229.75 229.23-416 512-416z"; // chart.tooltip.label.fill = am4core.color("#f00"); //.... //chart.current = container; return () => { chart.dispose(); }; }, []); return ( <div id="chartdiv6" style={{ width: "70%", height: "450px" }}></div> ); } export default BehaviourViz;
32.6
325
0.662577
1e112921659d9e43da6f85424a3d4a467dc15e7b
242
js
JavaScript
lib/deferrals.js
fbardelli-shutterstock/showcase
17b37b852ef9da0505b7b69cac833c4d89817e2d
[ "Unlicense" ]
19
2015-03-06T22:50:32.000Z
2021-08-01T22:39:39.000Z
lib/deferrals.js
fbardelli-shutterstock/showcase
17b37b852ef9da0505b7b69cac833c4d89817e2d
[ "Unlicense" ]
2
2015-04-24T18:04:53.000Z
2017-11-30T15:17:48.000Z
lib/deferrals.js
fbardelli-shutterstock/showcase
17b37b852ef9da0505b7b69cac833c4d89817e2d
[ "Unlicense" ]
4
2015-01-25T14:48:25.000Z
2020-04-05T02:10:09.000Z
var Deferrals = function() { this.queue = []; for (var i = 0; i < arguments.length; i++) { this.queue.push(arguments[i]); } this.run = function() { var deferral = this.queue.shift(); deferral(); }; }; module.exports = Deferrals;
17.285714
45
0.607438
1e11e79b04761be5df01062b17ead75fb75d9ca1
333
js
JavaScript
es/FilledRecentActors.js
eugeneilyin/mdi-norm
e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4
[ "MIT" ]
3
2018-11-11T01:48:20.000Z
2019-12-02T06:13:14.000Z
es/FilledRecentActors.js
eugeneilyin/mdi-norm
e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4
[ "MIT" ]
1
2019-02-21T05:59:35.000Z
2019-02-21T21:57:57.000Z
es/FilledRecentActors.js
eugeneilyin/mdi-norm
e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4
[ "MIT" ]
null
null
null
import React from 'react'; import { Icon } from './Icon'; import { pe, zi, bbt } from './fragments'; export var FilledRecentActors = /*#__PURE__*/ function FilledRecentActors(props) { return React.createElement(Icon, props, React.createElement("path", { d: "M21 5v14h2V5zm-4 14h2V5h-2zM14 5H2" + bbt + "h12" + zi + pe })); };
33.3
71
0.675676
1e1238067020c79c1db54a0c69e94f07003f80ee
2,801
js
JavaScript
src/tester/scenarios/RandomScenarios.js
crysadrak/QApe
09910d28d013ab4311a09db60e7e060a167d5e6f
[ "MIT" ]
1
2021-01-25T08:59:48.000Z
2021-01-25T08:59:48.000Z
src/tester/scenarios/RandomScenarios.js
crysadrak/QApe
09910d28d013ab4311a09db60e7e060a167d5e6f
[ "MIT" ]
null
null
null
src/tester/scenarios/RandomScenarios.js
crysadrak/QApe
09910d28d013ab4311a09db60e7e060a167d5e6f
[ "MIT" ]
null
null
null
import { report } from '../messanger'; /** * Random scenarios are default types of scenarios * executed whenever there is nothing else to execute. * They randomly click on the website and search for errors. */ export default class RandomScenarios { /** * @param {Object} config * @param {ActionsHandler} actionsHandler * @param {Reporter} reporter */ constructor(config, actionsHandler, reporter) { this._config = config; this._actionsHandler = actionsHandler; this._reporter = reporter; } /** * Specifies scenario type name * @returns {string} 'random' */ get type() { return 'random'; } /** * Executes a random scenario * performing actions on random page elements * and trying to produce some page errors. * @param {Browser} instance * @returns {Promise<Object>} results */ async runScenario(instance) { let results = {}; report('scenario:start', { type: this.type, }); let response = await instance.page.goto(this._config.url); if (response.status() >= 400) { results.executionError = `Cannot load url ${this._config.url} [status: ${response.status()}]`; } else { results = await this._performActions(instance); } report('scenario:end', { type: this.type, results, }); return results; } /** * Performs random actions on the instance * @param {Browser} instance * @returns {Promise<Object>} results */ async _performActions(instance) { let results = { scenario: [], errors: [] }; let failedActionsCount = 0; await this._config.beforeScenarioScript(instance); for (let i = 0; i < this._config.actionsPerScenario; i++) { let actionResults = await this._actionsHandler.execute(instance); if (actionResults.executionError) { failedActionsCount++; if (failedActionsCount >= this._config.numberOfActionFailuresToAbortRandomScenario) { results.executionError = 'Reached limit of allowed action execution errors.\n' + actionResults.executionError; break; } i--; continue; } else { failedActionsCount = 0; } results.scenario.push(actionResults); if (actionResults && actionResults.errors && actionResults.errors.length > 0) { results.errors = actionResults.errors; break; } } await this._config.afterScenarioScript(instance); return results; } }
27.460784
109
0.567297
1e128b4211ae5eae9619fa52fb2f9b9ce4ee68db
1,031
js
JavaScript
dist/lib-esm/text/test/xsltapply-cases.js
ruby232/web-standard-functions
7e5cb2138412360c56ad2c42bf36b643b987f5ab
[ "Apache-2.0" ]
null
null
null
dist/lib-esm/text/test/xsltapply-cases.js
ruby232/web-standard-functions
7e5cb2138412360c56ad2c42bf36b643b987f5ab
[ "Apache-2.0" ]
null
null
null
dist/lib-esm/text/test/xsltapply-cases.js
ruby232/web-standard-functions
7e5cb2138412360c56ad2c42bf36b643b987f5ab
[ "Apache-2.0" ]
null
null
null
export var testCases = [ [ /*from https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcessor/Basic_Example*/ '\n <?xml version="1.0"?>\n <?xml-stylesheet type="text/xsl" href="example.xsl"?>\n <Article>\n <Title>My Article</Title>\n <Authors>\n <Author>Mr. Foo</Author>\n <Author>Mr. Bar</Author>\n </Authors>\n <Body>This is my article text.</Body>\n </Article>\n ', '<?xml version="1.0"?>\n <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\n <xsl:output method="text"/>\n <xsl:template match="/">\n Article - <xsl:value-of select="/Article/Title"/>\n Authors:<xsl:apply-templates select="/Article/Authors/Author"/>\n </xsl:template>\n <xsl:template match="Author">\n - <xsl:value-of select="." />\n </xsl:template>\n </xsl:stylesheet>\n ', "\n Article - My Article\n Authors:\n - Mr. Foo\n - Mr. Bar", ], ]; //# sourceMappingURL=xsltapply-cases.js.map
103.1
457
0.582929
1e12a3956f405d8bf88e9a24980d69adc492c6ef
1,431
js
JavaScript
lib/locales/tr/commerce/product_description.js
iBet7o/faker.js
29234378807c4141588861f69421bf20b5ac635e
[ "MIT" ]
35,056
2015-01-01T05:58:25.000Z
2022-02-27T18:46:54.000Z
lib/locales/tr/commerce/product_description.js
iBet7o/faker.js
29234378807c4141588861f69421bf20b5ac635e
[ "MIT" ]
1,042
2015-01-02T09:59:44.000Z
2022-01-05T06:27:27.000Z
lib/locales/tr/commerce/product_description.js
iBet7o/faker.js
29234378807c4141588861f69421bf20b5ac635e
[ "MIT" ]
5,045
2015-01-09T20:18:03.000Z
2022-02-27T19:31:27.000Z
module["exports"] = [ "Gün boyu konfor ve destek için yapıştırılmış siyah deri ve PVC dolgulu koltuk ve sırt ile kaplanmış ergonomik yönetici koltuğu", "Otomobil düzeni, motorun arkasına monte edilmiş transaks tipi şanzımanlar ve dört tekerlekten çekiş ile bir ön motor tasarımından oluşur", "Yeni ABC 13 9370, 13.3, 5. Nesil CoreA5-8250U, 8GB RAM, 256GB SSD, power UHD Graphics, OS 10 Home, OS Office A & J 2016", "Dev Byte'ın ince ve basit Maple Oyun Klavyesi, şık bir gövde ve akıllı işlevsellik için 7 Renkli RGB LED Arka Aydınlatma ile birlikte gelir", "Apollotech B340, güvenilir bağlantıya, 12 aylık pil ömrüne ve modern tasarıma sahip uygun fiyatlı bir kablosuz faredir", "Nagasaki Lander, 1984 ABC800J ile başlayan birkaç Nagasaki spor bisiklet serisinin ticari markasıdır", "Futbol Antrenman Ve Rekreasyon Amaçlı İyidir", "Karbonit ağ kaleci eldivenleri ergonomik olarak kolay oturacak şekilde tasarlanmıştır", "Boston'un en gelişmiş kompresyon aşınması teknolojisi, kas oksijenlenmesini artırır, aktif kasları stabilize eder", "Yeni forma gömlek çeşitleri sizi göz önünde bulundurarak tasarlandı. Sizi farklı kılacak kesimler ve stiller ile", "Doğal bileşenlerin heyecan verici bir karışımına sahip güzel Apple Naturalé serisi. %100 Doğal İçeriğin İyiliği ile", "Andy ayakkabılar, trendlerin yanı sıra dayanıklılığı da göz önünde bulundurarak tasarlandı, en şık ayakkabı ve sandalet yelpazesi" ];
102.214286
144
0.797345
1e12c1888db741bd23fa87ab08141a1be69c847e
1,397
js
JavaScript
commands/force.js
tgreaves/cave
a5a670273ec2a52f3de53226d8a0fec4f500f9cf
[ "MIT" ]
5
2019-08-04T09:35:32.000Z
2020-05-16T04:16:32.000Z
commands/force.js
tgreaves/cave
a5a670273ec2a52f3de53226d8a0fec4f500f9cf
[ "MIT" ]
2
2019-07-26T13:23:50.000Z
2019-08-20T09:14:45.000Z
commands/force.js
tgreaves/cave
a5a670273ec2a52f3de53226d8a0fec4f500f9cf
[ "MIT" ]
1
2020-05-16T04:18:27.000Z
2020-05-16T04:18:27.000Z
'use strict'; const Ranvier = require('ranvier'); const B = Ranvier.Broadcast; const Logger = Ranvier.Logger; const ArgParser = require('../lib/ArgParser'); module.exports = { usage: 'force <player> <command>', command: (state) => (args, player, invokedCommand) => { if (!args || !args.length) { return B.sayAt(player, 'Force who?'); } let [ targetArg, forceCommand, forceCommandParam] = args.split(' '); let target = state.PlayerManager.getPlayer(targetArg); if (!target) { return B.sayAt(player, 'I don\'t know who that is.'); } if (!forceCommand) { return B.sayAt(player, 'To do what?'); } // These commands are banned for non-wizards to force. if (player.level < 4) { switch (forceCommand.toLowerCase()) { case 'quit': case 'force': case 'tell': case 'say': case 'activity': case 'collapse': return B.sayAt(player, 'NOT THAT ONE!'); } } if (player.level == 4) { // Automatic success, no need to prompt for type of forcing. return player.emit('forcing', player, target, forceCommand, forceCommandParam, 'm'); } else { // Caver needs to select HOW to force (Magic or strength?) return player.socket.emit('force-magic-or-strength', player.socket, { player, target, forceCommand, forceCommandParam }); } } };
27.392157
127
0.603436
1e12c86c760fb49a24f24b9b71e2525c777522eb
3,313
js
JavaScript
src/fts/Query.js
jestapinski/marian
6cc5161cc0c582e4c74a58369c7c7ad47e1a067a
[ "Apache-2.0" ]
17
2017-07-03T17:44:14.000Z
2022-01-21T09:01:08.000Z
src/fts/Query.js
jestapinski/marian
6cc5161cc0c582e4c74a58369c7c7ad47e1a067a
[ "Apache-2.0" ]
5
2017-08-17T21:40:54.000Z
2020-12-14T19:17:47.000Z
src/fts/Query.js
jestapinski/marian
6cc5161cc0c582e4c74a58369c7c7ad47e1a067a
[ "Apache-2.0" ]
13
2017-07-06T22:41:19.000Z
2021-10-17T10:08:00.000Z
'use strict' const {isStopWord, tokenize, stem} = require('./Stemmer.js') /** * Return true if there is a configuration of numbers in the tree that * appear in sequential order. * @param {Array<Array<number>>} tree The tree * @param {number|undefined} lastCandidate Recursive state. * @return {boolean} True if there is a configuration of numbers in the * tree that appear in sequential order. */ function haveContiguousPath(tree, lastCandidate) { if (tree.length === 0) { return true } for (const element of tree[0]) { if (lastCandidate === undefined || element === lastCandidate + 1) { if (haveContiguousPath(tree.slice(1), element)) { return true } } } return false } /** * Check if the given phraseComponents appear in contiguous positions * within the keywords map. * @param {[string]} phraseComponents List of stems that must appear sequentially. * @param {Map<string, [number]>} keywords Keywords * @return {boolean} True if there's a contiguous configuration of phrase components. */ function haveContiguousKeywords(phraseComponents, keywords) { const path = [] for (const component of phraseComponents) { const positions = keywords.get(component) if (positions === undefined) { return false } path.push(positions) } return haveContiguousPath(path) } function processPart(part) { return tokenize(part, false) } /** A parsed search query. */ class Query { /** * Create a new query. * @param {string} queryString The query to parse */ constructor(queryString) { this.terms = new Set() this.phrases = [] this.stemmedPhrases = [] this.filter = () => true const parts = queryString.split(/((?:\s+|^)"[^"]+"(?:\s+|$))/) let inQuotes = false for (const part of parts) { inQuotes = Boolean(part.match(/^\s*"/)) if (!inQuotes) { this.addTerms(processPart(part)) } else { const phraseMatch = part.match(/\s*"([^"]*)"?\s*/) if (!phraseMatch) { // This is a phrase fragment this.addTerms(processPart(part)) continue } const phrase = phraseMatch[1].toLowerCase().trim() this.phrases.push(phrase) const phraseParts = processPart(phrase) this.stemmedPhrases.push(phraseParts.filter((term) => !isStopWord(term)).map((term) => stem(term))) this.addTerms(phraseParts) } } } /** * Return true if the exact phrases in the query appear in ANY of the fields * appearing in the match. * @param {Map<String, [Number]>} tokens Token positions * @return {boolean} True if the given match contains this query's phrases. */ checkPhrases(tokens) { for (const phraseTokens of this.stemmedPhrases) { if (!haveContiguousKeywords(phraseTokens, tokens)) { return false } } return true } addTerms(terms) { for (const term of terms) { this.terms.add(term) } } } exports.Query = Query
29.061404
115
0.57863
1e1310916bd972191528bc39a8d9411ac932b4b6
44
js
JavaScript
js/main.js
MackSnider/snider_m_musicMixer
abeb1f41c7e6a9017cd70b1f080a538b7a918e38
[ "MIT" ]
null
null
null
js/main.js
MackSnider/snider_m_musicMixer
abeb1f41c7e6a9017cd70b1f080a538b7a918e38
[ "MIT" ]
null
null
null
js/main.js
MackSnider/snider_m_musicMixer
abeb1f41c7e6a9017cd70b1f080a538b7a918e38
[ "MIT" ]
null
null
null
console.log("javacript is now linked up");
14.666667
42
0.727273
1e133987f8c8aad36588c5e4bdee4cbcbc700c87
6,963
js
JavaScript
src/model/research/FluxResearchSubject.js
petertao95/flux
e4a9950ed4d63fa5fb7e9605c6d84925e500c2d5
[ "Apache-2.0" ]
null
null
null
src/model/research/FluxResearchSubject.js
petertao95/flux
e4a9950ed4d63fa5fb7e9605c6d84925e500c2d5
[ "Apache-2.0" ]
null
null
null
src/model/research/FluxResearchSubject.js
petertao95/flux
e4a9950ed4d63fa5fb7e9605c6d84925e500c2d5
[ "Apache-2.0" ]
null
null
null
import ResearchSubject from '../shr/research/ResearchSubject'; import FluxEntry from '../base/FluxEntry'; import Status from '../shr/action/Status'; import Study from '../shr/research/Study'; import TimePeriod from '../shr/core/TimePeriod'; import Title from '../shr/core/Title'; import Details from '../shr/core/Details'; import Identifier from '../shr/core/Identifier'; import Entry from '../shr/base/Entry'; import EntryType from '../shr/base/EntryType'; import ParticipationPeriod from '../shr/action/ParticipationPeriod'; import TimePeriodStart from '../shr/core/TimePeriodStart'; import TimePeriodEnd from '../shr/core/TimePeriodEnd'; import Lang from 'lodash'; import lookup from '../../lib/clinicaltrial_lookup.jsx'; class FluxResearchSubject extends FluxEntry { constructor(json) { super(); this._entry = this._researchSubject = ResearchSubject.fromJSON(json); if (!this._researchSubject.entryInfo) { let entry = new Entry(); entry.entryType = new EntryType(); entry.entryType.uri = 'http://standardhealthrecord.org/spec/shr/research/ResearchSubject'; this._researchSubject.entryInfo = entry; } } get entryInfo() { return this._researchSubject.entryInfo; } /** * Getter for title * This will return the displayText value from the Title object */ get title() { if (this._researchSubject.study && this._researchSubject.study.title) { return this._researchSubject.study.title.value; } else { return ""; } } _createStudyIfNeeded() { if (!this._researchSubject.study) { this._researchSubject.study = new Study(); this._researchSubject.study.entryInfo = new Entry(); this._researchSubject.study.entryInfo.entryType = new EntryType(); this._researchSubject.study.entryInfo.entryType.uri = 'http://standardhealthrecord.org/spec/shr/research/Study'; } } /** * Setter for title * The setter method is expecting a title sting * The method will create a Title object and set the value to the title string */ set title(title) { this._createStudyIfNeeded(); /* if (Lang.isNull(title)) { this._researchSubject.study.title = null; return; }*/ if (!this._researchSubject.study.title) { this._researchSubject.study.title = new Title(); } this._researchSubject.study.title.value = title; } /** * Getter for detail * This will return the displayText value from the Details object */ get details() { if (this._researchSubject.study && this._researchSubject.study.details) { return this._researchSubject.study.details.value; } else { return ""; } } /** * Setter for details * The setter method is expecting a details sting * The method will create a Details object and set the value to the detail string */ set details(details) { if (Lang.isNull(details)) return; this._createStudyIfNeeded(); let detailsObj = new Details(); detailsObj.value = details; this._researchSubject.study.details = detailsObj; } /** * Getter for identifier * This will return the displayText value from the Identifier object */ get identifier() { return this._researchSubject.study.identifier.value || ""; } /** * Setter for identifier * The setter method is expecting a identifier sting * The method will create an Identifier object and set the value to the identifier string */ set identifier(identifier) { this._createStudyIfNeeded(); let i = new Identifier(); i.value = identifier; this._researchSubject.study.identifier = i; } get enrollmentDate() { if (!this._researchSubject.participationPeriod || !this._researchSubject.participationPeriod.timePeriod || !this._researchSubject.participationPeriod.timePeriod.timePeriodStart) return null; return this._researchSubject.participationPeriod.timePeriod.timePeriodStart.value; } set enrollmentDate(val) { /* if (Lang.isNull(val)) { if (this._researchSubject.participationPeriod && this._researchSubject.participationPeriod.timePeriod) { this._researchSubject.participationPeriod.timePeriod.timePeriodStart = null; } return; }*/ if (!this._researchSubject.participationPeriod) { this._researchSubject.participationPeriod = new ParticipationPeriod(); } if (!this._researchSubject.participationPeriod.timePeriod) { this._researchSubject.participationPeriod.timePeriod = new TimePeriod(); } if (!this._researchSubject.participationPeriod.timePeriod.timePeriodStart) { this._researchSubject.participationPeriod.timePeriod.timePeriodStart = new TimePeriodStart(); } this._researchSubject.participationPeriod.timePeriod.timePeriodStart.value = val; } get endDate() { if (!this._researchSubject.participationPeriod || !this._researchSubject.participationPeriod.timePeriod || !this._researchSubject.participationPeriod.timePeriod.timePeriodEnd) return null; return this._researchSubject.participationPeriod.timePeriod.timePeriodEnd.value; } set endDate(val) { /* if (Lang.isNull(val)) { if (this._researchSubject.participationPeriod && this._researchSubject.participationPeriod.timePeriod) { this._researchSubject.participationPeriod.timePeriod.timePeriodEnd = null; } return; }*/ if (!this._researchSubject.participationPeriod) { this._researchSubject.participationPeriod = new ParticipationPeriod(); } if (!this._researchSubject.participationPeriod.timePeriod) { this._researchSubject.participationPeriod.timePeriod = new TimePeriod(); } if (!this._researchSubject.participationPeriod.timePeriod.timePeriodEnd) { this._researchSubject.participationPeriod.timePeriod.timePeriodEnd = new TimePeriodEnd(); } this._researchSubject.participationPeriod.timePeriod.timePeriodEnd.value = val; } get status() { if (!this._researchSubject.status || !this._researchSubject.status.value) return null; return this._researchSubject.status.value.coding[0].displayText.value; } set status(val) { if (!this._researchSubject.status) { this._researchSubject.status = new Status(); } this._researchSubject.status.value = lookup.getStatusCodeableConcept(val); } toJSON() { return this._researchSubject.toJSON(); } } export default FluxResearchSubject;
38.683333
198
0.661209
1e13ad77a9d818c2a8037f9754d75026a73affac
3,114
js
JavaScript
tests/external/my.cases.spec.js
bcgov/jag-efiling-api
cb71978737eb587cd3baa6e2cc6cbe42443d40f9
[ "Apache-2.0" ]
4
2018-03-02T01:41:33.000Z
2020-04-24T06:47:17.000Z
tests/external/my.cases.spec.js
bcgov/jag-efiling-api
cb71978737eb587cd3baa6e2cc6cbe42443d40f9
[ "Apache-2.0" ]
10
2020-01-17T01:51:49.000Z
2022-01-10T21:00:03.000Z
tests/external/my.cases.spec.js
bcgov/jag-efiling-api
cb71978737eb587cd3baa6e2cc6cbe42443d40f9
[ "Apache-2.0" ]
3
2018-05-09T17:59:44.000Z
2020-03-11T18:42:40.000Z
var expect = require('chai').expect; var Server = require('../../app/server/server'); var Database = require('../../app/store/database'); var Migrator = require('../../app/migrations/migrator'); var Truncator = require('../support/truncator'); var { execute } = require('yop-postgresql'); var { request, localhost5000json } = require('../support/request'); describe('My cases endpoint', function() { var server; var database; var mycases = localhost5000json({ path: '/api/cases', }); beforeEach(function(done) { server = new Server(); database = new Database(); server.useDatabase(database); var migrator = new Migrator(); migrator.migrateNow(function() { var truncator = new Truncator(); truncator.truncateTablesNow(function() { server.start(5000, 'localhost', done); }); }); }); afterEach(function(done) { server.stop(done); }); it('is a rest service', function(done){ var background = [ 'alter sequence person_id_seq restart', { sql:'insert into person(login) values ($1)', params:['bob'] }, { sql:'insert into person(login) values ($1)', params:['max'] }, { sql: 'insert into forms(person_id, type, status, data) values($1, $2, $3, $4);', params:[1, 'crazy-bob', 'new', JSON.stringify({value:'bob'})] }, { sql: 'insert into forms(person_id, type, status, data) values($1, $2, $3, $4);', params:[2, 'crazy-max', 'new', JSON.stringify({value:'max'})] }, 'select last_value from forms_id_seq' ]; execute(background, function(err, rows) { var newId = parseInt(rows[0].last_value); request(mycases, (err, response, body)=> { expect(response.statusCode).to.equal(200); let theCase = JSON.parse(body).cases[0]; expect(theCase.id).to.equal(newId); expect(theCase.type).to.equal('crazy-max'); expect(theCase.status).to.equal('new'); expect(theCase.data).to.deep.equal({value:'max'}); expect(new Date()-new Date(theCase.modified)).to.be.lessThan(2000); done(); }); }); }); it('ignores archived case', function(done){ var background = [ 'alter sequence person_id_seq restart', { sql:'insert into person(login) values ($1)', params:['max'] }, { sql: 'insert into forms(person_id, type, status, data) values($1, $2, $3, $4);', params:[1, 'crazy-max', 'archived', JSON.stringify({value:'max'})] }, 'select last_value from forms_id_seq' ]; execute(background, function(err, rows) { var newId = parseInt(rows[0].last_value); request(mycases, (err, response, body)=> { expect(response.statusCode).to.equal(200); let cases = JSON.parse(body).cases; expect(cases.length).to.equal(0); done(); }); }); }); });
39.417722
164
0.549133
1e13b1949b1ca73aea4d2a6ba956252e16aca91b
1,792
js
JavaScript
server/models/index.js
CelestialSystem/Coworkee
e3756d2dba76e3194305ee39483b2c767e381f0e
[ "MIT" ]
130
2017-05-11T15:40:37.000Z
2021-03-11T15:26:24.000Z
server/models/index.js
CelestialSystem/Coworkee
e3756d2dba76e3194305ee39483b2c767e381f0e
[ "MIT" ]
14
2017-05-23T01:32:15.000Z
2021-10-30T09:18:05.000Z
server/models/index.js
CelestialSystem/Coworkee
e3756d2dba76e3194305ee39483b2c767e381f0e
[ "MIT" ]
91
2017-05-10T21:18:21.000Z
2022-03-08T07:35:52.000Z
/** * This file collects all the models from the models directory and associates them if needed. */ "use strict"; var fs = require("fs"); var path = require("path"); var Sequelize = require("sequelize"); var Op = Sequelize.Op; var env = process.env.NODE_ENV || "development"; var config = require(path.join(__dirname, '..', 'utils', 'config')).database; config = config || {}; config.operatorsAliases = { $eq: Op.eq, $ne: Op.ne, $gte: Op.gte, $gt: Op.gt, $lte: Op.lte, $lt: Op.lt, $not: Op.not, $in: Op.in, $notIn: Op.notIn, $is: Op.is, $like: Op.like, $notLike: Op.notLike, $iLike: Op.iLike, $notILike: Op.notILike, $regexp: Op.regexp, $notRegexp: Op.notRegexp, $iRegexp: Op.iRegexp, $notIRegexp: Op.notIRegexp, $between: Op.between, $notBetween: Op.notBetween, $overlap: Op.overlap, $contains: Op.contains, $contained: Op.contained, $adjacent: Op.adjacent, $strictLeft: Op.strictLeft, $strictRight: Op.strictRight, $noExtendRight: Op.noExtendRight, $noExtendLeft: Op.noExtendLeft, $and: Op.and, $or: Op.or, $any: Op.any, $all: Op.all, $values: Op.values, $col: Op.col }; var sequelize = new Sequelize(config.database, config.username, config.password, config); var db = {}; fs.readdirSync(__dirname) .filter(function(file) { return (file.indexOf(".") !== 0) && (file !== "index.js"); }) .forEach(function(file) { var model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if ("associate" in db[modelName]) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
24.547945
93
0.616629
1e1404dd76f6184bcd066386f77c6bbe33d7c6cf
1,307
js
JavaScript
assets/Server.js
didoykent/lmsrep
db8d4e1ce1baa512a5f72f7337e42b09c78e2566
[ "MIT" ]
null
null
null
assets/Server.js
didoykent/lmsrep
db8d4e1ce1baa512a5f72f7337e42b09c78e2566
[ "MIT" ]
4
2021-03-10T21:21:41.000Z
2022-02-27T06:13:43.000Z
assets/Server.js
didoykent/lmsrep
db8d4e1ce1baa512a5f72f7337e42b09c78e2566
[ "MIT" ]
null
null
null
var app = require('express'); var server = require('http').Server(app); var io = require('socket.io')(server); var redis = require('redis'); const axios = require('axios'); let Users = []; server.listen(7740); var redisClient = redis.createClient(); redisClient.subscribe('notif'); redisClient.on('message', function(channel, message){ if(message.trim() && channel === 'notif'){ const user = JSON.parse(message) if(user){ Users.push(user.conn_id) } console.log(Users, 'users') } }) io.on('connection', function(socket){ console.log('Client connected') socket.on('student_writing_correction', function(message){ if(message){ io.sockets.emit('tutor_writing_correction', message) } console.log(message, 'correction') }) socket.on('set_content_correction', function(message) { if(message){ io.sockets.emit('tutor_corrected_content', message) console.log(message) } }) socket.on('qa', function(message) { if(message){ io.sockets.emit('student_qa', message) console.log(message) } }) socket.on('qa_reply', function(message){ if(message){ io.sockets.emit('qa_answer', message) console.log(message) } }) socket.on('disconnect', function(){ }) });
15.376471
61
0.630451
1e1406aa86a59564c084422cd995c8d971e381a1
1,007
js
JavaScript
node_modules/@antv/f2/src/geom/path.js
wtflove/vue-webpack_demo
11a108b54a781946d4a450cedc8ccc4352b51478
[ "ISC" ]
1
2018-08-28T09:30:49.000Z
2018-08-28T09:30:49.000Z
src/geom/path.js
Qutuijian/F2
893886345331f48bb5af30b85685aeba93ba46f9
[ "MIT" ]
null
null
null
src/geom/path.js
Qutuijian/F2
893886345331f48bb5af30b85685aeba93ba46f9
[ "MIT" ]
null
null
null
const Geom = require('./base'); const ShapeUtil = require('./shape/util'); const Util = require('../util/common'); require('./shape/line'); class Path extends Geom { getDefaultCfg() { const cfg = super.getDefaultCfg(); cfg.type = 'path'; cfg.shapeType = 'line'; return cfg; } getDrawCfg(obj) { const cfg = super.getDrawCfg(obj); cfg.isStack = this.hasAdjust('stack'); return cfg; } draw(data, shapeFactory) { const self = this; const container = self.get('container'); const yScale = self.getYScale(); const connectNulls = self.get('connectNulls'); const splitArray = ShapeUtil.splitArray(data, yScale.field, connectNulls); const cfg = this.getDrawCfg(data[0]); cfg.origin = data; Util.each(splitArray, function(subData, splitedIndex) { cfg.splitedIndex = splitedIndex; cfg.points = subData; self.drawShape(cfg.shape, data[0], cfg, container, shapeFactory); }); } } Geom.Path = Path; module.exports = Path;
25.175
78
0.649454