text
stringlengths
3
1.05M
# Copyright 2020 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """Bert for pretraining.""" import numpy as np import mindspore.nn as nn from mindspore.common.initializer import initializer, TruncatedNormal from mindspore.ops import operations as P from mindspore.ops import functional as F from mindspore.ops import composite as C from mindspore.common.tensor import Tensor from mindspore.common.parameter import Parameter, ParameterTuple from mindspore.common import dtype as mstype from mindspore.nn.wrap.grad_reducer import DistributedGradReducer from mindspore.context import ParallelMode from mindspore.communication.management import get_group_size from mindspore import context from .bert_model import BertModel GRADIENT_CLIP_TYPE = 1 GRADIENT_CLIP_VALUE = 1.0 clip_grad = C.MultitypeFuncGraph("clip_grad") # pylint: disable=consider-using-in @clip_grad.register("Number", "Number", "Tensor") def _clip_grad(clip_type, clip_value, grad): """ Clip gradients. Inputs: clip_type (int): The way to clip, 0 for 'value', 1 for 'norm'. clip_value (float): Specifies how much to clip. grad (tuple[Tensor]): Gradients. Outputs: tuple[Tensor], clipped gradients. """ if clip_type != 0 and clip_type != 1: return grad dt = F.dtype(grad) if clip_type == 0: new_grad = C.clip_by_value(grad, F.cast(F.tuple_to_array((-clip_value,)), dt), F.cast(F.tuple_to_array((clip_value,)), dt)) else: new_grad = nn.ClipByNorm()(grad, F.cast(F.tuple_to_array((clip_value,)), dt)) return new_grad class GetMaskedLMOutput(nn.Cell): """ Get masked lm output. Args: config (BertConfig): The config of BertModel. Returns: Tensor, masked lm output. """ def __init__(self, config): super(GetMaskedLMOutput, self).__init__() self.width = config.hidden_size self.reshape = P.Reshape() self.gather = P.Gather() weight_init = TruncatedNormal(config.initializer_range) self.dense = nn.Dense(self.width, config.hidden_size, weight_init=weight_init, activation=config.hidden_act).to_float(config.compute_type) self.layernorm = nn.LayerNorm((config.hidden_size,)).to_float(config.compute_type) self.output_bias = Parameter( initializer( 'zero', config.vocab_size), name='output_bias') self.matmul = P.MatMul(transpose_b=True) self.log_softmax = nn.LogSoftmax(axis=-1) self.shape_flat_offsets = (-1, 1) self.rng = Tensor(np.array(range(0, config.batch_size)).astype(np.int32)) self.last_idx = (-1,) self.shape_flat_sequence_tensor = (config.batch_size * config.seq_length, self.width) self.seq_length_tensor = Tensor(np.array((config.seq_length,)).astype(np.int32)) self.cast = P.Cast() self.compute_type = config.compute_type self.dtype = config.dtype def construct(self, input_tensor, output_weights, positions): flat_offsets = self.reshape( self.rng * self.seq_length_tensor, self.shape_flat_offsets) flat_position = self.reshape(positions + flat_offsets, self.last_idx) flat_sequence_tensor = self.reshape(input_tensor, self.shape_flat_sequence_tensor) input_tensor = self.gather(flat_sequence_tensor, flat_position, 0) input_tensor = self.cast(input_tensor, self.compute_type) output_weights = self.cast(output_weights, self.compute_type) input_tensor = self.dense(input_tensor) input_tensor = self.layernorm(input_tensor) logits = self.matmul(input_tensor, output_weights) logits = self.cast(logits, self.dtype) logits = logits + self.output_bias log_probs = self.log_softmax(logits) return log_probs class GetNextSentenceOutput(nn.Cell): """ Get next sentence output. Args: config (BertConfig): The config of Bert. Returns: Tensor, next sentence output. """ def __init__(self, config): super(GetNextSentenceOutput, self).__init__() self.log_softmax = P.LogSoftmax() self.weight_init = TruncatedNormal(config.initializer_range) self.dense = nn.Dense(config.hidden_size, 2, weight_init=self.weight_init, has_bias=True).to_float(config.compute_type) self.dtype = config.dtype self.cast = P.Cast() def construct(self, input_tensor): logits = self.dense(input_tensor) logits = self.cast(logits, self.dtype) log_prob = self.log_softmax(logits) return log_prob class BertPreTraining(nn.Cell): """ Bert pretraining network. Args: config (BertConfig): The config of BertModel. is_training (bool): Specifies whether to use the training mode. use_one_hot_embeddings (bool): Specifies whether to use one-hot for embeddings. Returns: Tensor, prediction_scores, seq_relationship_score. """ def __init__(self, config, is_training, use_one_hot_embeddings): super(BertPreTraining, self).__init__() self.bert = BertModel(config, is_training, use_one_hot_embeddings) self.cls1 = GetMaskedLMOutput(config) self.cls2 = GetNextSentenceOutput(config) def construct(self, input_ids, input_mask, token_type_id, masked_lm_positions): sequence_output, pooled_output, embedding_table = \ self.bert(input_ids, token_type_id, input_mask) prediction_scores = self.cls1(sequence_output, embedding_table, masked_lm_positions) seq_relationship_score = self.cls2(pooled_output) return prediction_scores, seq_relationship_score class BertPretrainingLoss(nn.Cell): """ Provide bert pre-training loss. Args: config (BertConfig): The config of BertModel. Returns: Tensor, total loss. """ def __init__(self, config): super(BertPretrainingLoss, self).__init__() self.vocab_size = config.vocab_size self.onehot = P.OneHot() self.on_value = Tensor(1.0, mstype.float32) self.off_value = Tensor(0.0, mstype.float32) self.reduce_sum = P.ReduceSum() self.reduce_mean = P.ReduceMean() self.reshape = P.Reshape() self.last_idx = (-1,) self.neg = P.Neg() self.cast = P.Cast() def construct(self, prediction_scores, seq_relationship_score, masked_lm_ids, masked_lm_weights, next_sentence_labels): """Defines the computation performed.""" label_ids = self.reshape(masked_lm_ids, self.last_idx) label_weights = self.cast(self.reshape(masked_lm_weights, self.last_idx), mstype.float32) one_hot_labels = self.onehot(label_ids, self.vocab_size, self.on_value, self.off_value) per_example_loss = self.neg(self.reduce_sum(prediction_scores * one_hot_labels, self.last_idx)) numerator = self.reduce_sum(label_weights * per_example_loss, ()) denominator = self.reduce_sum(label_weights, ()) + self.cast(F.tuple_to_array((1e-5,)), mstype.float32) masked_lm_loss = numerator / denominator # next_sentence_loss labels = self.reshape(next_sentence_labels, self.last_idx) one_hot_labels = self.onehot(labels, 2, self.on_value, self.off_value) per_example_loss = self.neg(self.reduce_sum( one_hot_labels * seq_relationship_score, self.last_idx)) next_sentence_loss = self.reduce_mean(per_example_loss, self.last_idx) # total_loss total_loss = masked_lm_loss + next_sentence_loss return total_loss class BertNetworkWithLoss(nn.Cell): """ Provide bert pre-training loss through network. Args: config (BertConfig): The config of BertModel. is_training (bool): Specifies whether to use the training mode. use_one_hot_embeddings (bool): Specifies whether to use one-hot for embeddings. Default: False. Returns: Tensor, the loss of the network. """ def __init__(self, config, is_training, use_one_hot_embeddings=False): super(BertNetworkWithLoss, self).__init__() self.bert = BertPreTraining(config, is_training, use_one_hot_embeddings) self.loss = BertPretrainingLoss(config) self.cast = P.Cast() def construct(self, input_ids, input_mask, token_type_id, next_sentence_labels, masked_lm_positions, masked_lm_ids, masked_lm_weights): prediction_scores, seq_relationship_score = \ self.bert(input_ids, input_mask, token_type_id, masked_lm_positions) total_loss = self.loss(prediction_scores, seq_relationship_score, masked_lm_ids, masked_lm_weights, next_sentence_labels) return self.cast(total_loss, mstype.float32) class BertTrainOneStepCell(nn.Cell): """ Encapsulation class of bert network training. Append an optimizer to the training network after that the construct function can be called to create the backward graph. Args: network (Cell): The training network. Note that loss function should have been added. optimizer (Optimizer): Optimizer for updating the weights. sens (Number): The adjust parameter. Default: 1.0. """ def __init__(self, network, optimizer, sens=1.0): super(BertTrainOneStepCell, self).__init__(auto_prefix=False) self.network = network self.weights = ParameterTuple(network.trainable_params()) self.optimizer = optimizer self.grad = C.GradOperation(get_by_list=True, sens_param=True) self.sens = sens self.reducer_flag = False self.parallel_mode = context.get_auto_parallel_context("parallel_mode") if self.parallel_mode in [ParallelMode.DATA_PARALLEL, ParallelMode.HYBRID_PARALLEL]: self.reducer_flag = True self.grad_reducer = None if self.reducer_flag: mean = context.get_auto_parallel_context("gradients_mean") degree = get_group_size() self.grad_reducer = DistributedGradReducer(optimizer.parameters, mean, degree) self.cast = P.Cast() self.hyper_map = C.HyperMap() def set_sens(self, value): self.sens = value def construct(self, input_ids, input_mask, token_type_id, next_sentence_labels, masked_lm_positions, masked_lm_ids, masked_lm_weights): """Defines the computation performed.""" weights = self.weights loss = self.network(input_ids, input_mask, token_type_id, next_sentence_labels, masked_lm_positions, masked_lm_ids, masked_lm_weights) grads = self.grad(self.network, weights)(input_ids, input_mask, token_type_id, next_sentence_labels, masked_lm_positions, masked_lm_ids, masked_lm_weights, self.cast(F.tuple_to_array((self.sens,)), mstype.float32)) grads = self.hyper_map(F.partial(clip_grad, GRADIENT_CLIP_TYPE, GRADIENT_CLIP_VALUE), grads) if self.reducer_flag: # apply grad reducer on grads grads = self.grad_reducer(grads) succ = self.optimizer(grads) return F.depend(loss, succ) grad_scale = C.MultitypeFuncGraph("grad_scale") reciprocal = P.Reciprocal() @grad_scale.register("Tensor", "Tensor") def tensor_grad_scale(scale, grad): return grad * reciprocal(scale) class BertTrainOneStepWithLossScaleCell(nn.Cell): """ Encapsulation class of bert network training. Append an optimizer to the training network after that the construct function can be called to create the backward graph. Args: network (Cell): The training network. Note that loss function should have been added. optimizer (Optimizer): Optimizer for updating the weights. scale_update_cell (Cell): Cell to do the loss scale. Default: None. """ def __init__(self, network, optimizer, scale_update_cell=None): super(BertTrainOneStepWithLossScaleCell, self).__init__(auto_prefix=False) self.network = network self.weights = ParameterTuple(network.trainable_params()) self.optimizer = optimizer self.grad = C.GradOperation(get_by_list=True, sens_param=True) self.reducer_flag = False self.allreduce = P.AllReduce() self.parallel_mode = context.get_auto_parallel_context("parallel_mode") if self.parallel_mode in [ParallelMode.DATA_PARALLEL, ParallelMode.HYBRID_PARALLEL]: self.reducer_flag = True self.grad_reducer = F.identity self.degree = 1 if self.reducer_flag: self.degree = get_group_size() self.grad_reducer = DistributedGradReducer(optimizer.parameters, False, self.degree) self.is_distributed = (self.parallel_mode != ParallelMode.STAND_ALONE) self.cast = P.Cast() self.alloc_status = P.NPUAllocFloatStatus() self.get_status = P.NPUGetFloatStatus() self.clear_before_grad = P.NPUClearFloatStatus() self.reduce_sum = P.ReduceSum(keep_dims=False) self.depend_parameter_use = P.ControlDepend(depend_mode=1) self.base = Tensor(1, mstype.float32) self.less_equal = P.LessEqual() self.hyper_map = C.HyperMap() self.loss_scale = None self.loss_scaling_manager = scale_update_cell if scale_update_cell: self.loss_scale = Parameter(Tensor(scale_update_cell.get_loss_scale(), dtype=mstype.float32), name="loss_scale") @C.add_flags(has_effect=True) def construct(self, input_ids, input_mask, token_type_id, next_sentence_labels, masked_lm_positions, masked_lm_ids, masked_lm_weights, sens=None): """Defines the computation performed.""" weights = self.weights loss = self.network(input_ids, input_mask, token_type_id, next_sentence_labels, masked_lm_positions, masked_lm_ids, masked_lm_weights) if sens is None: scaling_sens = self.loss_scale else: scaling_sens = sens # alloc status and clear should be right before gradoperation init = self.alloc_status() self.clear_before_grad(init) grads = self.grad(self.network, weights)(input_ids, input_mask, token_type_id, next_sentence_labels, masked_lm_positions, masked_lm_ids, masked_lm_weights, self.cast(scaling_sens, mstype.float32)) # apply grad reducer on grads grads = self.grad_reducer(grads) grads = self.hyper_map(F.partial(grad_scale, scaling_sens * self.degree), grads) grads = self.hyper_map(F.partial(clip_grad, GRADIENT_CLIP_TYPE, GRADIENT_CLIP_VALUE), grads) self.get_status(init) flag_sum = self.reduce_sum(init, (0,)) if self.is_distributed: # sum overflow flag over devices flag_reduce = self.allreduce(flag_sum) cond = self.less_equal(self.base, flag_reduce) else: cond = self.less_equal(self.base, flag_sum) overflow = cond if sens is None: overflow = self.loss_scaling_manager(self.loss_scale, cond) if overflow: succ = False else: succ = self.optimizer(grads) ret = (loss, cond, scaling_sens) return F.depend(ret, succ)
/** * @license * Copyright 2018-2022 Streamlit 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. */ describe("st.spinner", () => { before(() => { cy.loadApp("http://localhost:3000/"); }); it("displays a message", () => { cy.get(".stButton > button").click(); // click button to trigger spinner execution cy.get(".element-container .stSpinner").should("contain", "Loading..."); }); });
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2015 kyuupichan@gmail # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from collections import defaultdict from math import floor, log10 from typing import NamedTuple, List, Callable, Sequence, Union, Dict, Tuple from decimal import Decimal from .bitcoin import sha256, COIN, is_address from .transaction import Transaction, TxOutput, PartialTransaction, PartialTxInput, PartialTxOutput from .util import NotEnoughFunds from .logging import Logger # A simple deterministic PRNG. Used to deterministically shuffle a # set of coins - the same set of coins should produce the same output. # Although choosing UTXOs "randomly" we want it to be deterministic, # so if sending twice from the same UTXO set we choose the same UTXOs # to spend. This prevents attacks on users by malicious or stale # servers. class PRNG: def __init__(self, seed): self.sha = sha256(seed) self.pool = bytearray() def get_bytes(self, n: int) -> bytes: while len(self.pool) < n: self.pool.extend(self.sha) self.sha = sha256(self.sha) result, self.pool = self.pool[:n], self.pool[n:] return bytes(result) def randint(self, start, end): # Returns random integer in [start, end) n = end - start r = 0 p = 1 while p < n: r = self.get_bytes(1)[0] + (r << 8) p = p << 8 return start + (r % n) def choice(self, seq): return seq[self.randint(0, len(seq))] def shuffle(self, x): for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = self.randint(0, i+1) x[i], x[j] = x[j], x[i] class Bucket(NamedTuple): desc: str weight: int # as in BIP-141 value: int # in satoshis effective_value: int # estimate of value left after subtracting fees. in satoshis coins: List[PartialTxInput] # UTXOs min_height: int # min block height where a coin was confirmed witness: bool # whether any coin uses segwit class ScoredCandidate(NamedTuple): penalty: float tx: PartialTransaction buckets: List[Bucket] def strip_unneeded(bkts: List[Bucket], sufficient_funds) -> List[Bucket]: '''Remove buckets that are unnecessary in achieving the spend amount''' if sufficient_funds([], bucket_value_sum=0): # none of the buckets are needed return [] bkts = sorted(bkts, key=lambda bkt: bkt.value, reverse=True) bucket_value_sum = 0 for i in range(len(bkts)): bucket_value_sum += (bkts[i]).value if sufficient_funds(bkts[:i+1], bucket_value_sum=bucket_value_sum): return bkts[:i+1] raise Exception("keeping all buckets is still not enough") class CoinChooserBase(Logger): def __init__(self, *, enable_output_value_rounding: bool): Logger.__init__(self) self.enable_output_value_rounding = enable_output_value_rounding def keys(self, coins: Sequence[PartialTxInput]) -> Sequence[str]: raise NotImplementedError def bucketize_coins(self, coins: Sequence[PartialTxInput], *, fee_estimator_vb): keys = self.keys(coins) buckets = defaultdict(list) # type: Dict[str, List[PartialTxInput]] for key, coin in zip(keys, coins): buckets[key].append(coin) # fee_estimator returns fee to be paid, for given vbytes. # guess whether it is just returning a constant as follows. constant_fee = fee_estimator_vb(2000) == fee_estimator_vb(200) def make_Bucket(desc: str, coins: List[PartialTxInput]): witness = any(coin.is_segwit(guess_for_address=True) for coin in coins) # note that we're guessing whether the tx uses segwit based # on this single bucket weight = sum(Transaction.estimated_input_weight(coin, witness) for coin in coins) value = sum(coin.value_sats() for coin in coins) min_height = min(coin.block_height for coin in coins) assert min_height is not None # the fee estimator is typically either a constant or a linear function, # so the "function:" effective_value(bucket) will be homomorphic for addition # i.e. effective_value(b1) + effective_value(b2) = effective_value(b1 + b2) if constant_fee: effective_value = value else: # when converting from weight to vBytes, instead of rounding up, # keep fractional part, to avoid overestimating fee fee = fee_estimator_vb(Decimal(weight) / 4) effective_value = value - fee return Bucket(desc=desc, weight=weight, value=value, effective_value=effective_value, coins=coins, min_height=min_height, witness=witness) return list(map(make_Bucket, buckets.keys(), buckets.values())) def penalty_func(self, base_tx, *, tx_from_buckets: Callable[[List[Bucket]], Tuple[PartialTransaction, List[PartialTxOutput]]]) \ -> Callable[[List[Bucket]], ScoredCandidate]: raise NotImplementedError def _change_amounts(self, tx: PartialTransaction, count: int, fee_estimator_numchange) -> List[int]: # Break change up if bigger than max_change output_amounts = [o.value for o in tx.outputs()] # Don't split change of less than 0.02 BTC max_change = max(max(output_amounts) * 1.25, 0.02 * COIN) # Use N change outputs for n in range(1, count + 1): # How much is left if we add this many change outputs? change_amount = max(0, tx.get_fee() - fee_estimator_numchange(n)) if change_amount // n <= max_change: break # Get a handle on the precision of the output amounts; round our # change to look similar def trailing_zeroes(val): s = str(val) return len(s) - len(s.rstrip('0')) zeroes = [trailing_zeroes(i) for i in output_amounts] min_zeroes = min(zeroes) max_zeroes = max(zeroes) if n > 1: zeroes = range(max(0, min_zeroes - 1), (max_zeroes + 1) + 1) else: # if there is only one change output, this will ensure that we aim # to have one that is exactly as precise as the most precise output zeroes = [min_zeroes] # Calculate change; randomize it a bit if using more than 1 output remaining = change_amount amounts = [] while n > 1: average = remaining / n amount = self.p.randint(int(average * 0.7), int(average * 1.3)) precision = min(self.p.choice(zeroes), int(floor(log10(amount)))) amount = int(round(amount, -precision)) amounts.append(amount) remaining -= amount n -= 1 # Last change output. Round down to maximum precision but lose # no more than 10**max_dp_to_round_for_privacy # e.g. a max of 2 decimal places means losing 100 satoshis to fees max_dp_to_round_for_privacy = 2 if self.enable_output_value_rounding else 0 N = int(pow(10, min(max_dp_to_round_for_privacy, zeroes[0]))) amount = (remaining // N) * N amounts.append(amount) assert sum(amounts) <= change_amount return amounts def _change_outputs(self, tx: PartialTransaction, change_addrs, fee_estimator_numchange, dust_threshold) -> List[PartialTxOutput]: amounts = self._change_amounts(tx, len(change_addrs), fee_estimator_numchange) assert min(amounts) >= 0 assert len(change_addrs) >= len(amounts) assert all([isinstance(amt, int) for amt in amounts]) # If change is above dust threshold after accounting for the # size of the change output, add it to the transaction. amounts = [amount for amount in amounts if amount >= dust_threshold] change = [PartialTxOutput.from_address_and_value(addr, amount) for addr, amount in zip(change_addrs, amounts)] return change def _construct_tx_from_selected_buckets(self, *, buckets: Sequence[Bucket], base_tx: PartialTransaction, change_addrs, fee_estimator_w, dust_threshold, base_weight) -> Tuple[PartialTransaction, List[PartialTxOutput]]: # make a copy of base_tx so it won't get mutated tx = PartialTransaction.from_io(base_tx.inputs()[:], base_tx.outputs()[:]) tx.add_inputs([coin for b in buckets for coin in b.coins]) tx_weight = self._get_tx_weight(buckets, base_weight=base_weight) # change is sent back to sending address unless specified if not change_addrs: change_addrs = [tx.inputs()[0].address] # note: this is not necessarily the final "first input address" # because the inputs had not been sorted at this point assert is_address(change_addrs[0]) # This takes a count of change outputs and returns a tx fee output_weight = 4 * Transaction.estimated_output_size_for_address(change_addrs[0]) fee_estimator_numchange = lambda count: fee_estimator_w(tx_weight + count * output_weight) change = self._change_outputs(tx, change_addrs, fee_estimator_numchange, dust_threshold) tx.add_outputs(change) return tx, change def _get_tx_weight(self, buckets: Sequence[Bucket], *, base_weight: int) -> int: """Given a collection of buckets, return the total weight of the resulting transaction. base_weight is the weight of the tx that includes the fixed (non-change) outputs and potentially some fixed inputs. Note that the change outputs at this point are not yet known so they are NOT accounted for. """ total_weight = base_weight + sum(bucket.weight for bucket in buckets) is_segwit_tx = any(bucket.witness for bucket in buckets) if is_segwit_tx: total_weight += 2 # marker and flag # non-segwit inputs were previously assumed to have # a witness of '' instead of '00' (hex) # note that mixed legacy/segwit buckets are already ok num_legacy_inputs = sum((not bucket.witness) * len(bucket.coins) for bucket in buckets) total_weight += num_legacy_inputs return total_weight def make_tx(self, *, coins: Sequence[PartialTxInput], inputs: List[PartialTxInput], outputs: List[PartialTxOutput], change_addrs: Sequence[str], fee_estimator_vb: Callable, dust_threshold: int) -> PartialTransaction: """Select unspent coins to spend to pay outputs. If the change is greater than dust_threshold (after adding the change output to the transaction) it is kept, otherwise none is sent and it is added to the transaction fee. `inputs` and `outputs` are guaranteed to be a subset of the inputs and outputs of the resulting transaction. `coins` are further UTXOs we can choose from. Note: fee_estimator_vb expects virtual bytes """ assert outputs, 'tx outputs cannot be empty' # Deterministic randomness from coins utxos = [c.prevout.serialize_to_network() for c in coins] self.p = PRNG(b''.join(sorted(utxos))) # Copy the outputs so when adding change we don't modify "outputs" base_tx = PartialTransaction.from_io(inputs[:], outputs[:]) input_value = base_tx.input_value() # Weight of the transaction with no inputs and no change # Note: this will use legacy tx serialization as the need for "segwit" # would be detected from inputs. The only side effect should be that the # marker and flag are excluded, which is compensated in get_tx_weight() # FIXME calculation will be off by this (2 wu) in case of RBF batching base_weight = base_tx.estimated_weight() spent_amount = base_tx.output_value() def fee_estimator_w(weight): return fee_estimator_vb(Transaction.virtual_size_from_weight(weight)) def sufficient_funds(buckets, *, bucket_value_sum): '''Given a list of buckets, return True if it has enough value to pay for the transaction''' # assert bucket_value_sum == sum(bucket.value for bucket in buckets) # expensive! total_input = input_value + bucket_value_sum if total_input < spent_amount: # shortcut for performance return False # note re performance: so far this was constant time # what follows is linear in len(buckets) total_weight = self._get_tx_weight(buckets, base_weight=base_weight) return total_input >= spent_amount + fee_estimator_w(total_weight) def tx_from_buckets(buckets): return self._construct_tx_from_selected_buckets(buckets=buckets, base_tx=base_tx, change_addrs=change_addrs, fee_estimator_w=fee_estimator_w, dust_threshold=dust_threshold, base_weight=base_weight) # Collect the coins into buckets all_buckets = self.bucketize_coins(coins, fee_estimator_vb=fee_estimator_vb) # Filter some buckets out. Only keep those that have positive effective value. # Note that this filtering is intentionally done on the bucket level # instead of per-coin, as each bucket should be either fully spent or not at all. # (e.g. CoinChooserPrivacy ensures that same-address coins go into one bucket) all_buckets = list(filter(lambda b: b.effective_value > 0, all_buckets)) # Choose a subset of the buckets scored_candidate = self.choose_buckets(all_buckets, sufficient_funds, self.penalty_func(base_tx, tx_from_buckets=tx_from_buckets)) tx = scored_candidate.tx self.logger.info(f"using {len(tx.inputs())} inputs") self.logger.info(f"using buckets: {[bucket.desc for bucket in scored_candidate.buckets]}") return tx def choose_buckets(self, buckets: List[Bucket], sufficient_funds: Callable, penalty_func: Callable[[List[Bucket]], ScoredCandidate]) -> ScoredCandidate: raise NotImplemented('To be subclassed') class CoinChooserRandom(CoinChooserBase): def bucket_candidates_any(self, buckets: List[Bucket], sufficient_funds) -> List[List[Bucket]]: '''Returns a list of bucket sets.''' if not buckets: if sufficient_funds([], bucket_value_sum=0): return [[]] else: raise NotEnoughFunds() candidates = set() # Add all singletons for n, bucket in enumerate(buckets): if sufficient_funds([bucket], bucket_value_sum=bucket.value): candidates.add((n,)) # And now some random ones attempts = min(100, (len(buckets) - 1) * 10 + 1) permutation = list(range(len(buckets))) for i in range(attempts): # Get a random permutation of the buckets, and # incrementally combine buckets until sufficient self.p.shuffle(permutation) bkts = [] bucket_value_sum = 0 for count, index in enumerate(permutation): bucket = buckets[index] bkts.append(bucket) bucket_value_sum += bucket.value if sufficient_funds(bkts, bucket_value_sum=bucket_value_sum): candidates.add(tuple(sorted(permutation[:count + 1]))) break else: # note: this assumes that the effective value of any bkt is >= 0 raise NotEnoughFunds() candidates = [[buckets[n] for n in c] for c in candidates] return [strip_unneeded(c, sufficient_funds) for c in candidates] def bucket_candidates_prefer_confirmed(self, buckets: List[Bucket], sufficient_funds) -> List[List[Bucket]]: """Returns a list of bucket sets preferring confirmed coins. Any bucket can be: 1. "confirmed" if it only contains confirmed coins; else 2. "unconfirmed" if it does not contain coins with unconfirmed parents 3. other: e.g. "unconfirmed parent" or "local" This method tries to only use buckets of type 1, and if the coins there are not enough, tries to use the next type but while also selecting all buckets of all previous types. """ conf_buckets = [bkt for bkt in buckets if bkt.min_height > 0] unconf_buckets = [bkt for bkt in buckets if bkt.min_height == 0] other_buckets = [bkt for bkt in buckets if bkt.min_height < 0] bucket_sets = [conf_buckets, unconf_buckets, other_buckets] already_selected_buckets = [] already_selected_buckets_value_sum = 0 for bkts_choose_from in bucket_sets: try: def sfunds(bkts, *, bucket_value_sum): bucket_value_sum += already_selected_buckets_value_sum return sufficient_funds(already_selected_buckets + bkts, bucket_value_sum=bucket_value_sum) candidates = self.bucket_candidates_any(bkts_choose_from, sfunds) break except NotEnoughFunds: already_selected_buckets += bkts_choose_from already_selected_buckets_value_sum += sum(bucket.value for bucket in bkts_choose_from) else: raise NotEnoughFunds() candidates = [(already_selected_buckets + c) for c in candidates] return [strip_unneeded(c, sufficient_funds) for c in candidates] def choose_buckets(self, buckets, sufficient_funds, penalty_func): candidates = self.bucket_candidates_prefer_confirmed(buckets, sufficient_funds) scored_candidates = [penalty_func(cand) for cand in candidates] winner = min(scored_candidates, key=lambda x: x.penalty) self.logger.info(f"Total number of buckets: {len(buckets)}") self.logger.info(f"Num candidates considered: {len(candidates)}. " f"Winning penalty: {winner.penalty}") return winner class CoinChooserPrivacy(CoinChooserRandom): """Attempts to better preserve user privacy. First, if any coin is spent from a user address, all coins are. Compared to spending from other addresses to make up an amount, this reduces information leakage about sender holdings. It also helps to reduce blockchain UTXO bloat, and reduce future privacy loss that would come from reusing that address' remaining UTXOs. Second, it penalizes change that is quite different to the sent amount. Third, it penalizes change that is too big. """ def keys(self, coins): return [coin.scriptpubkey.hex() for coin in coins] def penalty_func(self, base_tx, *, tx_from_buckets): min_change = min(o.value for o in base_tx.outputs()) * 0.75 max_change = max(o.value for o in base_tx.outputs()) * 1.33 def penalty(buckets: List[Bucket]) -> ScoredCandidate: # Penalize using many buckets (~inputs) badness = len(buckets) - 1 tx, change_outputs = tx_from_buckets(buckets) change = sum(o.value for o in change_outputs) # Penalize change not roughly in output range if change == 0: pass # no change is great! elif change < min_change: badness += (min_change - change) / (min_change + 10000) # Penalize really small change; under 1 mBTC ~= using 1 more input if change < COIN / 1000: badness += 1 elif change > max_change: badness += (change - max_change) / (max_change + 10000) # Penalize large change; 5 BTC excess ~= using 1 more input badness += change / (COIN * 5) return ScoredCandidate(badness, tx, buckets) return penalty COIN_CHOOSERS = { 'Privacy': CoinChooserPrivacy, } def get_name(config): kind = config.get('coin_chooser') if not kind in COIN_CHOOSERS: kind = 'Privacy' return kind def get_coin_chooser(config): klass = COIN_CHOOSERS[get_name(config)] # note: we enable enable_output_value_rounding by default as # - for sacrificing a few satoshis # + it gives better privacy for the user re change output # + it also helps the network as a whole as fees will become noisier # (trying to counter the heuristic that "whole integer sat/byte feerates" are common) coinchooser = klass( enable_output_value_rounding=config.get('coin_chooser_output_rounding', True), ) return coinchooser
class Solution: def XXX(self, nums: List[int]) -> bool: pos=len(nums)-1 while pos>0: pre=pos-1 while pre>=0: if nums[pre]+pre>=pos: pos=pre break else: pre-=1 if pre<0: return False return pos<=0
import React from "react"; import "./styles/App.css"; import firebase from "firebase/app"; import "firebase/firestore"; import "firebase/auth"; import { useAuthState } from "react-firebase-hooks/auth"; import ChatRoom from "./components/ChatRoom"; import SignIn from "./components/SignIn"; import SignOut from "./components/SignOut"; firebase.initializeApp({ // Go to projectConsole --> project Setting -->add web app --> copy all the config // apiKey: "", // Insert Your key Here // authDomain: "", // Insert Your authDomain Here // databaseURL: "", // Insert Your databaseURL Here // projectId: "", // Insert Your projectId Here // storageBucket: "", // Insert Your storageBucket Here // messagingSenderId: "", // Insert Your messagingSenderId Here // appId: "", // Insert Your appId Here // measurementId: "", // Insert Your measurementId Here }); const auth = firebase.auth(); // const [user] = useAuthState(auth); function App() { const [user] = useAuthState(auth); return ( <div className="App"> <header> <h1> <span role="img" aria-label="message"> Community Chat App 💬 </span> </h1> <SignOut /> </header> <section>{user ? <ChatRoom /> : <SignIn />}</section> </div> ); } export default App;
// This is a convenience wrapper for reading and writing files in the 'refs' directory. import { InvalidOidError } from '../errors/InvalidOidError.js' import { NoRefspecError } from '../errors/NoRefspecError.js' import { NotFoundError } from '../errors/NotFoundError.js' import { GitPackedRefs } from '../models/GitPackedRefs.js' import { GitRefSpecSet } from '../models/GitRefSpecSet.js' import { compareRefNames } from '../utils/compareRefNames.js' import { join } from '../utils/join.js' import { GitConfigManager } from './GitConfigManager' // @see https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions const refpaths = (ref) => [ `${ref}`, `refs/${ref}`, `refs/tags/${ref}`, `refs/heads/${ref}`, `refs/remotes/${ref}`, `refs/remotes/${ref}/HEAD`, ] // @see https://git-scm.com/docs/gitrepository-layout const GIT_FILES = ['config', 'description', 'index', 'shallow', 'commondir'] export class GitRefManager { static async updateRemoteRefs({ fs, gitdir, remote, refs, symrefs, tags, refspecs = undefined, prune = false, pruneTags = false, }) { // Validate input for (const value of refs.values()) { if (!value.match(/[0-9a-f]{40}/)) { throw new InvalidOidError(value) } } const config = await GitConfigManager.get({ fs, gitdir }) if (!refspecs) { refspecs = await config.getall(`remote.${remote}.fetch`) if (refspecs.length === 0) { throw new NoRefspecError(remote) } // There's some interesting behavior with HEAD that doesn't follow the refspec. refspecs.unshift(`+HEAD:refs/remotes/${remote}/HEAD`) } const refspec = GitRefSpecSet.from(refspecs) const actualRefsToWrite = new Map() // Delete all current tags if the pruneTags argument is true. if (pruneTags) { const tags = await GitRefManager.listRefs({ fs, gitdir, filepath: 'refs/tags', }) await GitRefManager.deleteRefs({ fs, gitdir, refs: tags.map((tag) => `refs/tags/${tag}`), }) } // Add all tags if the fetch tags argument is true. if (tags) { for (const serverRef of refs.keys()) { if (serverRef.startsWith('refs/tags') && !serverRef.endsWith('^{}')) { // Git's behavior is to only fetch tags that do not conflict with tags already present. if (!(await GitRefManager.exists({ fs, gitdir, ref: serverRef }))) { // If there is a dereferenced an annotated tag value available, prefer that. const oid = refs.get(serverRef + '^{}') || refs.get(serverRef) actualRefsToWrite.set(serverRef, oid) } } } } // Combine refs and symrefs giving symrefs priority const refTranslations = refspec.translate([...refs.keys()]) for (const [serverRef, translatedRef] of refTranslations) { const value = refs.get(serverRef) actualRefsToWrite.set(translatedRef, value) } const symrefTranslations = refspec.translate([...symrefs.keys()]) for (const [serverRef, translatedRef] of symrefTranslations) { const value = symrefs.get(serverRef) const symtarget = refspec.translateOne(value) if (symtarget) { actualRefsToWrite.set(translatedRef, `ref: ${symtarget}`) } } // If `prune` argument is true, clear out the existing local refspec roots const pruned = [] if (prune) { for (const filepath of refspec.localNamespaces()) { const refs = ( await GitRefManager.listRefs({ fs, gitdir, filepath, }) ).map((file) => `${filepath}/${file}`) for (const ref of refs) { if (!actualRefsToWrite.has(ref)) { pruned.push(ref) } } } if (pruned.length > 0) { await GitRefManager.deleteRefs({ fs, gitdir, refs: pruned }) } } // Update files // TODO: For large repos with a history of thousands of pull requests // (i.e. gitlab-ce) it would be vastly more efficient to write them // to .git/packed-refs. // The trick is to make sure we a) don't write a packed ref that is // already shadowed by a loose ref and b) don't loose any refs already // in packed-refs. Doing this efficiently may be difficult. A // solution that might work is // a) load the current packed-refs file // b) add actualRefsToWrite, overriding the existing values if present // c) enumerate all the loose refs currently in .git/refs/remotes/${remote} // d) overwrite their value with the new value. // Examples of refs we need to avoid writing in loose format for efficieny's sake // are .git/refs/remotes/origin/refs/remotes/remote_mirror_3059 // and .git/refs/remotes/origin/refs/merge-requests for (const [key, value] of actualRefsToWrite) { await fs.write(join(gitdir, key), `${value.trim()}\n`, 'utf8') } return { pruned } } // TODO: make this less crude? static async writeRef({ fs, gitdir, ref, value }) { // Validate input if (!value.match(/[0-9a-f]{40}/)) { throw new InvalidOidError(value) } await fs.write(join(gitdir, ref), `${value.trim()}\n`, 'utf8') } static async writeSymbolicRef({ fs, gitdir, ref, value }) { await fs.write(join(gitdir, ref), 'ref: ' + `${value.trim()}\n`, 'utf8') } static async deleteRef({ fs, gitdir, ref }) { return GitRefManager.deleteRefs({ fs, gitdir, refs: [ref] }) } static async deleteRefs({ fs, gitdir, refs }) { // Delete regular ref await Promise.all(refs.map((ref) => fs.rm(join(gitdir, ref)))) // Delete any packed ref let text = await fs.read(`${gitdir}/packed-refs`, { encoding: 'utf8' }) const packed = GitPackedRefs.from(text) const beforeSize = packed.refs.size for (const ref of refs) { if (packed.refs.has(ref)) { packed.delete(ref) } } if (packed.refs.size < beforeSize) { text = packed.toString() await fs.write(`${gitdir}/packed-refs`, text, { encoding: 'utf8' }) } } /** * @param {object} args * @param {import('../models/FileSystem.js').FileSystem} args.fs * @param {string} args.gitdir * @param {string} args.ref * @param {number} [args.depth] * @returns {Promise<string>} */ static async resolve({ fs, gitdir, ref, depth = undefined }) { if (depth !== undefined) { depth-- if (depth === -1) { return ref } } let sha // Is it a ref pointer? if (ref.startsWith('ref: ')) { ref = ref.slice('ref: '.length) return GitRefManager.resolve({ fs, gitdir, ref, depth }) } // Is it a complete and valid SHA? if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { return ref } // We need to alternate between the file system and the packed-refs const packedMap = await GitRefManager.packedRefs({ fs, gitdir }) // Look in all the proper paths, in this order const allpaths = refpaths(ref).filter((p) => !GIT_FILES.includes(p)) // exclude git system files (#709) for (const ref of allpaths) { sha = (await fs.read(`${gitdir}/${ref}`, { encoding: 'utf8' })) || packedMap.get(ref) if (sha) { return GitRefManager.resolve({ fs, gitdir, ref: sha.trim(), depth }) } } // Do we give up? throw new NotFoundError(ref) } static async exists({ fs, gitdir, ref }) { try { await GitRefManager.expand({ fs, gitdir, ref }) return true } catch (err) { return false } } static async expand({ fs, gitdir, ref }) { // Is it a complete and valid SHA? if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { return ref } // We need to alternate between the file system and the packed-refs const packedMap = await GitRefManager.packedRefs({ fs, gitdir }) // Look in all the proper paths, in this order const allpaths = refpaths(ref) for (const ref of allpaths) { if (await fs.exists(`${gitdir}/${ref}`)) return ref if (packedMap.has(ref)) return ref } // Do we give up? throw new NotFoundError(ref) } static async expandAgainstMap({ ref, map }) { // Look in all the proper paths, in this order const allpaths = refpaths(ref) for (const ref of allpaths) { if (await map.has(ref)) return ref } // Do we give up? throw new NotFoundError(ref) } static resolveAgainstMap({ ref, fullref = ref, depth = undefined, map }) { if (depth !== undefined) { depth-- if (depth === -1) { return { fullref, oid: ref } } } // Is it a ref pointer? if (ref.startsWith('ref: ')) { ref = ref.slice('ref: '.length) return GitRefManager.resolveAgainstMap({ ref, fullref, depth, map }) } // Is it a complete and valid SHA? if (ref.length === 40 && /[0-9a-f]{40}/.test(ref)) { return { fullref, oid: ref } } // Look in all the proper paths, in this order const allpaths = refpaths(ref) for (const ref of allpaths) { const sha = map.get(ref) if (sha) { return GitRefManager.resolveAgainstMap({ ref: sha.trim(), fullref: ref, depth, map, }) } } // Do we give up? throw new NotFoundError(ref) } static async packedRefs({ fs, gitdir }) { const text = await fs.read(`${gitdir}/packed-refs`, { encoding: 'utf8' }) const packed = GitPackedRefs.from(text) return packed.refs } // List all the refs that match the `filepath` prefix static async listRefs({ fs, gitdir, filepath }) { const packedMap = GitRefManager.packedRefs({ fs, gitdir }) let files = null try { files = await fs.readdirDeep(`${gitdir}/${filepath}`) files = files.map((x) => x.replace(`${gitdir}/${filepath}/`, '')) } catch (err) { files = [] } for (let key of (await packedMap).keys()) { // filter by prefix if (key.startsWith(filepath)) { // remove prefix key = key.replace(filepath + '/', '') // Don't include duplicates; the loose files have precedence anyway if (!files.includes(key)) { files.push(key) } } } // since we just appended things onto an array, we need to sort them now files.sort(compareRefNames) return files } static async listBranches({ fs, gitdir, remote }) { if (remote) { return GitRefManager.listRefs({ fs, gitdir, filepath: `refs/remotes/${remote}`, }) } else { return GitRefManager.listRefs({ fs, gitdir, filepath: `refs/heads` }) } } static async listTags({ fs, gitdir }) { const tags = await GitRefManager.listRefs({ fs, gitdir, filepath: `refs/tags`, }) return tags.filter((x) => !x.endsWith('^{}')) } }
var tape = require("tape"), topojson = require("../"); tape("merge ignores null geometries", function(test) { var topology = { "type": "Topology", "objects": {}, "arcs": [] }; test.deepEqual(topojson.merge(topology, [{type: null}]), { type: "MultiPolygon", coordinates: [] }); test.end(); }); // // +----+----+ +----+----+ // | | | | | // | | | ==> | | // | | | | | // +----+----+ +----+----+ // tape("merge stitches together two side-by-side polygons", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0, 1]]}, {"type": "Polygon", "arcs": [[-1, 2]]} ] } }, "arcs": [ [[1, 1], [1, 0]], [[1, 0], [0, 0], [0, 1], [1, 1]], [[1, 1], [2, 1], [2, 0], [1, 0]] ] }; test.deepEqual(topojson.merge(topology, topology.objects.collection.geometries), { type: "MultiPolygon", coordinates: [[[[1, 0], [0, 0], [0, 1], [1, 1], [2, 1], [2, 0], [1, 0]]]] }); test.end(); }); // // +----+----+ +----+----+ // | | | | | // | | | ==> | | // | | | | | // +----+----+ +----+----+ // tape("merge stitches together geometry collections", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0, 1]]}, {"type": "Polygon", "arcs": [[-1, 2]]} ] } }, "arcs": [ [[1, 1], [1, 0]], [[1, 0], [0, 0], [0, 1], [1, 1]], [[1, 1], [2, 1], [2, 0], [1, 0]] ] }; test.deepEqual(topojson.merge(topology, [topology.objects.collection]), { type: "MultiPolygon", coordinates: [[[[1, 0], [0, 0], [0, 1], [1, 1], [2, 1], [2, 0], [1, 0]]]] }); test.end(); }); // // +----+ +----+ +----+ +----+ // | | | | | | | | // | | | | ==> | | | | // | | | | | | | | // +----+ +----+ +----+ +----+ // tape("merge does not stitch together two separated polygons", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0]]}, {"type": "Polygon", "arcs": [[1]]} ] } }, "arcs": [ [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]], [[2, 0], [2, 1], [3, 1], [3, 0], [2, 0]] ] }; test.deepEqual(topojson.merge(topology, topology.objects.collection.geometries), { type: "MultiPolygon", coordinates: [[[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]], [[[2, 0], [2, 1], [3, 1], [3, 0], [2, 0]]]] }); test.end(); }); // // +-----------+ +-----------+ // | | | | // | +---+ | ==> | +---+ | // | | | | | | | | // | +---+ | | +---+ | // | | | | // +-----------+ +-----------+ // tape("merge does not stitch together a polygon and its hole", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0], [1]]} ] } }, "arcs": [ [[0, 0], [0, 3], [3, 3], [3, 0], [0, 0]], [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]] ] }; test.deepEqual(topojson.merge(topology, topology.objects.collection.geometries), { type: "MultiPolygon", coordinates: [[[[0, 0], [0, 3], [3, 3], [3, 0], [0, 0]], [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]]]] }); test.end(); }); // // +-----------+ +-----------+ // | | | | // | +---+ | ==> | | // | | | | | | // | +---+ | | | // | | | | // +-----------+ +-----------+ // tape("merge stitches together a polygon surrounding another polygon", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0], [1]]}, {"type": "Polygon", "arcs": [[-2]]} ] } }, "arcs": [ [[0, 0], [0, 3], [3, 3], [3, 0], [0, 0]], [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]] ] }; test.deepEqual(topojson.merge(topology, topology.objects.collection.geometries), { type: "MultiPolygon", coordinates: [[[[0, 0], [0, 3], [3, 3], [3, 0], [0, 0]]]] }); test.end(); }); // // +-----------+-----------+ +-----------+-----------+ // | | | | | // | +---+ | +---+ | ==> | +---+ +---+ | // | | | | | | | | | | | | | // | +---+ | +---+ | | +---+ +---+ | // | | | | | // +-----------+-----------+ +-----------+-----------+ // tape("merge stitches together two side-by-side polygons with holes", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0, 1], [2]]}, {"type": "Polygon", "arcs": [[-1, 3], [4]]} ] } }, "arcs": [ [[3, 3], [3, 0]], [[3, 0], [0, 0], [0, 3], [3, 3]], [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]], [[3, 3], [6, 3], [6, 0], [3, 0]], [[4, 1], [5, 1], [5, 2], [4, 2], [4, 1]] ] }; test.deepEqual(topojson.merge(topology, topology.objects.collection.geometries), { type: "MultiPolygon", coordinates: [[[[3, 0], [0, 0], [0, 3], [3, 3], [6, 3], [6, 0], [3, 0]], [[1, 1], [2, 1], [2, 2], [1, 2], [1, 1]], [[4, 1], [5, 1], [5, 2], [4, 2], [4, 1]]]] }); test.end(); }); // // +-------+-------+ +-------+-------+ // | | | | | // | +---+---+ | ==> | +---+---+ | // | | | | | | | | // | +---+---+ | | +---+---+ | // | | | | | // +-------+-------+ +-------+-------+ // tape("merge stitches together two horseshoe polygons, creating a hole", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0, 1, 2, 3]]}, {"type": "Polygon", "arcs": [[-3, 4, -1, 5]]} ] } }, "arcs": [ [[2, 3], [2, 2]], [[2, 2], [1, 2], [1, 1], [2, 1]], [[2, 1], [2, 0]], [[2, 0], [0, 0], [0, 3], [2, 3]], [[2, 1], [3, 1], [3, 2], [2, 2]], [[2, 3], [4, 3], [4, 0], [2, 0]] ] }; test.deepEqual(topojson.merge(topology, topology.objects.collection.geometries), { type: "MultiPolygon", coordinates: [[[[2, 0], [0, 0], [0, 3], [2, 3], [4, 3], [4, 0], [2, 0]], [[2, 2], [1, 2], [1, 1], [2, 1], [3, 1], [3, 2], [2, 2]]]] }); test.end(); }); // // +-------+-------+ +-------+-------+ // | | | | | // | +---+---+ | ==> | | // | | | | | | | // | +---+---+ | | | // | | | | | // +-------+-------+ +-------+-------+ // tape("merge stitches together two horseshoe polygons surrounding two other polygons", function(test) { var topology = { "type": "Topology", "objects": { "collection": { "type": "GeometryCollection", "geometries": [ {"type": "Polygon", "arcs": [[0, 1, 2, 3]]}, {"type": "Polygon", "arcs": [[-3, 4, -1, 5]]}, {"type": "Polygon", "arcs": [[6, -2]]}, {"type": "Polygon", "arcs": [[-7, -5]]} ] } }, "arcs": [ [[2, 3], [2, 2]], [[2, 2], [1, 2], [1, 1], [2, 1]], [[2, 1], [2, 0]], [[2, 0], [0, 0], [0, 3], [2, 3]], [[2, 1], [3, 1], [3, 2], [2, 2]], [[2, 3], [4, 3], [4, 0], [2, 0]], [[2, 2], [2, 1]] ] }; test.deepEqual(topojson.merge(topology, topology.objects.collection.geometries), { type: "MultiPolygon", coordinates: [[[[2, 0], [0, 0], [0, 3], [2, 3], [4, 3], [4, 0], [2, 0]]]] }); test.end(); });
import $ from "../constructor"; $.prototype.first = function() { return this.get(0) || null; };
const { AuthenticationError } = require("apollo-server-express"); const { MusicianUser, Venue } = require("../models"); const { tokenise } = require("../utils/tokenise"); const login = async (_, { input }) => { const { email, password } = input; const musicianUser = await MusicianUser.findOne({ email }); if (!musicianUser) { const venueUser = await Venue.findOne({ email }); if (!venueUser) { throw new AuthenticationError("User does not exist"); } const isValidPassword = await venueUser.validatePassword(password); if (!isValidPassword) { throw new AuthenticationError("Incorrect email or password"); } const token = tokenise({ id: venueUser.id, email: venueUser.email }); return { token, user: venueUser, type: "venue" }; } const isValidPassword = await musicianUser.validatePassword(password); if (!isValidPassword) { throw new AuthenticationError("Incorrect email or password"); } const token = tokenise({ id: musicianUser.id, email: musicianUser.email }); return { token, user: musicianUser, type: "musician" }; }; module.exports = login;
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from 'src/redux/reducers'; import { persistStore, persistReducer } from 'redux-persist' import storage from 'redux-persist/lib/storage' // defaults to localStorage for web const persistConfig = { key: 'root', storage, } const persistedReducer = persistReducer(persistConfig, rootReducer) export const store = createStore(persistedReducer, applyMiddleware(thunk)); export const persistor = persistStore(store)
""" Copyright 2013 Steven Diamond 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. """ from .boolean import Boolean import cvxopt import numpy as np from itertools import product class Choose(Boolean): """ A variable with k 1's and all other entries 0. """ def __init__(self, rows: int = 1, cols: int = 1, k=None, *args, **kwargs) -> None: self.k = k super(Choose, self).__init__(rows, cols, *args, **kwargs) # Sets the initial z value to the expected value of each entry. def init_z(self): num_entries = float(self.size[0]*self.size[1]) self.z.value = cvxopt.matrix(num_entries/self.k, self.size, tc='d') # The k-largest values are set to 1. The remainder are set to 0. def _round(self, matrix): indices = product(range(self.size[0]), range(self.size[1])) v_ind = sorted(indices, key=lambda ind: -matrix[ind]) for ind in v_ind[0:self.k]: matrix[ind] = 1 for ind in v_ind[self.k:]: matrix[ind] = 0 return matrix
/** * @license * Copyright (c) 2018 amCharts (Antanas Marcelionis, Martynas Majeris) * * This sofware is provided under multiple licenses. Please see below for * links to appropriate usage. * * Free amCharts linkware license. Details and conditions: * https://github.com/amcharts/amcharts4/blob/master/LICENSE * * One of the amCharts commercial licenses. Details and pricing: * https://www.amcharts.com/online-store/ * https://www.amcharts.com/online-store/licenses-explained/ * * If in doubt, contact amCharts at contact@amcharts.com * * PLEASE DO NOT REMOVE THIS COPYRIGHT NOTICE. * @hidden */ am4internal_webpackJsonp(["a3a5"],{"2ghO":function(e,t,a){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o={type:"FeatureCollection",features:[{type:"Feature",geometry:{type:"Polygon",coordinates:[[[-76.932,38.91],[-76.91,38.893],[-76.992,38.829],[-77.02,38.813],[-77.026,38.827],[-77.022,38.871],[-77.057,38.901],[-77.093,38.907],[-77.121,38.934],[-77.041,38.995],[-76.932,38.91]]]},properties:{name:"Washington, District of Columbia",id:"11001",STATE:"DC",TYPE:"Federal District",CNTRY:"USA"},id:"11001"}]};window.am4geodata_region_usa_dcLow=o}},["2ghO"]); //# sourceMappingURL=dcLow.js.map
import { combineReducers } from 'redux' let defaultConfig = { hueIP: '192.168.0.18', hueUser: 'gDiIztNg3YZOQF3ASNLHlrDj7SppTwLT-12-C-cs' } defaultConfig["apiUrl"] = `http://${defaultConfig.hueIP}/api/${defaultConfig.hueUser}`; function config (state = defaultConfig, action) { switch (action.type) { case 'UPDATE_CONFIG': return action.order default: return state } } const rootReducer = combineReducers({ config }) export default rootReducer
//>>built define("dojox/sketch/Figure","dojo/_base/kernel dojo/_base/lang dojo/_base/connect dojo/_base/html ../gfx ../xml/DomParser ./UndoStack".split(" "),function(d){d.experimental("dojox.sketch");var e=dojox.sketch;e.tools={};e.registerTool=function(a,b){e.tools[a]=b};e.Figure=function(a){var b=this;this.annCounter=1;this.shapes=[];this.imageSrc=this.image=null;this.size={w:0,h:0};this.node=this.group=this.surface=null;this.zoomFactor=1;this.tools=null;this.obj={};d.mixin(this,a);this.selected=[];this.hasSelections= function(){return 0<this.selected.length};this.isSelected=function(a){for(var f=0;f<b.selected.length;f++)if(b.selected[f]==a)return!0;return!1};this.select=function(a){b.isSelected(a)||(b.clearSelections(),b.selected=[a]);a.setMode(e.Annotation.Modes.View);a.setMode(e.Annotation.Modes.Edit)};this.deselect=function(a){for(var f=-1,c=0;c<b.selected.length;c++)if(b.selected[c]==a){f=c;break}-1<f&&(a.setMode(e.Annotation.Modes.View),b.selected.splice(f,1));return a};this.clearSelections=function(){for(var a= 0;a<b.selected.length;a++)b.selected[a].setMode(e.Annotation.Modes.View);b.selected=[]};this.replaceSelection=function(a,f){if(b.isSelected(f)){for(var c=-1,d=0;d<b.selected.length;d++)if(b.selected[d]==f){c=d;break}-1<c&&b.selected.splice(c,1,a)}else b.select(a)};this._cshape=this._absEnd=this._end=this._start=this._ctool=this._startPoint=this._prevState=this._action=this._lp=this._ctr=this._c=null;this._dblclick=function(a){var c=b._fromEvt(a);if(c)b.onDblClickShape(c,a)};this._keydown=function(a){var c= !1;if(a.ctrlKey)if(90===a.keyCode||122===a.keyCode)b.undo(),c=!0;else if(89===a.keyCode||121===a.keyCode)b.redo(),c=!0;if(46===a.keyCode||8===a.keyCode)b._delete(b.selected),c=!0;c&&d.stopEvent(a)};this._md=function(a){"vml"==dojox.gfx.renderer&&b.node.focus();var c=b._fromEvt(a);b._startPoint={x:a.pageX,y:a.pageY};b._ctr=d.position(b.node);b._ctr={x:b._ctr.x-b.node.scrollLeft,y:b._ctr.y-b.node.scrollTop};var e=a.clientX-b._ctr.x,k=a.clientY-b._ctr.y;b._lp={x:e,y:k};b._start={x:e,y:k};b._end={x:e, y:k};b._absEnd={x:e,y:k};c?(c.type&&"Anchor"!=c.type()&&(b.isSelected(c)?b._sameShapeSelected=!0:(b.select(c),b._sameShapeSelected=!1)),c.beginEdit(),b._c=c):(b.clearSelections(),b._ctool.onMouseDown(a))};this._mm=function(a){if(b._ctr)if(b._c&&!b._c.shape)b._clearMouse();else{var c=a.clientX-b._ctr.x,d=a.clientY-b._ctr.y,e=c-b._lp.x,m=d-b._lp.y;b._absEnd={x:c,y:d};if(b._c)b._c.setBinding({dx:e/b.zoomFactor,dy:m/b.zoomFactor}),b._lp={x:c,y:d};else if(b._end={x:e,y:m},c={x:Math.min(b._start.x,b._absEnd.x), y:Math.min(b._start.y,b._absEnd.y),width:Math.abs(b._start.x-b._absEnd.x),height:Math.abs(b._start.y-b._absEnd.y)},c.width&&c.height)b._ctool.onMouseMove(a,c)}};this._mu=function(a){if(b._c)b._c.shape&&b._c.endEdit();else b._ctool.onMouseUp(a);b._clearMouse()};this._clearMouse=function(){b._c=b._ctr=b._lp=b._action=b._prevState=b._startPoint=null;b._cshape=b._start=b._end=b._absEnd=null};this.initUndoStack()};var c=e.Figure.prototype;c.initUndoStack=function(){this.history=new e.UndoStack(this)}; c.setTool=function(a){this._ctool=a};c.gridSize=0;c._calCol=function(a){return this.gridSize?Math.round(a/this.gridSize)*this.gridSize:a};c._delete=function(a,b){for(var c=0;c<a.length;c++)if(a[c].setMode(e.Annotation.Modes.View),a[c].destroy(b),this.remove(a[c]),this._remove(a[c]),!b)a[c].onRemove();a.splice(0,a.length)};c.onDblClickShape=function(a,b){if(a.onDblClick)a.onDblClick(b)};c.onCreateShape=function(a){};c.onBeforeCreateShape=function(a){};c.initialize=function(a){this.node=a;this.surface= dojox.gfx.createSurface(a,this.size.w,this.size.h);this.group=this.surface.createGroup();this._cons=[];var b=this.surface.getEventSource();this._cons.push(d.connect(b,"ondraggesture",d.stopEvent),d.connect(b,"ondragenter",d.stopEvent),d.connect(b,"ondragover",d.stopEvent),d.connect(b,"ondragexit",d.stopEvent),d.connect(b,"ondragstart",d.stopEvent),d.connect(b,"onselectstart",d.stopEvent),d.connect(b,"onmousedown",this._md),d.connect(b,"onmousemove",this._mm),d.connect(b,"onmouseup",this._mu),d.connect(b, "onclick",this,"onClick"),d.connect(b,"ondblclick",this._dblclick),d.connect(a,"onkeydown",this._keydown));this.image=this.group.createImage({width:this.imageSize.w,height:this.imageSize.h,src:this.imageSrc})};c.destroy=function(a){this.node&&(a||(this.history&&this.history.destroy(),this._subscribed&&(d.unsubscribe(this._subscribed),delete this._subscribed)),d.forEach(this._cons,d.disconnect),this._cons=[],d.empty(this.node),this.group=this.surface=null,this.obj={},this.shapes=[])};c.nextKey=function(){return"annotation-"+ this.annCounter++};c.draw=function(){};c.zoom=function(a){this.zoomFactor=a/100;this.surface.setDimensions(this.size.w*this.zoomFactor,this.size.h*this.zoomFactor);this.group.setTransform(dojox.gfx.matrix.scale(this.zoomFactor,this.zoomFactor));for(a=0;a<this.shapes.length;a++)this.shapes[a].zoom(this.zoomFactor)};c.getFit=function(){return 100*Math.min((this.node.parentNode.offsetWidth-5)/this.size.w,(this.node.parentNode.offsetHeight-5)/this.size.h)};c.unzoom=function(){this.zoomFactor=1;this.surface.setDimensions(this.size.w, this.size.h);this.group.setTransform()};c._add=function(a){this.obj[a._key]=a};c._remove=function(a){this.obj[a._key]&&delete this.obj[a._key]};c._get=function(a){a&&-1<a.indexOf("bounding")?a=a.replace("-boundingBox",""):a&&-1<a.indexOf("-labelShape")&&(a=a.replace("-labelShape",""));return this.obj[a]};c._keyFromEvt=function(a){var b=a.target.id+"";if(0==b.length){a=a.target.parentNode;for(b=this.surface.getEventSource();a&&0==a.id.length&&a!=b;)a=a.parentNode;b=a.id}return b};c._fromEvt=function(a){return this._get(this._keyFromEvt(a))}; c.add=function(a){for(var b=0;b<this.shapes.length;b++)if(this.shapes[b]==a)return!0;this.shapes.push(a);return!0};c.remove=function(a){for(var b=-1,c=0;c<this.shapes.length;c++)if(this.shapes[c]==a){b=c;break}-1<b&&this.shapes.splice(b,1);return a};c.getAnnotator=function(a){for(var b=0;b<this.shapes.length;b++)if(this.shapes[b].id==a)return this.shapes[b];return null};c.convert=function(a,b){var c=b+"Annotation";if(e[c]){var f=a.type(),p=a.id,k=a.label,m=a.mode,g,h,n,l;switch(f){case "Preexisting":case "Lead":l= {dx:a.transform.dx,dy:a.transform.dy};g={x:a.start.x,y:a.start.y};h={x:a.end.x,y:a.end.y};n={x:h.x-(h.x-g.x)/2,y:h.y-(h.y-g.y)/2};break;case "SingleArrow":case "DoubleArrow":l={dx:a.transform.dx,dy:a.transform.dy};g={x:a.start.x,y:a.start.y};h={x:a.end.x,y:a.end.y};n={x:a.control.x,y:a.control.y};break;case "Underline":l={dx:a.transform.dx,dy:a.transform.dy},g={x:a.start.x,y:a.start.y},n={x:g.x+50,y:g.y+50},h={x:g.x+100,y:g.y+100}}c=new e[c](this,p);"Underline"==c.type()?c.transform={dx:l.dx+g.x, dy:l.dy+g.y}:(c.transform&&(c.transform=l),c.start&&(c.start=g));c.end&&(c.end=h);c.control&&(c.control=n);c.label=k;c.token=d.lang.shallowCopy(a.token);c.initialize();this.replaceSelection(c,a);this._remove(a);this.remove(a);a.destroy();c.setMode(m)}};c.setValue=function(a){a=dojox.xml.DomParser.parse(a);this.load(a,this.node)};c.load=function(a,b){this.surface&&this.destroy(!0);var c=a.documentElement;this.size={w:parseFloat(c.getAttribute("width"),10),h:parseFloat(c.getAttribute("height"),10)}; var c=c.childrenByName("g")[0],d=c.childrenByName("image")[0];this.imageSize={w:parseFloat(d.getAttribute("width"),10),h:parseFloat(d.getAttribute("height"),10)};this.imageSrc=d.getAttribute("xlink:href");this.initialize(b);c=c.childrenByName("g");for(d=0;d<c.length;d++)this._loadAnnotation(c[d]);this._loadDeferred&&(this._loadDeferred.callback(this),this._loadDeferred=null);this.onLoad()};c.onLoad=function(){};c.onClick=function(){};c._loadAnnotation=function(a){var b=a.getAttribute("dojoxsketch:type")+ "Annotation";return e[b]?(b=new e[b](this,a.id),b.initialize(a),this.nextKey(),b.setMode(e.Annotation.Modes.View),this._add(b),b):null};c.onUndo=function(){};c.onBeforeUndo=function(){};c.onRedo=function(){};c.onBeforeRedo=function(){};c.undo=function(){this.history&&(this.onBeforeUndo(),this.history.undo(),this.onUndo())};c.redo=function(){this.history&&(this.onBeforeRedo(),this.history.redo(),this.onRedo())};c.serialize=function(){for(var a='\x3csvg xmlns\x3d"http://www.w3.org/2000/svg" xmlns:xlink\x3d"http://www.w3.org/1999/xlink" xmlns:dojoxsketch\x3d"http://dojotoolkit.org/dojox/sketch" width\x3d"'+ this.size.w+'" height\x3d"'+this.size.h+'"\x3e\x3cg\x3e\x3cimage xlink:href\x3d"'+this.imageSrc+'" x\x3d"0" y\x3d"0" width\x3d"'+this.size.w+'" height\x3d"'+this.size.h+'" /\x3e',b=0;b<this.shapes.length;b++)a+=this.shapes[b].serialize();return a+"\x3c/g\x3e\x3c/svg\x3e"};c.getValue=c.serialize;return dojox.sketch.Figure}); //# sourceMappingURL=Figure.js.map
"use strict" const os = require(`os`) const fs = require(`fs-extra`) const { cli } = require(`@nodeguy/cli`) var path = require(`path`) const homeDir = require(`os`).homedir() const appDir = path.resolve(__dirname + `/../../../`) let { spawn, exec } = require(`child_process`) const optionsSpecification = { overwrite: [`overwrite ~/.gaiad-testnet/`, false], password: [`custom password, default is 12345678`, 12345678] } cli(optionsSpecification, async options => { const platform = os.platform() const environment = platform === `darwin` ? `darwin_amd64` : platform === `win32` ? `windows_amd64` : `linux_amd64` try { const secret = await init(options, environment) await moveFiles(options, environment) console.log(`\n 🎉 SUCCESS 🎉\n`) console.log( `To begin your local node please run: ./builds/Gaia/${environment}/gaiad start --home ~/.gaiad-testnet To begin Voyager please run: yarn start local-testnet Your secret is: ${secret} ` ) } catch (error) { console.log(`Encountered an Error:`) console.error(error.msg ? error : error.toString()) } }) function makeExec(command) { console.log(`$ ` + command) return new Promise((resolve, reject) => { exec(command, (err, stdout, stderr) => { if (err) return reject(err) if (stderr) return reject(stderr) resolve(stdout) }) }) } async function moveFiles(options, environment) { let out if ( options.overwrite && fs.existsSync(appDir + `/builds/testnets/local-testnet`) ) { out = await makeExec(`rm -r builds/testnets/local-testnet`) out && console.log(out) } out = await makeExec(`mkdir builds/testnets/local-testnet`) out && console.log(out) out = await makeExec( `cp ~/.gaiad-testnet/config/{genesis.json,config.toml} builds/testnets/local-testnet/` ) out && console.log(out) out = await makeExec( `sed -i.bak 's/seeds = ""/seeds = "localhost"/g' ./builds/testnets/local-testnet/config.toml` ) out && console.log(out) out = await makeExec( `sed -i.bak 's/index_all_tags = false/index_all_tags = true/g' ${homeDir}/.gaiad-testnet/config/config.toml` ) out && console.log(out) out = await makeExec( `./builds/Gaia/${environment}/gaiad version > ./builds/testnets/local-testnet/gaiaversion.txt` ) out && console.log(out) } function init(options, environment) { return new Promise(async (resolve, reject) => { if (options.overwrite && fs.existsSync(homeDir + `/.gaiad-testnet`)) { let out = await makeExec(`rm -r ${homeDir}/.gaiad-testnet`) out && console.log(out) } let command = `builds/Gaia/${environment}/gaiad init --home ${homeDir}/.gaiad-testnet --name local` if (options.overwrite) { command += ` -o --owk` } console.log(`$ ` + command) const localnodeProcess = spawn(command, { shell: true }) localnodeProcess.stdout.on(`data`, data => { let dataJson = JSON.parse(data.toString()) resolve(dataJson.app_message.secret) }) localnodeProcess.stdin.write(`${options.password}\n`) localnodeProcess.stderr.on(`data`, reject) localnodeProcess.once(`exit`, reject) }) }
const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] let state = false //? color picker let picker = () => { if (state == false) { let second = document.querySelector(".second") second.style.display = "flex" state = true } else { let second = document.querySelector(".second") second.style.display = "none" state = false } } //?hex let hex_start = () => { let hex_color = "#" for (let i = 0; i < 6; i++) { let hex_randomizer = Math.floor(Math.random() * hex.length) hex_color += hex[hex_randomizer] } console.log(hex_color) document.body.style.backgroundColor = hex_color let hex_value = (document.getElementById("color_text").value = hex_color) } //? hexa let hexa_start = () => { let hex_color = "#" for (let i = 0; i < 8; i++) { let hex_randomizer = Math.floor(Math.random() * hex.length) hex_color += hex[hex_randomizer] } console.log(hex_color) document.body.style.backgroundColor = hex_color let hex_value = (document.getElementById("color_text").value = hex_color) } //? rgb let rgb_start = () => { let rgb_color0 = "" let rgb_color1 = "" let rgb_color2 = "" for (let i = 0; i < 3; i++) { let rgb_randomizer = Math.floor(Math.random() * 256) switch (i) { case 0: rgb_color0 += rgb_randomizer break case 1: rgb_color1 += rgb_randomizer break case 2: rgb_color2 += rgb_randomizer break } } let rgb = `rgb(${rgb_color0},${rgb_color1},${rgb_color2})` console.log(rgb) document.body.style.backgroundColor = rgb let rgb_value = (document.getElementById("color_text").value = rgb) } //? rgba let rgba_start = () => { let rgb_color0 = "" let rgb_color1 = "" let rgb_color2 = "" for (let i = 0; i < 3; i++) { let rgb_randomizer = Math.floor(Math.random() * 256) switch (i) { case 0: rgb_color0 += rgb_randomizer break case 1: rgb_color1 += rgb_randomizer break case 2: rgb_color2 += rgb_randomizer break } } let rgb_color3 = Math.floor(Math.random() * 100) let rgb = `rgba(${rgb_color0},${rgb_color1},${rgb_color2}, 0.${rgb_color3})` console.log(rgb) document.body.style.backgroundColor = rgb let rgb_value = (document.getElementById("color_text").value = rgb) } //?hsla let hsla_start = () => { let hsl_color0 = Math.floor(Math.random() * 360) let hsl_color1 = Math.floor(Math.random() * 100) let hsl_color2 = Math.floor(Math.random() * 100) let hsl_color3 = Math.floor(Math.random() * 100) let hsl = `hsla(${hsl_color0}, ${hsl_color1}%, ${hsl_color2}%, 0.${hsl_color3})` console.log(hsl) document.body.style.backgroundColor = hsl let hsl_value = (document.getElementById("color_text").value = hsl) } //?hsl let hsl_start = () => { let hsl_color0 = Math.floor(Math.random() * 360) let hsl_color1 = Math.floor(Math.random() * 100) let hsl_color2 = Math.floor(Math.random() * 100) let hsl = `hsl(${hsl_color0}, ${hsl_color1}%, ${hsl_color2}%)` console.log(hsl) document.body.style.backgroundColor = hsl let hsl_value = (document.getElementById("color_text").value = hsl) } //? copy let copy = () => { let copycolor = document.getElementById("color_text") copycolor.select() copycolor.setSelectionRange(0, 9999) document.execCommand("copy") let memory = document.getElementById("color_text").value let copyied = (document.getElementById("color_text").value = "Copied!") document.getElementById("color_text").blur() setTimeout(() => { let memory_paste = (document.getElementById("color_text").value = memory) }, 500) }
import { bundleMDX } from 'mdx-bundler' import fs from 'fs' import matter from 'gray-matter' import path from 'path' import readingTime from 'reading-time' import { visit } from 'unist-util-visit' import getAllFilesRecursively from '@/lib/utils/files' // Remark packages import remarkGfm from 'remark-gfm' import remarkFootnotes from 'remark-footnotes' import remarkMath from 'remark-math' import remarkExtractFrontmatter from '@/lib/remark-extract-frontmatter' import remarkCodeTitles from '@/lib/remark-code-title' import remarkTocHeadings from '@/lib/remark-toc-headings' import remarkImgToJsx from '@/lib/remark-img-to-jsx' // Rehype packages import rehypeSlug from 'rehype-slug' import rehypeAutolinkHeadings from 'rehype-autolink-headings' import rehypeKatex from 'rehype-katex' import rehypeCitation from 'rehype-citation' import rehypePrismPlus from 'rehype-prism-plus' import rehypePresetMinify from 'rehype-preset-minify' const root = process.cwd() export function getFiles(type) { const prefixPaths = path.join(root, 'data', type) const files = getAllFilesRecursively(prefixPaths) // Only want to return blog/path and ignore root, replace is needed to work on Windows return files.map((file) => file.slice(prefixPaths.length + 1).replace(/\\/g, '/')) } export function formatSlug(slug) { return slug.replace(/\.(mdx|md)/, '') } export function dateSortDesc(a, b) { if (a > b) return -1 if (a < b) return 1 return 0 } export async function getFileBySlug(type, slug) { const mdxPath = path.join(root, 'data', type, `${slug}.mdx`) const mdPath = path.join(root, 'data', type, `${slug}.md`) const source = fs.existsSync(mdxPath) ? fs.readFileSync(mdxPath, 'utf8') : fs.readFileSync(mdPath, 'utf8') // https://github.com/kentcdodds/mdx-bundler#nextjs-esbuild-enoent if (process.platform === 'win32') { process.env.ESBUILD_BINARY_PATH = path.join(root, 'node_modules', 'esbuild', 'esbuild.exe') } else { process.env.ESBUILD_BINARY_PATH = path.join(root, 'node_modules', 'esbuild', 'bin', 'esbuild') } let toc = [] const { code, frontmatter } = await bundleMDX({ source, // mdx imports can be automatically source from the components directory cwd: path.join(root, 'components'), xdmOptions(options, frontmatter) { // this is the recommended way to add custom remark/rehype plugins: // The syntax might look weird, but it protects you in case we add/remove // plugins in the future. options.remarkPlugins = [ ...(options.remarkPlugins ?? []), remarkExtractFrontmatter, [remarkTocHeadings, { exportRef: toc }], remarkGfm, remarkCodeTitles, [remarkFootnotes, { inlineNotes: true }], remarkMath, remarkImgToJsx, ] options.rehypePlugins = [ ...(options.rehypePlugins ?? []), rehypeSlug, rehypeAutolinkHeadings, rehypeKatex, [rehypeCitation, { path: path.join(root, 'data') }], [rehypePrismPlus, { ignoreMissing: true }], rehypePresetMinify, ] return options }, esbuildOptions: (options) => { options.loader = { ...options.loader, '.js': 'jsx', } return options }, }) return { mdxSource: code, toc, frontMatter: { readingTime: readingTime(code), slug: slug || null, fileName: fs.existsSync(mdxPath) ? `${slug}.mdx` : `${slug}.md`, ...frontmatter, date: frontmatter.date ? new Date(frontmatter.date).toISOString() : null, }, } } export async function getAllFilesFrontMatter(folder) { const prefixPaths = path.join(root, 'data', folder) const files = getAllFilesRecursively(prefixPaths) const allFrontMatter = [] files.forEach((file) => { // Replace is needed to work on Windows const fileName = file.slice(prefixPaths.length + 1).replace(/\\/g, '/') // Remove Unexpected File if (path.extname(fileName) !== '.md' && path.extname(fileName) !== '.mdx') { return } const source = fs.readFileSync(file, 'utf8') const { data: frontmatter } = matter(source) if (frontmatter.draft !== true) { allFrontMatter.push({ ...frontmatter, slug: formatSlug(fileName), date: frontmatter.date ? new Date(frontmatter.date).toISOString() : null, }) } }) return allFrontMatter.sort((a, b) => dateSortDesc(a.date, b.date)) }
const mongoose = require('mongoose'); const { Schema, model } = mongoose; const Job = require('./Job'); const bcrypt = require('bcrypt'); const userSchema = new Schema( { username: { type: String, required: true, unique: true, trim: true }, email: { type: String, required: true, unique: true, match: [/.+@.+\..+/, 'Must match an email address!'] }, password: { type: String, required: true, minlength: 5 }, jobs: [Job.schema] }, { toJSON: { virtuals: true } } ); // set up pre-save middleware to create password userSchema.pre('save', async function(next) { if (this.isNew || this.isModified('password')) { const saltRounds = 10; this.password = await bcrypt.hash(this.password, saltRounds); } next(); }); // compare the incoming password with the hashed password userSchema.methods.isCorrectPassword = async function(password) { return bcrypt.compare(password, this.password); }; const User = mongoose.model('User', userSchema); module.exports = User;
import {join} from 'path' import http from 'http' import Koa from 'koa' import koaBodyParser from 'koa-bodyparser' import R from 'ramda' import chalk from 'chalk' import {sequelize} from "./middleware/database"; import {socket} from "./middleware/websocket"; import { systemLogger } from "../config/logger"; const MIDDLEWARES = ['router','log'] const useMiddlewares = async (app) => { R.map( R.compose( R.forEachObjIndexed( e => e(app) ), require, name => join(__dirname, `./middleware/${name}`) ) )(MIDDLEWARES) } async function start() { const app = new Koa() app.use(koaBodyParser()) const port = 3000 app.on('error', err => {systemLogger.error(err); }); await useMiddlewares(app) const server = http.createServer(app.callback()) socket(server) try { await sequelize.sync() server.listen(port, () => { console.log( process.env.NODE_ENV === 'development' ? `Open ${chalk.green('http://localhost:' + port)}` : `Server started at port ${port}` ) }) } catch (e) { console.log(e) } } start()
import { module, skip /* test */ } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Controller | admin/slots', function(hooks) { setupTest(hooks); // Replace this with your real tests. skip('it exists', function(assert) { let controller = this.owner.lookup('controller:admin/slots'); assert.ok(controller); }); });
define([ 'dojo/_base/declare', 'dojo/_base/array', 'dojo/_base/lang', 'dojo/on', 'dojo/Evented', './LayerInfos/LayerInfos' ], function(declare, array, lang, on, Evented, LayerInfos) { var clazz = declare([Evented], { declaredClass: "jimu.LayerStructure", map: null, _layerInfos: null, _eventHandles: null, constructor: function(layerInfos) { this._layerInfos = layerInfos; this.map = this._layerInfos.map; this._eventHandles = []; this._bindEvents(); }, getLayerNodes: function() { // summary: // Get the operational layerNodes of current map; // parameters: // null // return value: // LayerNode[] return this._getNodesArrayFromInfosArray(this._layerInfos.getLayerInfoArray()); }, getTableNodes: function() { // summary: // Get the operational tableNodes of current map; // parameters: // null // return value: // LayerNode[] return this._getNodesArrayFromInfosArray(this._layerInfos.getTableInfoArray()); }, getWebmapLayerNodes: function() { // summary: // Get operational layerNodes that are defined in the webmap; // parameters: // null // return value: // LayerNode[] return this._getNodesArrayFromInfosArray(this._layerInfos.getLayerInfoArrayOfWebmap()); }, getWebmapTableNodes: function() { // summary: // Get operational tableNodes that are defined in the webmap; // parameters: // null // return value: // LayerNode[] return this._getNodesArrayFromInfosArray(this._layerInfos.getTableInfoArrayOfWebmap()); }, addTable: function(table) { // summary: // Add a table to layerStructure. // parameters: // table = { // id: Optional parameters, // title: title of new table, // url: alternative with featureCollectionData, // featureCollectionData: alternative with url, // options: Optional parameters. See options list of FeatureLayer's Constructor from // ArcGIS JavaScript API reference. // } // return value: // LayerNode var tableNode = null; var tableInfo = this._layerInfos.addTable(table); if(tableInfo) { tableNode = tableInfo._adaptor; } return tableNode; }, removeTable: function(nodeId) { // summary: // Rmove a tableNode from layerStructure by nodeId. // parameters: // nodeId: tableNode id // return value: // null var tableNode = this.getNodeById(nodeId); if(tableNode) { this._layerInfos.removeTable(tableNode._layerInfo); } }, _traversal: function(callback, nodes) { for(var i = 0; i < nodes.length; i++) { if(nodes[i].traversal(callback)) { return true; } } return false; }, traversal: function(callback) { // summary: // Depth-first traversal all ndoes of the layerStructure. // parameters: // callback: function(layerNode) {}; // parameters: // layerNode: // return value: // boolean; // true: return true will interrupt traversal. // false: return false will continue traversal. // return value: // boolean; // return ture means traversal was interrupted. // return false means traversal was complete. return this._traversal(callback, this.getLayerNodes().concat(this.getTableNodes())); }, traversalWithNodes: function(callback, nodes) { // summary: // Depth-first traversal all ndoes of 'nodes' paramater. // parameters: // callback: function(layerNode) {}; // parameters: // layerNode: // return value: // boolean; // true: return true will interrupt traversal. // false: return false will continue traversal. // nodes: layerNods array; // return value: // boolean; // return ture means traversal was interrupted. // return false means traversal was complete. return this._traversal(callback, nodes); }, getNodeById: function(nodeId) { // summary: // Get the layerNode/tableNode by Id; // parameters: // nodeId: layerNode/tableNode Id; // return value: // LayerNode var resultNode = null; this.traversal(function(layerNode) { if(layerNode.id === nodeId) { resultNode = layerNode; return true; } }); return resultNode; }, getBasemapLayerObjects: function() { // summary: // Get the layerObjects of basemap; // parameters: // null; // return value: // LayerObject[] return this._layerInfos.getBasemapLayers(); }, restoreState: function(options) { this._layerInfos.restoreState(options); }, // getState: function() { // }, // moveUpLayerNode: function() { // }, // moveDownLayerNode: function() { // }, destroy: function() { array.forEach(this._eventHandles, function(eventHandle) { eventHandle.remove(); }); this.inherited(arguments); }, _getNodesArrayFromInfosArray: function(layerInfos) { var nodes = []; array.forEach(layerInfos, function(layerInfo) { nodes.push(layerInfo._adaptor); }, this); return nodes; }, _emitEvent: function() { try { this.emit.apply(this, arguments); } catch (err) { console.warn(err); } }, _bindEvents: function() { var handle; handle = on(this._layerInfos, 'layerInfosChanged', lang.hitch(this, this._onLayerNodesStructureChanged)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'tableInfosChanged', lang.hitch(this, this._onTableNdoesStructureChanged)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'layerInfosReorder', lang.hitch(this, this._onLayerReordered)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'layerInfosIsShowInMapChanged', lang.hitch(this, this._onVisibilityChanged)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'layerInfosIsVisibleChanged', lang.hitch(this, this._onToggleChanged)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'layerInfosFilterChanged', lang.hitch(this, this._onFilterChanged)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'layerInfosRendererChanged', lang.hitch(this, this._onRendererChanged)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'layerInfosOpacityChanged', lang.hitch(this, this._onOpacityChanged)); this._eventHandles.push(handle); handle = on(this._layerInfos, 'layerInfosTimeExtentChanged', lang.hitch(this, this._onTimeExtentChanged)); this._eventHandles.push(handle); }, // emit event when layerNode and tableNode changed. _onLayerNodesStructureChanged: function(layerInfo, changedType, layerInfoSelf) { var changedNodes = [layerInfoSelf._adaptor]; var changedRootNodes = [layerInfo._adaptor]; var eventObject = { type: changedType, layerNodes: changedNodes, rootLayerNodes: changedRootNodes }; this._emitEvent(clazz.EVENT_STRUCTURE_CHANGE, eventObject); //this._emitEvent(clazz.EVENT_STRUCTURE_CHANGE, changedType, changedNodes, changedRootNodes); }, _onTableNdoesStructureChanged: function(tableInfos, changedType) { var changedNodes = this._getNodesArrayFromInfosArray(tableInfos); var changedRootNodes = changedNodes; var eventObject = { type: changedType, layerNodes: changedNodes, rootLayerNodes: changedRootNodes }; this._emitEvent(clazz.EVENT_STRUCTURE_CHANGE, eventObject); //this._emitEvent(clazz.EVENT_STRUCTURE_CHANGE, changedType, changedNodes, changedRootNodes); }, _onLayerReordered: function(layerInfo, changedType) { var changedNodes = [layerInfo._adaptor]; var changedRootNodes = changedNodes; var eventObject = { type: changedType, layerNodes: changedNodes, rootLayerNodes: changedRootNodes }; this._emitEvent(clazz.EVENT_STRUCTURE_CHANGE, eventObject); //this._emitEvent(clazz.EVENT_STRUCTURE_CHANGE, changedType, changedNodes, changedRootNodes); }, _onVisibilityChanged: function(changedLayerInfos) { var changedNodes = this._getNodesArrayFromInfosArray(changedLayerInfos); var eventObject = { layerNodes: changedNodes }; this._emitEvent(clazz.EVENT_VISIBILITY_CHANGE, eventObject); }, _onToggleChanged: function(changedLayerInfos) { var changedNodes = this._getNodesArrayFromInfosArray(changedLayerInfos); var eventObject = { layerNodes: changedNodes }; this._emitEvent(clazz.EVENT_TOOGLE_CHANGE, eventObject); }, _onFilterChanged: function(changedLayerInfos) { var changedNodes = this._getNodesArrayFromInfosArray(changedLayerInfos); var eventObject = { layerNodes: changedNodes }; this._emitEvent(clazz.EVENT_FILTER_CHANGE, eventObject); }, _onRendererChanged: function(changedLayerInfos) { var changedNodes = this._getNodesArrayFromInfosArray(changedLayerInfos); var eventObject = { layerNodes: changedNodes }; this._emitEvent(clazz.EVENT_RENDERER_CHANGE, eventObject); }, _onOpacityChanged: function(changedLayerInfos) { var changedNodes = this._getNodesArrayFromInfosArray(changedLayerInfos); var eventObject = { layerNodes: changedNodes }; this._emitEvent(clazz.EVENT_OPACITY_CHANGE, eventObject); }, _onTimeExtentChanged: function(changedLayerInfos) { var changedNodes = this._getNodesArrayFromInfosArray(changedLayerInfos); var eventObject = { layerNodes: changedNodes }; this._emitEvent(clazz.EVENT_TIME_EXTENT_CHANGE, eventObject); } }); var instance = null; clazz.getInstance = function() { // need to confirm instance. if(!instance || instance._layerInfos._objectId !== LayerInfos.getInstanceSync()._objectId) { if(instance) { instance.destroy(); } instance = new clazz(LayerInfos.getInstanceSync()); } return instance; }; clazz.createInstance = function(map) { var layerStructure = new clazz(LayerInfos.createInstance(map)); return layerStructure; }; lang.mixin(clazz, { STRUCTURE_CHANGE_ADD: LayerInfos.ADDED, STRUCTURE_CHANGE_REMOVE: LayerInfos.REMOVED, STRUCTURE_CHANGE_SUBNODE_ADD: LayerInfos.SUBLAYER_ADDED, STRUCTURE_CHANGE_SUBNODE_REMOVE: LayerInfos.SUBLAYER_REMOVED, STRUCTURE_CHANGE_NODE_UPDATE: LayerInfos.UPDATED, STRUCTURE_CHANGE_REORDER: LayerInfos.REORDERED, EVENT_STRUCTURE_CHANGE: "structure-change", EVENT_TOOGLE_CHANGE: "toggle-change", EVENT_VISIBILITY_CHANGE: "visibility-change", EVENT_FILTER_CHANGE: "filter-change", EVENT_RENDERER_CHANGE: "renderer-change", EVENT_OPACITY_CHANGE: "opacity-change", EVENT_TIME_EXTENT_CHANGE: "time-extent-change" }); return clazz; });
import test from 'ava' import { hashAnything } from './digest.js' test('Test hash anything - mix of variables, objects, arrays, strings etc.', async (t) => { const a = 'test' const b = [11, 22, 33] const c = { a: 1, b: [1, 2, 3], c: 'test' } const d = 123213 const hash = await hashAnything(a, b, c, d) t.is(hash.length, 64) })
module.exports = new Date(2011, 6, 10)
import dayjs from 'dayjs/esm' import localeData from 'dayjs/plugin/localeData' import minMax from 'dayjs/plugin/minMax' import isSameOrBefore from 'dayjs/plugin/isSameOrBefore' import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' dayjs.extend(localeData) dayjs.extend(minMax) dayjs.extend(isSameOrBefore) dayjs.extend(isSameOrAfter) export { dayjs }
const path = require('path'); module.exports = { description: 'disallows duplicate imports', error: { code: 'PARSE_ERROR', message: `Identifier 'a' has already been declared`, parserError: { loc: { column: 9, line: 2 }, message: "Identifier 'a' has already been declared (2:9)", pos: 36, raisedAt: 39 }, pos: 36, watchFiles: [path.resolve(__dirname, 'main.js')], loc: { file: path.resolve(__dirname, 'main.js'), line: 2, column: 9 }, frame: ` 1: import { a } from './foo'; 2: import { a } from './foo'; ^ 3: 4: assert.equal(a, 1); ` } }; // test copied from https://github.com/esnext/es6-module-transpiler/tree/master/test/examples/duplicate-import-fails
"""Changing recording to input, and moving tags to json Revision ID: 93a369d8ac64 Revises: 928495730715 Create Date: 2018-05-28 17:14:59.127304 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '93a369d8ac64' down_revision = 'c872ccb5ecf2' branch_labels = None depends_on = None from sqlalchemy.orm import sessionmaker, Session as BaseSession from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() Session = sessionmaker() class TestInput(Base): __tablename__ = 'test_inputs' id = sa.Column(sa.Integer(), primary_key=True) path = sa.Column(sa.String(), index=True, nullable=False) database = sa.Column(sa.String(), nullable=False) __table_args__ = (sa.UniqueConstraint('database', 'path', name='_database_path'),) def upgrade(): # projects # op.alter_column('ci_commits', 'project_id', type_=sa.String, new_column_name= 'project') # drop the uniqueness constaint op.alter_column('ci_commits', 'project', type_=sa.String, new_column_name= 'project_id') # drop the uniqueness constaint op.alter_column('recordings', 'path', type_=sa.String) # drop the uniqueness constaint op.create_table( 'projects', sa.Column('id', sa.String(), primary_key=True), sa.Column('information', sa.JSON()) ) # op.drop_column("ci_commits", "project") # op.add_column('ci_commits', sa.Column('project_id', # sa.String, # sa.ForeignKey('projects.id'), # default='dvs/psp_swip', # # nullable=False, # index=True, # ) # ) bind = op.get_bind() session = Session(bind=bind) class CiCommitNew(Base): __tablename__ = 'ci_commits' id = sa.Column(sa.String, primary_key=True) # git commit id project_id = sa.Column(sa.String(), sa.ForeignKey('projects.id'), index=True) project = sa.orm.relationship("Project", back_populates="ci_commits") authored_datetime = sa.Column(sa.DateTime(timezone=True), index=True) class Project(Base): __tablename__ = 'projects' id = sa.Column(sa.String(), primary_key=True) ci_commits = sa.orm.relationship("CiCommitNew", order_by=CiCommitNew.authored_datetime, back_populates="project") try: slam_project = session.query(Project).filter_by(id='dvs/psp_swip').one() except: slam_project = Project(id='dvs/psp_swip') for o in session.query(CiCommitNew): o.project = slam_project session.commit() # # recordings => test_inputs op.rename_table('recordings', 'test_inputs') op.add_column('test_inputs', sa.Column('database', sa.String)) # nullable=False op.alter_column('test_inputs', 'path', type_=sa.String) # drop the uniqueness constaint slam_database = '/net/f2/algo_archive/DVS_SLAM_Database' for o in session.query(TestInput): o.database = slam_database session.commit() op.create_index('outputs_batch_id_idx', 'outputs', ['batch_id']) op.create_index('ci_commits_batch_id_idx', 'ci_commits', ['project_id']) op.create_index('ci_commits_branch_idx', 'ci_commits', ['branch']) op.create_index('ci_commits_authored_datetime_idx', 'ci_commits', ['authored_datetime']) op.create_unique_constraint('input_test_database_path_unique', 'test_inputs', ['database', 'path']) def downgrade(): # remove the projects bind = op.get_bind() session = Session(bind=bind) # class CiCommitOld(Base): # __tablename__ = 'ci_commits' # id = sa.Column(sa.String, primary_key=True) # git commit id # project = sa.Column(sa.String()) op.drop_column("ci_commits", "project") op.alter_column('ci_commits', 'project_id', type_=sa.String, new_column_name= 'project') # for o in session.query(CiCommitNew): # o.project = o.project_id # session.commit() # op.drop_table('projects') # op.rename_table('test_inputs', 'recordings') # we don't remove the index, why bother...
const foreach = require('guld-fs-foreach') const spawn = require('guld-spawn').getSpawn() async function strReplace (oldstr, newstr, args) { return foreach(args[0], async f => { if (f === '') return var resp = await spawn('sed', '', ['-i', `s/${oldstr}/${newstr}/g`, f], true) return resp }, args.slice(1)) } module.exports = strReplace
#!/usr/bin/env python3 # # This file is part of LiteX-Boards. # # Copyright (c) Greg Davill <greg.davill@gmail.com> # SPDX-License-Identifier: BSD-2-Clause import os import sys import argparse from migen import * from migen.genlib.misc import WaitTimer from migen.genlib.resetsync import AsyncResetSynchronizer from litex_boards.platforms import orangecrab from litex.build.lattice.trellis import trellis_args, trellis_argdict from litex.soc.cores.clock import * from litex.soc.integration.soc_core import * from litex.soc.integration.builder import * from litex.soc.cores.led import LedChaser from litedram.modules import MT41K64M16, MT41K128M16, MT41K256M16, MT41K512M16 from litedram.phy import ECP5DDRPHY # CRG --------------------------------------------------------------------------------------------- class _CRG(Module): def __init__(self, platform, sys_clk_freq, with_usb_pll=False): self.rst = Signal() self.clock_domains.cd_por = ClockDomain(reset_less=True) self.clock_domains.cd_sys = ClockDomain() # # # # Clk / Rst clk48 = platform.request("clk48") rst_n = platform.request("usr_btn", loose=True) if rst_n is None: rst_n = 1 # Power on reset por_count = Signal(16, reset=2**16-1) por_done = Signal() self.comb += self.cd_por.clk.eq(clk48) self.comb += por_done.eq(por_count == 0) self.sync.por += If(~por_done, por_count.eq(por_count - 1)) # PLL self.submodules.pll = pll = ECP5PLL() self.comb += pll.reset.eq(~por_done | ~rst_n | self.rst) pll.register_clkin(clk48, 48e6) pll.create_clkout(self.cd_sys, sys_clk_freq) # USB PLL if with_usb_pll: self.clock_domains.cd_usb_12 = ClockDomain() self.clock_domains.cd_usb_48 = ClockDomain() usb_pll = ECP5PLL() self.submodules += usb_pll self.comb += usb_pll.reset.eq(~por_done) usb_pll.register_clkin(clk48, 48e6) usb_pll.create_clkout(self.cd_usb_48, 48e6) usb_pll.create_clkout(self.cd_usb_12, 12e6) # FPGA Reset (press usr_btn for 1 second to fallback to bootloader) reset_timer = WaitTimer(int(48e6)) reset_timer = ClockDomainsRenamer("por")(reset_timer) self.submodules += reset_timer self.comb += reset_timer.wait.eq(~rst_n) self.comb += platform.request("rst_n").eq(~reset_timer.done) class _CRGSDRAM(Module): def __init__(self, platform, sys_clk_freq, with_usb_pll=False): self.rst = Signal() self.clock_domains.cd_init = ClockDomain() self.clock_domains.cd_por = ClockDomain(reset_less=True) self.clock_domains.cd_sys = ClockDomain() self.clock_domains.cd_sys2x = ClockDomain() self.clock_domains.cd_sys2x_i = ClockDomain(reset_less=True) # # # self.stop = Signal() self.reset = Signal() # Clk / Rst clk48 = platform.request("clk48") rst_n = platform.request("usr_btn", loose=True) if rst_n is None: rst_n = 1 # Power on reset por_count = Signal(16, reset=2**16-1) por_done = Signal() self.comb += self.cd_por.clk.eq(clk48) self.comb += por_done.eq(por_count == 0) self.sync.por += If(~por_done, por_count.eq(por_count - 1)) # PLL sys2x_clk_ecsout = Signal() self.submodules.pll = pll = ECP5PLL() self.comb += pll.reset.eq(~por_done | ~rst_n | self.rst) pll.register_clkin(clk48, 48e6) pll.create_clkout(self.cd_sys2x_i, 2*sys_clk_freq) pll.create_clkout(self.cd_init, 24e6) self.specials += [ Instance("ECLKBRIDGECS", i_CLK0 = self.cd_sys2x_i.clk, i_SEL = 0, o_ECSOUT = sys2x_clk_ecsout), Instance("ECLKSYNCB", i_ECLKI = sys2x_clk_ecsout, i_STOP = self.stop, o_ECLKO = self.cd_sys2x.clk), Instance("CLKDIVF", p_DIV = "2.0", i_ALIGNWD = 0, i_CLKI = self.cd_sys2x.clk, i_RST = self.reset, o_CDIVX = self.cd_sys.clk), AsyncResetSynchronizer(self.cd_sys, ~pll.locked | self.reset), AsyncResetSynchronizer(self.cd_sys2x, ~pll.locked | self.reset), ] # USB PLL if with_usb_pll: self.clock_domains.cd_usb_12 = ClockDomain() self.clock_domains.cd_usb_48 = ClockDomain() usb_pll = ECP5PLL() self.submodules += usb_pll self.comb += usb_pll.reset.eq(~por_done) usb_pll.register_clkin(clk48, 48e6) usb_pll.create_clkout(self.cd_usb_48, 48e6) usb_pll.create_clkout(self.cd_usb_12, 12e6) # FPGA Reset (press usr_btn for 1 second to fallback to bootloader) reset_timer = WaitTimer(int(48e6)) reset_timer = ClockDomainsRenamer("por")(reset_timer) self.submodules += reset_timer self.comb += reset_timer.wait.eq(~rst_n) self.comb += platform.request("rst_n").eq(~reset_timer.done) # BaseSoC ------------------------------------------------------------------------------------------ class BaseSoC(SoCCore): def __init__(self, revision="0.2", device="25F", sdram_device="MT41K64M16", sys_clk_freq=int(48e6), toolchain="trellis", with_led_chaser=True, **kwargs): platform = orangecrab.Platform(revision=revision, device=device ,toolchain=toolchain) # Serial ----------------------------------------------------------------------------------- if kwargs["uart_name"] in ["serial", "usb_acm"]: kwargs["uart_name"] = "usb_acm" # Defaults to USB ACM through ValentyUSB. os.system("git clone https://github.com/litex-hub/valentyusb -b hw_cdc_eptri") sys.path.append("valentyusb") # SoCCore ---------------------------------------------------------------------------------- SoCCore.__init__(self, platform, sys_clk_freq, ident = "LiteX SoC on OrangeCrab", ident_version = True, **kwargs) # CRG -------------------------------------------------------------------------------------- with_usb_pll = kwargs.get("uart_name", None) == "usb_acm" crg_cls = _CRGSDRAM if not self.integrated_main_ram_size else _CRG self.submodules.crg = crg_cls(platform, sys_clk_freq, with_usb_pll) # DDR3 SDRAM ------------------------------------------------------------------------------- if not self.integrated_main_ram_size: available_sdram_modules = { "MT41K64M16": MT41K64M16, "MT41K128M16": MT41K128M16, "MT41K256M16": MT41K256M16, "MT41K512M16": MT41K512M16, } sdram_module = available_sdram_modules.get(sdram_device) ddram_pads = platform.request("ddram") self.submodules.ddrphy = ECP5DDRPHY( pads = ddram_pads, sys_clk_freq = sys_clk_freq, cmd_delay = 0 if sys_clk_freq > 64e6 else 100) self.ddrphy.settings.rtt_nom = "disabled" if hasattr(ddram_pads, "vccio"): self.comb += ddram_pads.vccio.eq(0b111111) if hasattr(ddram_pads, "gnd"): self.comb += ddram_pads.gnd.eq(0) self.comb += self.crg.stop.eq(self.ddrphy.init.stop) self.comb += self.crg.reset.eq(self.ddrphy.init.reset) self.add_sdram("sdram", phy = self.ddrphy, module = sdram_module(sys_clk_freq, "1:2"), l2_cache_size = kwargs.get("l2_size", 8192) ) # Leds ------------------------------------------------------------------------------------- if with_led_chaser: self.submodules.leds = LedChaser( pads = platform.request_all("user_led"), sys_clk_freq = sys_clk_freq) # Build -------------------------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser(description="LiteX SoC on OrangeCrab") parser.add_argument("--build", action="store_true", help="Build bitstream.") parser.add_argument("--load", action="store_true", help="Load bitstream.") parser.add_argument("--toolchain", default="trellis", help="FPGA toolchain (trellis or diamond).") parser.add_argument("--sys-clk-freq", default=48e6, help="System clock frequency.") parser.add_argument("--revision", default="0.2", help="Board Revision (0.1 or 0.2).") parser.add_argument("--device", default="25F", help="ECP5 device (25F or 45F).") parser.add_argument("--sdram-device", default="MT41K64M16", help="SDRAM device (MT41K64M16, MT41K128M16, MT41K256M16 or MT41K512M16).") parser.add_argument("--with-spi-sdcard", action="store_true", help="Enable SPI-mode SDCard support.") builder_args(parser) soc_core_args(parser) trellis_args(parser) args = parser.parse_args() soc = BaseSoC( toolchain = args.toolchain, revision = args.revision, device = args.device, sdram_device = args.sdram_device, sys_clk_freq = int(float(args.sys_clk_freq)), **soc_core_argdict(args)) if args.with_spi_sdcard: soc.add_spi_sdcard() builder = Builder(soc, **builder_argdict(args)) builder_kargs = trellis_argdict(args) if args.toolchain == "trellis" else {} builder.build(**builder_kargs, run=args.build) if args.load: prog = soc.platform.create_programmer() prog.load_bitstream(os.path.join(builder.gateware_dir, soc.build_name + ".bit")) if __name__ == "__main__": main()
import { combineReducers } from 'redux'; import commandHistoryStorage from './commandHistoryStorage'; import fileStorage from './fileStorage'; import workspaceStorage from './workspaceStorage'; export default combineReducers({ commandHistoryStorage, fileStorage, workspaceStorage, });
import GroupService from '@baserow/modules/core/services/group' /** * Mixin that fetches a group invitation based on the `groupInvitationToken` query * parameter. If the token is not found, null will be added as invitation data value. */ export default { async asyncData({ route, app }) { const token = route.query.groupInvitationToken if (token) { try { const { data: invitation } = await GroupService( app.$client ).fetchInvitationByToken(token) return { invitation } } catch {} } return { invitation: null } }, }
import axios from 'axios'; export default { all() { return axios.get('/api/orders'); }, find(id) { return axios.get(`/api/orders/${id}`); }, update(id, data, config) { return axios.post(`/api/orders/${id}`, data, config); }, updateAll(data) { return axios.post(`/api/orders/updateAll`, data); }, delete(id) { return axios.delete(`/api/orders/${id}`); }, create(data, config) { return axios.post('/api/orders/create', data, config); }, getDraw(draw, config) { return axios.post(`/api/orders/draw`, draw, config); } };
import {TestResults} from '@cdo/apps/constants'; module.exports = { app: 'turtle', levelFile: 'levels', levelId: '4_10', tests: [ { description: 'Top Solve: Repeat 9x', expected: { result: true, testResult: TestResults.ALL_PASS }, timeout: 30000, missingBlocks: [], xml: '<xml><block type="when_run"><next><block type="controls_repeat"><title name="TIMES">9</title><statement name="DO"><block type="controls_repeat" deletable="false" editable="false"><title name="TIMES">10</title><statement name="DO"><block type="draw_colour" inline="true" deletable="false" editable="false"><value name="COLOUR"><block type="colour_random" deletable="false" editable="false"></block></value><next><block type="controls_repeat" deletable="false" editable="false"><title name="TIMES">4</title><statement name="DO"><block type="draw_move_by_constant" deletable="false" editable="false"><title name="DIR">moveForward</title><title name="VALUE">20</title><next><block type="draw_turn_by_constant" deletable="false" editable="false"><title name="DIR">turnRight</title><title name="VALUE">90</title></block></next></block></statement><next><block type="draw_move_by_constant" deletable="false" editable="false"><title name="DIR">moveForward</title><title name="VALUE">20</title></block></next></block></next></block></statement><next><block type="draw_turn_by_constant" deletable="false" editable="false"><title name="DIR">turnRight</title><title name="VALUE">80</title></block></next></block></statement></block></next></block></xml>' } ] };
import os import pika import sys import pyowm import json from pika import PlainCredentials OWM_API_KEY = os.getenv("OWM_API_KEY", "") RAW_GEOLOCATION_QUEUE = "rawGeoLocations" WETTER_QUEUE = "gefundenesWetter" owm = pyowm.OWM(OWM_API_KEY) connection = pika.BlockingConnection( pika.ConnectionParameters('192.168.1.1', credentials=PlainCredentials("gast", "gast"))) locationChannel = connection.channel() locationChannel.queue_declare(RAW_GEOLOCATION_QUEUE, durable=True) wetterChannel = connection.channel() wetterChannel.queue_declare(WETTER_QUEUE, durable=True) class Location: def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude class Wetter: def __init__(self, status): self.status = status def location_decoder(obj): return Location(obj['latitude'], obj['longitude']) class WetterFinder: def __init__(self, owm, publishChannel, publishQueueName): self.owm = owm self.publishChannel = publishChannel self.publishQueueName = publishQueueName self.gefundeneWetter = 0 def get_wetter(self, wetterresponse): return wetterresponse.get_weather().get_status() def tweet_erhalten(self, channel, method, properties, body): location = json.loads(body, object_hook=location_decoder) if location.latitude < -90 or location.latitude > 90 or location.longitude < -90 or location.longitude > 90: return wetterresponse = self.owm.weather_at_coords(location.longitude, location.latitude) daswetter = self.get_wetter(wetterresponse) channel.basic_ack(delivery_tag=method.delivery_tag) if daswetter is None: return self.gefundeneWetter += 1 sys.stdout.write("\rGefundene Wetter: " + str(self.gefundeneWetter)) sys.stdout.flush() wetter = Wetter(daswetter) self.publishChannel.basic_publish(exchange='', routing_key=self.publishQueueName, body=json.dumps(wetter.__dict__)) wetterfinder = WetterFinder(owm, wetterChannel, WETTER_QUEUE) locationChannel.basic_consume(wetterfinder.tweet_erhalten, queue=RAW_GEOLOCATION_QUEUE) locationChannel.start_consuming()
"use strict"; exports.__esModule = true; exports.CmdButton = exports.CmdDiv = exports.CmdSwitch = exports.CmdCheckbox = exports.withCommand = undefined; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _core = require("@blueprintjs/core"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var withCommand = function withCommand(mappings) { return function (WrappedComponent) { return function (_ref) { var cmd = _ref.cmd, _ref$cmdOptions = _ref.cmdOptions, cmdOptions = _ref$cmdOptions === undefined ? {} : _ref$cmdOptions, props = _objectWithoutProperties(_ref, ["cmd", "cmdOptions"]); var mappedProps = {}; Object.keys(mappings).forEach(function (k) { mappedProps[k] = mappings[k] === "execute" ? function (event) { return cmd.execute({ event: event }); } : typeof mappings[k] === "function" ? mappings[k](cmd, props) : cmd[mappings[k]]; }); var out = _react2.default.createElement(WrappedComponent, _extends({}, props, mappedProps)); var tooltip = cmd.tooltip || typeof cmd.isDisabled === "string" && cmd.isDisabled; if (tooltip && !cmdOptions.ignoreTooltip) { out = _react2.default.createElement( _core.Tooltip, { content: tooltip }, out ); } return cmd.isHidden && !cmdOptions.ignoreHidden ? null : out; }; }; }; exports.withCommand = withCommand; var CmdCheckbox = exports.CmdCheckbox = withCommand({ onChange: "execute", label: function label(cmd, props) { return props.name || props.prefix && _react2.default.createElement( _react2.default.Fragment, null, props.prefix, cmd.name ) || cmd.name; }, disabled: "isDisabled", checked: "isActive" })(_core.Checkbox); var CmdSwitch = exports.CmdSwitch = withCommand({ onChange: "execute", label: function label(cmd, props) { return props.name || props.prefix && _react2.default.createElement( _react2.default.Fragment, null, props.prefix, cmd.name ) || cmd.name; }, disabled: "isDisabled", checked: "isActive" })(_core.Switch); var Div = function Div(_ref2) { var onChange = _ref2.onChange, children = _ref2.children; return _react2.default.createElement( "div", { onClick: onChange }, children ); }; var CmdDiv = exports.CmdDiv = withCommand({ onChange: "execute", children: function children(cmd, props) { return props.name || props.prefix && _react2.default.createElement( _react2.default.Fragment, null, props.prefix, cmd.name ) || cmd.name; }, disabled: "isDisabled", checked: "isActive" })(Div); var CmdButton = exports.CmdButton = withCommand({ onClick: "execute", text: function text(cmd) { return cmd.isActive === false && cmd.inactiveName || cmd.name; }, icon: "icon", disabled: "isDisabled" })(_core.Button);
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.1.1 (2019-10-28) */ !function(){"use strict";function e(){}function o(e){return function(){return e}}function t(){return u}var r,n=tinymce.util.Tools.resolve("tinymce.PluginManager"),d=function(){return(d=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)},a=o(!1),c=o(!0),u=(r={fold:function(e,t){return e()},is:a,isSome:a,isNone:c,getOr:l,getOrThunk:s,getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:o(null),getOrUndefined:o(undefined),or:l,orThunk:s,map:t,each:e,bind:t,exists:a,forall:c,filter:t,equals:i,equals_:i,toArray:function(){return[]},toString:o("none()")},Object.freeze&&Object.freeze(r),r);function i(e){return e.isNone()}function s(e){return e()}function l(e){return e}function m(t){return function(e){return function(e){if(null===e)return"null";var t=typeof e;return"object"==t&&(Array.prototype.isPrototypeOf(e)||e.constructor&&"Array"===e.constructor.name)?"array":"object"==t&&(String.prototype.isPrototypeOf(e)||e.constructor&&"String"===e.constructor.name)?"string":t}(e)===t}}function f(e,t){for(var r=0,n=e.length;r<n;r++){t(e[r],r)}}function h(e,t){return G(e,t)?E(e[t]):D()}function p(t){return function(e){return e?function(e){return e.replace(/px$/,"")}(e.style[t]):""}}function g(r){return function(e,t){e&&(e.style[r]=function(e){return/^[0-9.]+$/.test(e)?e+"px":e}(t))}}function v(e,t){if(e)for(var r=0;r<e.length;r++)if(-1!==t.indexOf(e[r].filter))return e[r]}function b(e){return ae.getAttrib(e,"data-ephox-embed-iri")}function w(e,t){return function(e){var t=ae.createFragment(e);return""!==b(t.firstChild)}(t)?function(e){var t=ae.createFragment(e).firstChild;return{type:"ephox-embed-iri",source1:b(t),source2:"",poster:"",width:oe.getMaxWidth(t),height:oe.getMaxHeight(t)}}(t):function(n,e){var i={};return ne({validate:!1,allow_conditional_comments:!0,start:function(e,t){if(i.source1||"param"!==e||(i.source1=t.map.movie),"iframe"!==e&&"object"!==e&&"embed"!==e&&"video"!==e&&"audio"!==e||(i.type||(i.type=e),i=re.extend(t.map,i)),"script"===e){var r=v(n,t.map.src);if(!r)return;i={type:"script",source1:t.map.src,width:String(r.width),height:String(r.height)}}"source"===e&&(i.source1?i.source2||(i.source2=t.map.src):i.source1=t.map.src),"img"!==e||i.poster||(i.poster=t.map.src)}}).parse(e),i.source1=i.source1||i.src||i.data,i.source2=i.source2||"",i.poster=i.poster||"",i}(e,t)}function y(e,t){var r,n,i,o;for(r in t)if(i=""+t[r],e.map[r])for(n=e.length;n--;)(o=e[n]).name===r&&(i?(e.map[r]=i,o.value=i):(delete e.map[r],e.splice(n,1)));else i&&(e.push({name:r,value:i}),e.map[r]=i)}function x(e,t){var r=me.createFragment(e).firstChild;return oe.setMaxWidth(r,t.width),oe.setMaxHeight(r,t.height),function(e){var t=se();return ne(t).parse(e),t.getContent()}(r.outerHTML)}function j(r,e){var n=re.extend({},e);if(!n.source1&&(re.extend(n,w(J(r),n.embed)),!n.source1))return"";n.source2||(n.source2=""),n.poster||(n.poster=""),n.source1=r.convertURL(n.source1,"source"),n.source2=r.convertURL(n.source2,"source"),n.source1mime=ue(n.source1),n.source2mime=ue(n.source2),n.poster=r.convertURL(n.poster,"poster");var t=function(t){var e=fe.filter(function(e){return e.regex.test(t)});return 0<e.length?re.extend({},e[0],{url:function(e,t){for(var r=e.regex.exec(t),n=e.url,i=function(e){n=n.replace("$"+e,function(){return r[e]?r[e]:""})},o=0;o<r.length;o++)i(o);return n.replace(/\?$/,"")}(e[0],t)}):null}(n.source1);if(t&&(n.source1=t.url,n.type=t.type,n.allowFullscreen=t.allowFullscreen,n.width=n.width||String(t.w),n.height=n.height||String(t.h)),n.embed)return de(n.embed,n,!0);var i=v(J(r),n.source1);i&&(n.type="script",n.width=String(i.width),n.height=String(i.height));var o=K(r),a=Q(r);return n.width=n.width||"300",n.height=n.height||"150",re.each(n,function(e,t){n[t]=r.dom.encode(""+e)}),"iframe"===n.type?function(e){var t=e.allowFullscreen?' allowFullscreen="1"':"";return'<iframe src="'+e.source1+'" width="'+e.width+'" height="'+e.height+'"'+t+"></iframe>"}(n):"application/x-shockwave-flash"===n.source1mime?function(e){var t='<object data="'+e.source1+'" width="'+e.width+'" height="'+e.height+'" type="application/x-shockwave-flash">';return e.poster&&(t+='<img src="'+e.poster+'" width="'+e.width+'" height="'+e.height+'" />'),t+="</object>"}(n):-1!==n.source1mime.indexOf("audio")?function(e,t){return t?t(e):'<audio controls="controls" src="'+e.source1+'">'+(e.source2?'\n<source src="'+e.source2+'"'+(e.source2mime?' type="'+e.source2mime+'"':"")+" />\n":"")+"</audio>"}(n,o):"script"===n.type?function(e){return'<script src="'+e.source1+'"><\/script>'}(n):function(e,t){return t?t(e):'<video width="'+e.width+'" height="'+e.height+'"'+(e.poster?' poster="'+e.poster+'"':"")+' controls="controls">\n<source src="'+e.source1+'"'+(e.source1mime?' type="'+e.source1mime+'"':"")+" />\n"+(e.source2?'<source src="'+e.source2+'"'+(e.source2mime?' type="'+e.source2mime+'"':"")+" />\n":"")+"</video>"}(n,a)}function O(t){return function(e){return j(t,e)}}function A(e){var r=q(e,{source1:e.source1.value,source2:h(e,"source2").bind(function(e){return h(e,"value")}).getOr(""),poster:h(e,"poster").bind(function(e){return h(e,"value")}).getOr("")});return h(e,"dimensions").each(function(e){f(["width","height"],function(t){h(e,t).each(function(e){return r[t]=e})})}),r}function S(e){var n=q(e,{source1:{value:h(e,"source1").getOr("")},source2:{value:h(e,"source2").getOr("")},poster:{value:h(e,"poster").getOr("")}});return f(["width","height"],function(r){h(e,r).each(function(e){var t=n.dimensions||{};t[r]=e,n.dimensions=t})}),n}function _(r){return function(e){var t=e&&e.msg?"Media embed handler error: "+e.msg:"Media embed handler threw unknown error.";r.notificationManager.open({type:"error",text:t})}}function C(e,t){return w(J(e),t)}function M(i,o){return function(e){if(N(e.url)&&0<e.url.trim().length){var t=e.html,r=C(o,t),n=d(d({},r),{source1:e.url,embed:t});i.setData(S(n))}}}function F(e,t){var r=e.dom.select("img[data-mce-object]");e.insertContent(t),function(e,t){for(var r=e.dom.select("img[data-mce-object]"),n=0;n<t.length;n++)for(var i=r.length-1;0<=i;i--)t[n]===r[i]&&r.splice(i,1);e.selection.select(r[0])}(e,r),e.nodeChanged()}function P(e,t){var r,n=t.name;return(r=new ye("img",1)).shortEnded=!0,Oe(e,t,r),r.attr({width:t.attr("width")||"300",height:t.attr("height")||("audio"===n?"30":"150"),style:t.attr("style"),src:xe.transparentSrc,"data-mce-object":n,"class":"mce-object mce-object-"+n}),r}function k(e,t){var r,n,i,o=t.name;return(r=new ye("span",1)).attr({contentEditable:"false",style:t.attr("style"),"data-mce-object":o,"class":"mce-preview-object mce-object-"+o}),Oe(e,t,r),(n=new ye(o,1)).attr({src:t.attr("src"),allowfullscreen:t.attr("allowfullscreen"),style:t.attr("style"),"class":t.attr("class"),width:t.attr("width"),height:t.attr("height"),frameborder:"0"}),(i=new ye("span",1)).attr("class","mce-shim"),r.append(n),r.append(i),r}function T(e){for(;e=e.parent;)if(e.attr("data-ephox-embed-iri")||(void 0,(t=e.attr("class"))&&/\btiny-pageembed\b/.test(t)))return!0;var t;return!1}var $,z=function(r){function e(){return i}function t(e){return e(r)}var n=o(r),i={fold:function(e,t){return t(r)},is:function(e){return r===e},isSome:c,isNone:a,getOr:n,getOrThunk:n,getOrDie:n,getOrNull:n,getOrUndefined:n,or:e,orThunk:e,map:function(e){return z(e(r))},each:function(e){e(r)},bind:t,exists:t,forall:t,filter:function(e){return e(r)?i:u},toArray:function(){return[r]},toString:function(){return"some("+r+")"},equals:function(e){return e.is(r)},equals_:function(e,t){return e.fold(a,function(e){return t(r,e)})}};return i},D=t,E=function(e){return null===e||e===undefined?u:z(e)},N=m("string"),U=m("array"),R=m("function"),L=Array.prototype.slice,W=Array.prototype.push,H=(R(Array.from)&&Array.from,function(e){function t(){return r}var r=e;return{get:t,set:function(e){r=e},clone:function(){return H(t())}}}),I=Object.prototype.hasOwnProperty,q=($=function(e,t){return t},function(){for(var e=new Array(arguments.length),t=0;t<e.length;t++)e[t]=arguments[t];if(0===e.length)throw new Error("Can't merge zero objects");for(var r={},n=0;n<e.length;n++){var i=e[n];for(var o in i)I.call(i,o)&&(r[o]=$(r[o],i[o]))}return r}),B=Object.hasOwnProperty,G=function(e,t){return B.call(e,t)},J=function(e){return e.getParam("media_scripts")},K=function(e){return e.getParam("audio_template_callback")},Q=function(e){return e.getParam("video_template_callback")},V=function(e){return e.getParam("media_live_embeds",!0)},X=function(e){return e.getParam("media_filter_html",!0)},Y=function(e){return e.getParam("media_url_resolver")},Z=function(e){return e.getParam("media_alt_source",!0)},ee=function(e){return e.getParam("media_poster",!0)},te=function(e){return e.getParam("media_dimensions",!0)},re=tinymce.util.Tools.resolve("tinymce.util.Tools"),ne=tinymce.util.Tools.resolve("tinymce.html.SaxParser"),ie=tinymce.util.Tools.resolve("tinymce.dom.DOMUtils"),oe={getMaxWidth:p("maxWidth"),getMaxHeight:p("maxHeight"),setMaxWidth:g("maxWidth"),setMaxHeight:g("maxHeight")},ae=ie.DOM,ce=tinymce.util.Tools.resolve("tinymce.util.Promise"),ue=function(e){var t={mp3:"audio/mpeg",m4a:"audio/x-m4a",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg",swf:"application/x-shockwave-flash"}[e.toLowerCase().split(".").pop()];return t||""},se=tinymce.util.Tools.resolve("tinymce.html.Writer"),le=tinymce.util.Tools.resolve("tinymce.html.Schema"),me=ie.DOM,de=function(e,t,r){return function(e){var t=me.createFragment(e);return""!==me.getAttrib(t.firstChild,"data-ephox-embed-iri")}(e)?x(e,t):function(e,i,o){var a,c=se(),u=0;return ne({validate:!1,allow_conditional_comments:!0,comment:function(e){c.comment(e)},cdata:function(e){c.cdata(e)},text:function(e,t){c.text(e,t)},start:function(e,t,r){switch(e){case"video":case"object":case"embed":case"img":case"iframe":i.height!==undefined&&i.width!==undefined&&y(t,{width:i.width,height:i.height})}if(o)switch(e){case"video":y(t,{poster:i.poster,src:""}),i.source2&&y(t,{src:""});break;case"iframe":y(t,{src:i.source1});break;case"source":if(++u<=2&&(y(t,{src:i["source"+u],type:i["source"+u+"mime"]}),!i["source"+u]))return;break;case"img":if(!i.poster)return;a=!0}c.start(e,t,r)},end:function(e){if("video"===e&&o)for(var t=1;t<=2;t++)if(i["source"+t]){var r=[];r.map={},u<t&&(y(r,{src:i["source"+t],type:i["source"+t+"mime"]}),c.start("source",r,!0))}if(i.poster&&"object"===e&&o&&!a){var n=[];n.map={},y(n,{src:i.poster,width:i.width,height:i.height}),c.start("img",n,!0)}c.end(e)}},le({})).parse(e),c.getContent()}(e,t,r)},fe=[{regex:/youtu\.be\/([\w\-_\?&=.]+)/i,type:"iframe",w:560,h:314,url:"//www.youtube.com/embed/$1",allowFullscreen:!0},{regex:/youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?/i,type:"iframe",w:560,h:314,url:"//www.youtube.com/embed/$2?$4",allowFullscreen:!0},{regex:/youtube.com\/embed\/([a-z0-9\?&=\-_]+)/i,type:"iframe",w:560,h:314,url:"//www.youtube.com/embed/$1",allowFullscreen:!0},{regex:/vimeo\.com\/([0-9]+)/,type:"iframe",w:425,h:350,url:"//player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc",allowFullscreen:!0},{regex:/vimeo\.com\/(.*)\/([0-9]+)/,type:"iframe",w:425,h:350,url:"//player.vimeo.com/video/$2?title=0&amp;byline=0",allowFullscreen:!0},{regex:/maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/,type:"iframe",w:425,h:350,url:'//maps.google.com/maps/ms?msid=$2&output=embed"',allowFullscreen:!1},{regex:/dailymotion\.com\/video\/([^_]+)/,type:"iframe",w:480,h:270,url:"//www.dailymotion.com/embed/video/$1",allowFullscreen:!0},{regex:/dai\.ly\/([^_]+)/,type:"iframe",w:480,h:270,url:"//www.dailymotion.com/embed/video/$1",allowFullscreen:!0}],he={},pe=function(e,t){var r=Y(e);return r?function(n,i,o){return new ce(function(t,e){function r(e){return e.html&&(he[n.source1]=e),t({url:n.source1,html:e.html?e.html:i(n)})}he[n.source1]?r(he[n.source1]):o({url:n.source1},r,e)})}(t,O(e),r):function(t,r){return new ce(function(e){e({html:r(t),url:t.source1})})}(t,O(e))},ge=function(e){return he.hasOwnProperty(e)},ve=function(n){function i(e){return A(e.getData())}var e=function(e){var t=e.selection.getNode(),r=function(e){return e.getAttribute("data-mce-object")||e.getAttribute("data-ephox-embed-iri")}(t)?e.serializer.serialize(t,{selection:!0}):"";return q({embed:r},w(J(e),r))}(n),r=H(e),t=S(e),o={title:"General",name:"general",items:function(e){for(var t=[],r=0,n=e.length;r<n;++r){if(!U(e[r]))throw new Error("Arr.flatten item "+r+" was not an array, input: "+e);W.apply(t,e[r])}return t}([[{name:"source1",type:"urlinput",filetype:"media",label:"Source"}],te(n)?[{type:"sizeinput",name:"dimensions",label:"Constrain proportions",constrain:!0}]:[]])},a={title:"Embed",items:[{type:"textarea",name:"embed",label:"Paste your embed code below:"}]},c=[];Z(n)&&c.push({name:"source2",type:"urlinput",filetype:"media",label:"Alternative source URL"}),ee(n)&&c.push({name:"poster",type:"urlinput",filetype:"image",label:"Media poster (Image URL)"});var u={title:"Advanced",name:"advanced",items:c},s=[o,a];0<c.length&&s.push(u);var l={type:"tabpanel",tabs:s},m=n.windowManager.open({title:"Insert/Edit Media",size:"normal",body:l,buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],onSubmit:function(e){var t=i(e);!function(e,t,r){t.embed=de(t.embed,t),t.embed&&(e.source1===t.source1||ge(t.source1))?F(r,t.embed):pe(r,t).then(function(e){F(r,e.html)})["catch"](_(r))}(r.get(),t,n),e.close()},onChange:function(e,t){switch(t.name){case"source1":!function(e,t){var r=i(t);e.source1!==r.source1&&(M(m,n)({url:r.source1,html:""}),pe(n,r).then(M(m,n))["catch"](_(n)))}(r.get(),e);break;case"embed":!function(e){var t=A(e.getData()),r=C(n,t.embed);e.setData(S(r))}(e);break;case"dimensions":case"poster":!function(e){var t=i(e),r=j(n,t);e.setData(S(d(d({},t),{embed:r})))}(e)}r.set(i(e))},initialData:t})},be=function(e){return{showDialog:function(){ve(e)}}},we=function(e){e.addCommand("mceMedia",function(){ve(e)})},ye=tinymce.util.Tools.resolve("tinymce.html.Node"),xe=tinymce.util.Tools.resolve("tinymce.Env"),je=function(i,e){if(!1===X(i))return e;var o,a=se();return ne({validate:!1,allow_conditional_comments:!1,comment:function(e){a.comment(e)},cdata:function(e){a.cdata(e)},text:function(e,t){a.text(e,t)},start:function(e,t,r){if(o=!0,"script"!==e&&"noscript"!==e){for(var n=0;n<t.length;n++){if(0===t[n].name.indexOf("on"))return;"style"===t[n].name&&(t[n].value=i.dom.serializeStyle(i.dom.parseStyle(t[n].value),e))}a.start(e,t,r),o=!1}},end:function(e){o||a.end(e)}},le({})).parse(e),a.getContent()},Oe=function(e,t,r){var n,i,o,a,c;for(a=(o=t.attributes).length;a--;)n=o[a].name,i=o[a].value,"width"!==n&&"height"!==n&&"style"!==n&&("data"!==n&&"src"!==n||(i=e.convertURL(i,n)),r.attr("data-mce-p-"+n,i));(c=t.firstChild&&t.firstChild.value)&&(r.attr("data-mce-html",escape(je(e,c))),r.firstChild=null)},Ae=function(i){return function(e){for(var t,r,n=e.length;n--;)(t=e[n]).parent&&(t.parent.attr("data-mce-object")||"script"===t.name&&!(r=v(J(i),t.attr("src")))||(r&&(r.width&&t.attr("width",r.width.toString()),r.height&&t.attr("height",r.height.toString())),"iframe"===t.name&&V(i)&&xe.ceFalse?T(t)||t.replace(k(i,t)):T(t)||t.replace(P(i,t))))}},Se=function(d){d.on("preInit",function(){var t=d.schema.getSpecialElements();re.each("video audio iframe object".split(" "),function(e){t[e]=new RegExp("</"+e+"[^>]*>","gi")});var r=d.schema.getBoolAttrs();re.each("webkitallowfullscreen mozallowfullscreen allowfullscreen".split(" "),function(e){r[e]={}}),d.parser.addNodeFilter("iframe,video,audio,object,embed,script",Ae(d)),d.serializer.addAttributeFilter("data-mce-object",function(e,t){for(var r,n,i,o,a,c,u,s,l=e.length;l--;)if((r=e[l]).parent){for(u=r.attr(t),n=new ye(u,1),"audio"!==u&&"script"!==u&&((s=r.attr("class"))&&-1!==s.indexOf("mce-preview-object")?n.attr({width:r.firstChild.attr("width"),height:r.firstChild.attr("height")}):n.attr({width:r.attr("width"),height:r.attr("height")})),n.attr({style:r.attr("style")}),i=(o=r.attributes).length;i--;){var m=o[i].name;0===m.indexOf("data-mce-p-")&&n.attr(m.substr(11),o[i].value)}"script"===u&&n.attr("type","text/javascript"),(a=r.attr("data-mce-html"))&&((c=new ye("#text",3)).raw=!0,c.value=je(d,unescape(a)),n.append(c)),r.replace(n)}})}),d.on("SetContent",function(){d.$("span.mce-preview-object").each(function(e,t){var r=d.$(t);0===r.find("span.mce-shim").length&&r.append('<span class="mce-shim"></span>')})})},_e=function(e){e.on("ResolveName",function(e){var t;1===e.target.nodeType&&(t=e.target.getAttribute("data-mce-object"))&&(e.name=t)})},Ce=function(t){t.on("click keyup touchend",function(){var e=t.selection.getNode();e&&t.dom.hasClass(e,"mce-preview-object")&&t.dom.getAttrib(e,"data-mce-selected")&&e.setAttribute("data-mce-selected","2")}),t.on("ObjectSelected",function(e){var t=e.target.getAttribute("data-mce-object");"audio"!==t&&"script"!==t||e.preventDefault()}),t.on("ObjectResized",function(e){var t,r=e.target;r.getAttribute("data-mce-object")&&(t=r.getAttribute("data-mce-html"))&&(t=unescape(t),r.setAttribute("data-mce-html",escape(de(t,{width:String(e.width),height:String(e.height)}))))})},Me=function(e){e.ui.registry.addToggleButton("media",{tooltip:"Insert/edit media",icon:"embed",onAction:function(){e.execCommand("mceMedia")},onSetup:function(t,r){return function(e){return t.selection.selectorChangedWithUnbind(r.join(","),e.setActive).unbind}}(e,["img[data-mce-object]","span[data-mce-object]","div[data-ephox-embed-iri]"])}),e.ui.registry.addMenuItem("media",{icon:"embed",text:"Media...",onAction:function(){e.execCommand("mceMedia")}})};!function Fe(){n.add("media",function(e){return we(e),Me(e),_e(e),Se(e),Ce(e),be(e)})}()}();
define({ "map": { "error": "Impossível criar mapa" }, "tools": { "search": { "error": "A localização não pode ser encontrada", "notWhatYouWanted": "Não é o que queria?", "selectAnother": "Selecionar outra localização", "currentLocation": "Localização Atual", "title": "localização" }, "legend": "Legenda", "about": "Sobre" } });
// (C) Copyright 2015 Martin Dougiamas // // 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. angular.module('mm.core') /** * Provider with some 'util' functionalities. * * @module mm.core * @ngdoc provider * @name $mmUtil */ .provider('$mmUtil', function(mmCoreSecondsYear, mmCoreSecondsDay, mmCoreSecondsHour, mmCoreSecondsMinute) { var self = this, // Use 'self' to be coherent with the rest of services. provider = this; // To access provider methods from the service. /** * Serialize an object to be used in a request. * * @module mm.core * @ngdoc method * @name $mmUtilProvider#param * @param {Object} obj Object to serialize. * @return {String} Serialization of the object. */ self.param = function(obj) { var query = '', name, value, fullSubName, subName, subValue, innerObj, i; for (name in obj) { value = obj[name]; if (value instanceof Array) { for (i = 0; i < value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += self.param(innerObj) + '&'; } } else if (value instanceof Object) { for (subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += self.param(innerObj) + '&'; } } else if (value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } return query.length ? query.substr(0, query.length - 1) : query; }; this.$get = function($ionicLoading, $ionicPopup, $injector, $translate, $http, $log, $q, $mmLang, $mmFS, $timeout, $mmApp, $mmText, mmCoreWifiDownloadThreshold, mmCoreDownloadThreshold, $ionicScrollDelegate, $mmWS, $cordovaInAppBrowser, $mmConfig, mmCoreSettingsRichTextEditor) { $log = $log.getInstance('$mmUtil'); var self = {}, // Use 'self' to be coherent with the rest of services. matchesFn, inputSupportKeyboard = ['date', 'datetime', 'datetime-local', 'email', 'month', 'number', 'password', 'search', 'tel', 'text', 'time', 'url', 'week']; /** * Formats a URL, trim, lowercase, etc... * * @module mm.core * @ngdoc method * @name $mmUtil#formatURL * @param {String} url The url to be formatted. * @return {String} Fromatted url. */ self.formatURL = function(url) { url = url.trim(); // Check if the URL starts by http or https. if (! /^http(s)?\:\/\/.*/i.test(url)) { // Test first allways https. url = "https://" + url; } // http allways in lowercase. url = url.replace(/^http/i, 'http'); url = url.replace(/^https/i, 'https'); // Replace last slash. url = url.replace(/\/$/, ""); return url; }; /** * Resolves an object. * * @description * This is used to resolve what a callback should be when attached to a delegate. * For instance, if the object attached is a function, it is returned as is, but * we also support complex definition of objects. If we receive a string we will parse * it and to inject its service using $injector from Angular. * * Examples: * - (Function): returns the same function. * - (Object): returns the same object. * - '$mmSomething': Injects and returns $mmSomething. * - '$mmSomething.method': Injectes and returns a reference to the function 'method'. * * @module mm.core * @ngdoc method * @name $mmUtil#resolveObject * @param {Mixed} object String, object or function. * @param {Boolean} [instantiate=false] When true, if the object resolved is a function, instantiates it. * @return {Object} The reference to the object resolved. */ self.resolveObject = function(object, instantiate) { var toInject, resolved; instantiate = angular.isUndefined(instantiate) ? false : instantiate; if (angular.isFunction(object) || angular.isObject(object)) { resolved = object; } else if (angular.isString(object)) { toInject = object.split('.'); resolved = $injector.get(toInject[0]); if (toInject.length > 1) { resolved = resolved[toInject[1]]; } } if (angular.isFunction(resolved) && instantiate) { resolved = resolved(); } if (typeof resolved === 'undefined') { throw new Error('Unexpected argument object passed'); } return resolved; }; /** * Returns if a URL is downloadable: plugin file OR theme/image.php OR gravatar. * * @module mm.core * @ngdoc method * @name $mmUtil#isDownloadableUrl * @param {String} url The URL to test. * @return {Boolean} True when the URL is downloadable. */ self.isDownloadableUrl = function(url) { return self.isPluginFileUrl(url) || self.isThemeImageUrl(url) || self.isGravatarUrl(url); }; /** * Returns if a URL is a gravatar URL. * * @module mm.core * @ngdoc method * @name $mmUtil#isGravatarUrl * @param {String} url The URL to test. * @return {Boolean} True when the URL is a gravatar URL. */ self.isGravatarUrl = function(url) { return url && url.indexOf('gravatar.com/avatar') !== -1; }; /** * Returns if a URL is a pluginfile URL. * * @module mm.core * @ngdoc method * @name $mmUtil#isPluginFileUrl * @param {String} url The URL to test. * @return {Boolean} True when the URL is a pluginfile URL. */ self.isPluginFileUrl = function(url) { return url && url.indexOf('/pluginfile.php') !== -1; }; /** * Returns if a URL is a theme image URL. * * @module mm.core * @ngdoc method * @name $mmUtil#isThemeImageUrl * @param {String} url The URL to test. * @return {Boolean} True when the URL is a theme image URL. */ self.isThemeImageUrl = function(url) { return url && url.indexOf('/theme/image.php') !== -1; }; /** * Validates a URL for a specific pattern. * * @module mm.core * @ngdoc method * @name $mmUtil#isValidURL * @param {String} url The url to test against the pattern * @return {Boolean} TRUE if the url matches the expected pattern. * FALSE otherwise. */ self.isValidURL = function(url) { return /^http(s)?\:\/\/.+/i.test(url); }; /** * Generic function for adding the wstoken to Moodle urls and for pointing to the correct script. * For download remote files from Moodle we need to use the special /webservice/pluginfile passing * the ws token as a get parameter. * * @module mm.core * @ngdoc method * @name $mmUtil#fixPluginfileURL * @param {String} url The url to be fixed. * @param {String} token Token to use. * @return {String} Fixed URL. */ self.fixPluginfileURL = function(url, token) { // This function is used in regexp callbacks, better not to risk!! if (!url) { return ''; } // First check if we need to fix this url or is already fixed. if (url.indexOf('token=') != -1) { return url; } // Check if is a valid URL (contains the pluginfile endpoint). if (url.indexOf('pluginfile') == -1) { return url; } if (!token) { return ''; } // In which way the server is serving the files? Are we using slash parameters? if (url.indexOf('?file=') != -1 || url.indexOf('?forcedownload=') != -1 || url.indexOf('?rev=') != -1) { url += '&'; } else { url += '?'; } url += 'token=' + token; // Some webservices returns directly the correct download url, others not. if (url.indexOf('/webservice/pluginfile') == -1) { url = url.replace('/pluginfile', '/webservice/pluginfile'); } return url; }; /** * Open a file using platform specific method. * * node-webkit: Using the default application configured. * Android: Using the WebIntent plugin. * iOs: Using handleDocumentWithURL. * * @module mm.core * @ngdoc method * @name $mmUtil#openFile * @param {String} path The local path of the file to be open. * @return {Void} * @todo Restore node-webkit support. */ self.openFile = function(path) { var deferred = $q.defer(); if (window.plugins) { var extension = $mmFS.getFileExtension(path), mimetype = $mmFS.getMimeType(extension); if (ionic.Platform.isAndroid() && window.plugins.webintent) { var iParams = { action: "android.intent.action.VIEW", url: path, type: mimetype }; window.plugins.webintent.startActivity( iParams, function() { $log.debug('Intent launched'); deferred.resolve(); }, function() { $log.debug('Intent launching failed.'); $log.debug('action: ' + iParams.action); $log.debug('url: ' + iParams.url); $log.debug('type: ' + iParams.type); if (!extension || extension.indexOf('/') > -1 || extension.indexOf('\\') > -1) { // Extension not found. $mmLang.translateAndRejectDeferred(deferred, 'mm.core.erroropenfilenoextension'); } else { $mmLang.translateAndRejectDeferred(deferred, 'mm.core.erroropenfilenoapp'); } } ); } else if (ionic.Platform.isIOS() && typeof handleDocumentWithURL == 'function') { $mmFS.getBasePath().then(function(fsRoot) { // Encode/decode the specific file path, note that a path may contain directories // with white spaces, special characters... if (path.indexOf(fsRoot > -1)) { path = path.replace(fsRoot, ""); path = encodeURIComponent(decodeURIComponent(path)); path = fsRoot + path; } handleDocumentWithURL( function() { $log.debug('File opened with handleDocumentWithURL' + path); deferred.resolve(); }, function(error) { $log.debug('Error opening with handleDocumentWithURL' + path); if(error == 53) { $log.error('No app that handles this file type.'); } self.openInBrowser(path); deferred.resolve(); }, path ); }, deferred.reject); } else { // Last try, launch the file with the browser. self.openInBrowser(path); deferred.resolve(); } } else { // Changing _blank for _system may work in cordova 2.4 and onwards. $log.debug('Opening external file using window.open()'); window.open(path, '_blank'); deferred.resolve(); } return deferred.promise; }; /** * Open a URL using a browser. * * Do not use for files, refer to {@link $mmUtil#openFile}. * * @module mm.core * @ngdoc method * @name $mmUtil#openInBrowser * @param {String} url The URL to open. * @return {Void} */ self.openInBrowser = function(url) { window.open(url, '_system'); }; /** * Open a URL using InAppBrowser. * * Do not use for files, refer to {@link $mmUtil#openFile}. * * @module mm.core * @ngdoc method * @name $mmUtil#openInApp * @param {String} url The URL to open. * @param {Object} options Override default options passed to $cordovaInAppBrowser#open * @return {Void} */ self.openInApp = function(url, options) { if (!url) { return; } options = options || {}; if (!options.enableViewPortScale) { options.enableViewPortScale = 'yes'; // Enable zoom on iOS. } if (!options.location && ionic.Platform.isIOS() && url.indexOf('file://') === 0) { // The URL uses file protocol, don't show it on iOS. // In Android we keep it because otherwise we lose the whole toolbar. options.location = 'no'; } $cordovaInAppBrowser.open(url, '_blank', options); }; /** * Close the InAppBrowser window. * * @module mm.core * @ngdoc method * @name $mmUtil#closeInAppBrowser * @return {Void} */ self.closeInAppBrowser = function() { $cordovaInAppBrowser.close(); }; /** * Open an online file using platform specific method. * Specially useful for audio and video since they can be streamed. * * node-webkit: Using the default application configured. * Android: Using the WebIntent plugin. * iOS: Using the window.open method (InAppBrowser) * We don't use iOS quickview framework because it doesn't support streaming. * * @module mm.core * @ngdoc method * @name $mmUtil#openOnlineFile * @param {String} url The URL of the file. * @return {Promise} Promise resolved when opened. * @todo Restore node-webkit support. */ self.openOnlineFile = function(url) { var deferred = $q.defer(); if (ionic.Platform.isAndroid() && window.plugins && window.plugins.webintent) { // In Android we need the mimetype to open it. var extension, iParams; $mmWS.getRemoteFileMimeType(url).then(function(mimetype) { if (!mimetype) { // Couldn't retireve mimetype. Try to guess it. extension = $mmFS.guessExtensionFromUrl(url); mimetype = $mmFS.getMimeType(extension); } iParams = { action: "android.intent.action.VIEW", url: url, type: mimetype }; window.plugins.webintent.startActivity( iParams, function() { $log.debug('Intent launched'); deferred.resolve(); }, function() { $log.debug('Intent launching failed.'); $log.debug('action: ' + iParams.action); $log.debug('url: ' + iParams.url); $log.debug('type: ' + iParams.type); if (!extension || extension.indexOf('/') > -1 || extension.indexOf('\\') > -1) { // Extension not found. $mmLang.translateAndRejectDeferred(deferred, 'mm.core.erroropenfilenoextension'); } else { $mmLang.translateAndRejectDeferred(deferred, 'mm.core.erroropenfilenoapp'); } } ); }); } else { $log.debug('Opening remote file using window.open()'); window.open(url, '_blank'); deferred.resolve(); } return deferred.promise; }; /** * Get the mimetype of a file given its URL. It'll perform a HEAD request to get it, if that * fails it'll try to guess it using the URL. * * @module mm.core * @ngdoc method * @name $mmUtil#getMimeType * @param {String} url The URL of the file. * @return {Promise} Promise resolved with the mimetype. */ self.getMimeType = function(url) { return $mmWS.getRemoteFileMimeType(url).then(function(mimetype) { if (!mimetype) { // Couldn't retireve mimetype. Try to guess it. extension = $mmFS.guessExtensionFromUrl(url); mimetype = $mmFS.getMimeType(extension); } return mimetype || ''; }); }; /** * Displays a loading modal window. * * @module mm.core * @ngdoc method * @name $mmUtil#showModalLoading * @param {String} text The text of the modal window. * @param {Boolean} needsTranslate True if the 'text' is a $translate key, false otherwise. * @return {Object} Object with a 'dismiss' function to close the modal. * @description * Usage: * var modal = $mmUtil.showModalLoading(myText); * ... * modal.dismiss(); */ self.showModalLoading = function(text, needsTranslate) { var modalClosed = false, modalShown = false, showModalPromise; if (!text) { text = 'mm.core.loading'; needsTranslate = true; } function showModal(text) { if (!modalClosed) { $ionicLoading.show({ template: '<ion-spinner></ion-spinner>' + '<p>'+text+'</p>' }); // Leave some delay before setting modalShown to true. // @todo In Ionic 1.3.1 $ionicLoading returns a promise, we should use that promise instead of a delay. showModalPromise = $timeout(function() { showModalPromise = null; if (!modalClosed) { modalShown = true; } }, 200); } } if (needsTranslate) { $translate(text).then(showModal); } else { showModal(text); } return { dismiss: function() { modalClosed = true; if (showModalPromise) { // Modal is being shown. Wait for it to be shown and hide it. showModalPromise.finally(function() { $ionicLoading.hide(); }); } else if (modalShown) { // Modal shown, hide it. $ionicLoading.hide(); } } }; }; /** * Displays a loading modal window using a certain template. * * @module mm.core * @ngdoc method * @name $mmUtil#showModalLoadingWithTemplate * @param {String} [template] Template to use in the modal. * @param {Object} [options] Options. See http://ionicframework.com/docs/api/service/$ionicLoading/ * @return {Object} Object with a 'dismiss' function to close the modal. * @description * Usage: * var modal = $mmUtil.showModalLoadingWithTemplate(template); * ... * modal.dismiss(); */ self.showModalLoadingWithTemplate = function(template, options) { options = options || {}; if (!template) { template = "<ion-spinner></ion-spinner><p>{{'mm.core.loading' | translate}}</p>"; } options.template = template; $ionicLoading.show(options); return { dismiss: function() { $ionicLoading.hide(); } }; }; /** * Show a modal with an error message. * * @module mm.core * @ngdoc method * @name $mmUtil#showErrorModal * @param {String} errorMessage Message to show. * @param {Boolean} needsTranslate True if the errorMessage is a $translate key, false otherwise. * @param {Number} [autocloseTime] Number of milliseconds to wait to close the modal. * If not defined, modal won't be automatically closed. */ self.showErrorModal = function(errorMessage, needsTranslate, autocloseTime) { var errorKey = 'mm.core.error', langKeys = [errorKey], matches; if (angular.isObject(errorMessage)) { // We received an object instead of a string. Search for common properties. if (typeof errorMessage.content != 'undefined') { errorMessage = errorMessage.content; } else if (typeof errorMessage.body != 'undefined') { errorMessage = errorMessage.body; } else if (typeof errorMessage.message != 'undefined') { errorMessage = errorMessage.message; } else if (typeof errorMessage.error != 'undefined') { errorMessage = errorMessage.error; } else { // No common properties found, just stringify it. errorMessage = JSON.stringify(errorMessage); } // Try to remove tokens from the contents. matches = errorMessage.match(/token"?[=|:]"?(\w*)/, ''); if (matches && matches[1]) { errorMessage = errorMessage.replace(new RegExp(matches[1], 'g'), 'secret'); } } if (needsTranslate) { langKeys.push(errorMessage); } $translate(langKeys).then(function(translations) { var popup = $ionicPopup.alert({ title: translations[errorKey], template: needsTranslate ? translations[errorMessage] : errorMessage }); if (typeof autocloseTime != 'undefined' && !isNaN(parseInt(autocloseTime))) { $timeout(function() { popup.close(); }, parseInt(autocloseTime)); } else { delete popup; } }); }; /** * Show a modal with an error message. * * @module mm.core * @ngdoc method * @name $mmUtil#showModal * @param {String} title Language key. * @param {String} message Language key. */ self.showModal = function(title, message) { var promises = [ $translate(title), $translate(message), ]; $q.all(promises).then(function(translations) { $ionicPopup.alert({ title: translations[0], template: translations[1] }); }); }; /** * Show a confirm modal. * * @module mm.core * @ngdoc method * @name $mmUtil#showConfirm * @param {Mixed} template Template to show in the modal body. Can be a string or a promise. * @param {String} [title] Title of the modal. * @param {Object} [options] More options. See http://ionicframework.com/docs/api/service/$ionicPopup/ * @return {Promise} Promise resolved if the user confirms and rejected if he cancels. */ self.showConfirm = function(template, title, options) { options = options || {}; options.template = template; options.title = title; return $ionicPopup.confirm(options).then(function(confirmed) { if (!confirmed) { return $q.reject(); } }); }; /** * Show a prompt modal to input some data. * * @module mm.core * @ngdoc method * @name $mmUtil#showPrompt * @param {String} body Modal body. * @param {String} title Modal title. * @param {String} inputPlaceholder Placeholder of the input box. By default, "Password". * @param {String} [inputType] Type of the input box. By default, password. * @return {Promise} Promise resolved with the input data if the user clicks OK, rejected if cancels. */ self.showPrompt = function(body, title, inputPlaceholder, inputType) { inputType = inputType || 'password'; var options = { template: body, title: title, inputPlaceholder: inputPlaceholder, inputType: inputType }; return $ionicPopup.prompt(options).then(function(data) { if (typeof data == 'undefined') { return $q.reject(); } return data; }); }; /** * Reads and parses a JSON file. * * @module mm.core * @ngdoc method * @name $mmUtil#readJSONFile * @param {String} path Path to the file. * @return {Promise} Promise to be resolved when the file is parsed. */ self.readJSONFile = function(path) { return $http.get(path).then(function(response) { return response.data; }); }; /** * Get country name based on country code. * * @module mm.core * @ngdoc method * @name $mmUtil#getCountryName * @param {String} code Country code (AF, ES, US, ...). * @return {String} Country name. If the country is not found, return the country code. */ self.getCountryName = function(code) { var countryKey = 'mm.core.country-' + code, countryName = $translate.instant(countryKey); return countryName !== countryKey ? countryName : code; }; /** * Returns the URL to the documentation of the app, based on Moodle version and current language. * * @param {String} [release] Moodle release. * @param {String} [page] Docs page to go to. * @return {Promise} Promise resolved with the Moodle docs URL. */ self.getDocsUrl = function(release, page) { page = page || 'Mobile_app'; var docsurl = 'https://docs.moodle.org/en/' + page; if (typeof release != 'undefined') { var version = release.substr(0, 3).replace(".", ""); // Check is a valid number. if (parseInt(version) >= 24) { // Append release number. docsurl = docsurl.replace('https://docs.moodle.org/', 'https://docs.moodle.org/' + version + '/'); } } return $mmLang.getCurrentLanguage().then(function(lang) { return docsurl.replace('/en/', '/' + lang + '/'); }, function() { return docsurl; }); }; /** * Return the current timestamp (UNIX format, seconds). * * @module mm.core * @ngdoc method * @name $mmUtil#timestamp * @return {Number} The current timestamp in seconds. */ self.timestamp = function() { return Math.round(new Date().getTime() / 1000); }; /** * Return true if the param is false (bool), 0 (number) or "0" (string). * * @module mm.core * @ngdoc method * @name $mmUtil#isFalseOrZero * @param {Mixed} value Value to check. * @return {Number} True if value is false, 0 or "0". */ self.isFalseOrZero = function(value) { return typeof value != 'undefined' && (value === false || parseInt(value) === 0); }; /** * Return true if the param is true (bool), 1 (number) or "1" (string). * * @module mm.core * @ngdoc method * @name $mmUtil#isTrueOrOne * @param {Mixed} value Value to check. * @return {Number} True if value is true, 1 or "1". */ self.isTrueOrOne = function(value) { return typeof value != 'undefined' && (value === true || parseInt(value) === 1); }; /** * Returns hours, minutes and seconds in a human readable format * * @module mm.core * @ngdoc method * @name $mmUtil#formatTime * @param {Integer} seconds A number of seconds * @return {String} Human readable seconds formatted */ self.formatTime = function(seconds) { var langKeys = ['mm.core.day', 'mm.core.days', 'mm.core.hour', 'mm.core.hours', 'mm.core.min', 'mm.core.mins', 'mm.core.sec', 'mm.core.secs', 'mm.core.year', 'mm.core.years', 'mm.core.now']; return $translate(langKeys).then(function(translations) { totalSecs = Math.abs(seconds); var years = Math.floor(totalSecs / mmCoreSecondsYear); var remainder = totalSecs - (years * mmCoreSecondsYear); var days = Math.floor(remainder / mmCoreSecondsDay); remainder = totalSecs - (days * mmCoreSecondsDay); var hours = Math.floor(remainder / mmCoreSecondsHour); remainder = remainder - (hours * mmCoreSecondsHour); var mins = Math.floor(remainder / mmCoreSecondsMinute); var secs = remainder - (mins * mmCoreSecondsMinute); var ss = (secs == 1) ? translations['mm.core.sec'] : translations['mm.core.secs']; var sm = (mins == 1) ? translations['mm.core.min'] : translations['mm.core.mins']; var sh = (hours == 1) ? translations['mm.core.hour'] : translations['mm.core.hours']; var sd = (days == 1) ? translations['mm.core.day'] : translations['mm.core.days']; var sy = (years == 1) ? translations['mm.core.year'] : translations['mm.core.years']; var oyears = '', odays = '', ohours = '', omins = '', osecs = ''; if (years) { oyears = years + ' ' + sy; } if (days) { odays = days + ' ' + sd; } if (hours) { ohours = hours + ' ' + sh; } if (mins) { omins = mins + ' ' + sm; } if (secs) { osecs = secs + ' ' + ss; } if (years) { return oyears + ' ' + odays; } if (days) { return odays + ' ' + ohours; } if (hours) { return ohours + ' ' + omins; } if (mins) { return omins + ' ' + osecs; } if (secs) { return osecs; } return translations['mm.core.now']; }); }; /** * Returns hours, minutes and seconds in a human readable format * * @module mm.core * @ngdoc method * @name $mmUtil#formatDuration * @param {Integer} duration Duration in seconds * @param {Integer} [precission] Number of elements to have in precission. 0 or undefined to full precission. * @return {String} Full Human readable duration formatted */ self.formatDuration = function(duration, precission) { eventDuration = moment.duration(duration, 'seconds'); if (!precission) { precission = 5; } durationString = ""; if (precission && eventDuration.years() > 0) { durationString += " " + moment.duration(eventDuration.years(), 'years').humanize(); precission--; } if (precission && eventDuration.months() > 0) { durationString += " " + moment.duration(eventDuration.months(), 'months').humanize(); precission--; } if (precission && eventDuration.days() > 0) { durationString += " " + moment.duration(eventDuration.days(), 'days').humanize(); precission--; } if (precission && eventDuration.hours() > 0) { durationString += " " + moment.duration(eventDuration.hours(), 'hours').humanize(); precission--; } if (precission && eventDuration.minutes() > 0) { durationString += " " + moment.duration(eventDuration.minutes(), 'minutes').humanize(); precission--; } return durationString.trim(); }; /** * Empties an array without losing its reference. * * @module mm.core * @ngdoc method * @name $mmUtil#emptyArray * @param {Array} array Array to empty. */ self.emptyArray = function(array) { array.length = 0; // Empty array without losing its reference. }; /** * Removes all properties from an object without losing its reference. * * @module mm.core * @ngdoc method * @name $mmUtil#emptyObject * @param {Object} object Object to remove the properties. */ self.emptyObject = function(object) { for (var key in object) { if (object.hasOwnProperty(key)) { delete object[key]; } } }; /** * Similar to $q.all, but if a promise fails this function's promise won't be rejected until ALL promises have finished. * * @module mm.core * @ngdoc method * @name $mmUtil#allPromises * @param {Promise[]} promises Promises. * @return {Promise} Promise resolved if all promises are resolved and rejected if at least 1 promise fails. */ self.allPromises = function(promises) { if (!promises || !promises.length) { return $q.when(); } var count = 0, failed = false, deferred = $q.defer(); angular.forEach(promises, function(promise) { promise.catch(function() { failed = true; }).finally(function() { count++; if (count === promises.length) { // All promises have finished, reject/resolve. if (failed) { deferred.reject(); } else { deferred.resolve(); } } }); }); return deferred.promise; }; /** * Compare two objects. This function won't compare functions and proto properties, it's a basic compare. * Also, this will only check if itemA's properties are in itemB with same value. This function will still * return true if itemB has more properties than itemA. * * @module mm.core * @ngdoc method * @name $mmUtil#basicLeftCompare * @param {Mixed} itemA First object. * @param {Mixed} itemB Second object. * @param {Number} [maxLevels=0] Number of levels to reach if 2 objects are compared. * @param {Number} [level=0] Current deep level (when comparing objects). * @return {Boolean} True if equal, false otherwise. */ self.basicLeftCompare = function(itemA, itemB, maxLevels, level) { level = level || 0; maxLevels = maxLevels || 0; if (angular.isFunction(itemA) || angular.isFunction(itemB)) { return true; // Don't compare functions. } else if (angular.isObject(itemA) && angular.isObject(itemB)) { if (level >= maxLevels) { return true; // Max deep reached. } var equal = true; angular.forEach(itemA, function(value, name) { if (!self.basicLeftCompare(value, itemB[name], maxLevels, level + 1)) { equal = false; } }); return equal; } else { // We'll treat "2" and 2 as the same value. var floatA = parseFloat(itemA), floatB = parseFloat(itemB); if (!isNaN(floatA) && !isNaN(floatB)) { return floatA == floatB; } return itemA === itemB; } }; /** * If the download size is higher than a certain threshold shows a confirm dialog. * * @module mm.core * @ngdoc method * @name $mmUtil#confirmDownloadSize * @param {Object|Number} sizeCalc Containing size to download (in bytes) and a boolean to indicate if its * totaly or partialy calculated. * @param {String} [message] Code of the message to show. Default: 'mm.course.confirmdownload'. * @param {String} [unknownsizemessage] Code of the message to show if size is unknown. * Default: 'mm.course.confirmdownloadunknownsize'. * @param {Number} [wifiThreshold] Threshold to show confirm in WiFi connection. Default: mmCoreWifiDownloadThreshold. * @param {Number} [limitedThreshold] Threshold to show confirm in limited connection. Default: mmCoreDownloadThreshold. * @return {Promise} Promise resolved when the user confirms or if no confirm needed. */ self.confirmDownloadSize = function(sizeCalc, message, unknownsizemessage, wifiThreshold, limitedThreshold) { wifiThreshold = typeof wifiThreshold == 'undefined' ? mmCoreWifiDownloadThreshold : wifiThreshold; limitedThreshold = typeof limitedThreshold == 'undefined' ? mmCoreDownloadThreshold : limitedThreshold; // Backward compatibility conversion. if (typeof sizeCalc == 'number') { sizeCalc = {size: sizeCalc, total: false}; } if (sizeCalc.size < 0 || (sizeCalc.size == 0 && !sizeCalc.total)) { // Seems size was unable to be calculated. Show a warning. unknownsizemessage = unknownsizemessage || 'mm.course.confirmdownloadunknownsize'; return self.showConfirm($translate(unknownsizemessage)); } else if (!sizeCalc.total) { // Filesize is only partial. var readableSize = $mmText.bytesToSize(sizeCalc.size, 2); return self.showConfirm($translate('mm.course.confirmpartialdownloadsize', {size: readableSize})); } else if (sizeCalc.size >= wifiThreshold || ($mmApp.isNetworkAccessLimited() && sizeCalc.size >= limitedThreshold)) { message = message || 'mm.course.confirmdownload'; var readableSize = $mmText.bytesToSize(sizeCalc.size, 2); return self.showConfirm($translate(message, {size: readableSize})); } return $q.when(); }; /** * Sum the filesizes from a list of files checking if the size will be partial or totally calculated. * * @module mm.core * @ngdoc method * @name $mmUtil#sumFileSizes * @param {Array} files List of files to sum its filesize. * @return {Object} With the file size and a boolean to indicate if it is the total size or only partial. */ self.sumFileSizes = function(files) { var results = { size: 0, total: true }; angular.forEach(files, function(file) { if (typeof file.filesize == 'undefined') { // We don't have the file size, cannot calculate its total size. results.total = false; } else { results.size += file.filesize; } }); return results; }; /** * Formats a size to be used as width/height of an element. * If the size is already valid (like '500px' or '50%') it won't be modified. * Returned size will have a format like '500px'. * * @module mm.core * @ngdoc method * @name $mmUtil#formatPixelsSize * @param {Mixed} size Size to format. * @return {String} Formatted size. If size is not valid, returns an empty string. */ self.formatPixelsSize = function(size) { if (typeof size == 'string' && (size.indexOf('px') > -1 || size.indexOf('%') > -1)) { // It seems to be a valid size. return size; } size = parseInt(size, 10); if (!isNaN(size)) { return size + 'px'; } return ''; }; /** * Serialize an object to be used in a request. * * @module mm.core * @ngdoc method * @name $mmUtil#param * @param {Object} obj Object to serialize. * @return {String} Serialization of the object. */ self.param = function(obj) { return provider.param(obj); }; /** * Rounds a number to use a certain amout of decimals or less. * Difference between this function and float's toFixed: * 7.toFixed(2) -> 7.00 * roundToDecimals(7, 2) -> 7 * * @module mm.core * @ngdoc method * @name $mmUtil#roundToDecimals * @param {Float} number Float to round. * @param {Number} [decimals=2] Number of decimals. By default, 2. * @return {Float} Rounded number. */ self.roundToDecimals = function(number, decimals) { if (typeof decimals == 'undefined') { decimals = 2; } var multiplier = Math.pow(10, decimals); return Math.round(parseFloat(number) * multiplier) / multiplier; }; /** * Extracts the parameters from a URL and stores them in an object. * * @module mm.core * @ngdoc method * @name $mmUtil#extractUrlParams * @param {String} url URL to treat. * @return {Object} Object with the params. */ self.extractUrlParams = function(url) { var regex = /[?&]+([^=&]+)=?([^&]*)?/gi, params = {}; url.replace(regex, function(match, key, value) { params[key] = value !== undefined ? value : ''; }); return params; }; /** * Given an HTML, searched all links and media and tries to restore original sources using the paths object. * * @module mm.core * @ngdoc method * @name $mmUtil#restoreSourcesInHtml * @param {String} html HTML code. * @param {Object} paths Object linking URLs in the html code with the real URLs to use. * @param {Function} [anchorFn] Function to call with each anchor. Optional. * @return {String} Treated HTML code. */ self.restoreSourcesInHtml = function(html, paths, anchorFn) { var div = angular.element('<div>'), media; div.html(html); // Treat img, audio, video and source. media = div[0].querySelectorAll('img, video, audio, source'); angular.forEach(media, function(el) { var src = paths[decodeURIComponent(el.getAttribute('src'))]; if (typeof src !== 'undefined') { el.setAttribute('src', src); } }); // We do the same for links. angular.forEach(div.find('a'), function(anchor) { var href = decodeURIComponent(anchor.getAttribute('href')), url = paths[href]; if (typeof url !== 'undefined') { anchor.setAttribute('href', url); if (angular.isFunction(anchorFn)) { anchorFn(anchor, href); } } }); return div.html(); }; /** * Scroll to a certain element inside another element. * This is done this way because using anchorScroll or $location.hash sticks the scroll to go upwards. * * @module mm.core * @ngdoc method * @name $mmUtil#scrollToElement * @param {Object} container Element to search in. * @param {String} [selector] Selector to find the element to scroll to. If not defined, scroll to the container. * @param {Object} [scrollDelegate] Scroll delegate. If not defined, use $ionicScrollDelegate. * @param {String} [scrollParentClass] Scroll Parent Class where to stop calculating the position. Default scroll-content. * @return {Boolean} True if the element is found, false otherwise. */ self.scrollToElement = function(container, selector, scrollDelegate, scrollParentClass) { var position; if (!scrollDelegate) { scrollDelegate = $ionicScrollDelegate; } position = self.getElementXY(container, selector, scrollParentClass); if (!position) { return false; } scrollDelegate.scrollTo(position[0], position[1]); return true; }; /** * Retrieve the position of a element relative to another element. * * @module mm.core * @ngdoc method * @name $mmUtil#getElementXY * @param {Object} container Element to search in. * @param {String} [selector] Selector to find the element to scroll to. If not defined, scroll to the container. * @param {String} [scrollParentClass] Scroll Parent Class where to stop calculating the position. Default scroll-content. * @return {Array} positionLeft, positionTop of the element relative to. */ self.getElementXY = function(container, selector, positionParentClass) { var element = selector ? container.querySelector(selector) : container, offsetElement, positionTop = 0, positionLeft = 0; if (!positionParentClass) { positionParentClass = 'scroll-content'; } if (!element) { return false; } while (element) { positionLeft += (element.offsetLeft - element.scrollLeft + element.clientLeft); positionTop += (element.offsetTop - element.scrollTop + element.clientTop); offsetElement = element.offsetParent; element = element.parentElement; // Every parent class has to be checked but the position has to be got form offsetParent. while (offsetElement != element && element) { // If positionParentClass element is reached, stop adding tops. if (angular.element(element).hasClass(positionParentClass)) { element = false; } else { element = element.parentElement; } } // Finally, check again. if (angular.element(element).hasClass(positionParentClass)) { element = false; } } return [positionLeft, positionTop]; }; /** * Search all the URLs in a CSS file content. * * @module mm.core * @ngdoc method * @name $mmUtil#extractUrlsFromCSS * @param {String} code CSS code. * @return {String[]} List of URLs. */ self.extractUrlsFromCSS = function(code) { // First of all, search all the url(...) occurrences that don't include "data:". var urls = [], matches = code.match(/url\(\s*["']?(?!data:)([^)]+)\)/igm); // Extract the URL form each match. angular.forEach(matches, function(match) { var submatches = match.match(/url\(\s*['"]?([^'"]*)['"]?\s*\)/im); if (submatches && submatches[1]) { urls.push(submatches[1]); } }); return urls; }; /** * Returns the contents of a certain selection in a DOM element. * * @module mm.core * @ngdoc method * @name $mmUtil#getContentsOfElement * @param {Object} element DOM element to search in. * @param {String} selector Selector to search. * @return {String} Selection contents. Undefined if not found. */ self.getContentsOfElement = function(element, selector) { if (element) { var el = element[0] || element, // Convert from jqLite to plain JS if needed. selected = el.querySelector(selector); if (selected) { return selected.innerHTML; } } }; /** * Search and remove a certain element from inside another element. * * @module mm.core * @ngdoc method * @name $mmUtil#removeElement * @param {Object} element DOM element to search in. * @param {String} selector Selector to search. * @return {Void} */ self.removeElement = function(element, selector) { if (element) { var el = element[0] || element, // Convert from jqLite to plain JS if needed. selected = el.querySelector(selector); if (selected) { angular.element(selected).remove(); } } }; /** * Search and remove a certain element from an HTML code. * * @module mm.core * @ngdoc method * @name $mmUtil#removeElementFromHtml * @param {String} html HTML code to change. * @param {String} selector Selector to search. * @param {Boolean} removeAll True if it should remove all matches found, false if it should only remove the first one. * @return {String} HTML without the element. */ self.removeElementFromHtml = function(html, selector, removeAll) { // Create a fake div element so we can search using querySelector. var div = document.createElement('div'), selected; div.innerHTML = html; if (removeAll) { selected = div.querySelectorAll(selector); angular.forEach(selected, function(el) { angular.element(el).remove(); }); } else { selected = div.querySelector(selector); if (selected) { angular.element(selected).remove(); } } return div.innerHTML; }; /** * Search for certain classes in an element contents and replace them with the specified new values. * * @module mm.core * @ngdoc method * @name $mmUtil#replaceClassesInElement * @param {Object} element DOM element. * @param {Object} map Mapping of the classes to replace. Keys must be the value to replace, values must be * the new class name. Example: {'correct': 'mm-question-answer-correct'}. * @return {Void} */ self.replaceClassesInElement = function(element, map) { element = element[0] || element; // Convert from jqLite to plain JS if needed. angular.forEach(map, function(newValue, toReplace) { var matches = element.querySelectorAll('.' + toReplace); angular.forEach(matches, function(element) { element.className = element.className.replace(toReplace, newValue); }); }); }; /** * Equivalent to element.closest(). If the browser doesn't support element.closest, it will * traverse the parents to achieve the same functionality. * Returns the closest ancestor of the current element (or the current element itself) which matches the selector. * * @module mm.core * @ngdoc method * @name $mmUtil#closest * @param {Object} element DOM Element. * @param {String} selector Selector to search. * @return {Object} Closest ancestor. */ self.closest = function(element, selector) { // Try to use closest if the browser supports it. if (typeof element.closest == 'function') { return element.closest(selector); } if (!matchesFn) { // Find the matches function supported by the browser. ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) { if (typeof document.body[fn] == 'function') { matchesFn = fn; return true; } return false; }); if (!matchesFn) { return; } } // Traverse parents. while (element) { if (element[matchesFn](selector)) { return element; } element = element.parentElement; } }; /** * Extract the downloadable URLs from an HTML. * * @module mm.core * @ngdoc method * @name $mmUtil#extractDownloadableFilesFromHtml * @param {String} html HTML code. * @return {String[]} List of file urls. */ self.extractDownloadableFilesFromHtml = function(html) { var div = document.createElement('div'), elements, urls = []; div.innerHTML = html; elements = div.querySelectorAll('a, img, audio, video, source'); angular.forEach(elements, function(element) { var url = element.tagName === 'A' ? element.href : element.src; if (url && self.isDownloadableUrl(url) && urls.indexOf(url) == -1) { urls.push(url); } }); return urls; }; /** * Extract the downloadable URLs from an HTML and returns them in fake file objects. * * @module mm.core * @ngdoc method * @name $mmUtil#extractDownloadableFilesFromHtmlAsFakeFileObjects * @param {String} html HTML code. * @return {Object[]} List of fake file objects with file URLs. */ self.extractDownloadableFilesFromHtmlAsFakeFileObjects = function(html) { var urls = self.extractDownloadableFilesFromHtml(html); // Convert them to fake file objects. return urls.map(function(url) { return { fileurl: url }; }); }; /** * Converts an object into an array of objects, where each entry is an object containing * the key and value of the original object. * For example, it can convert {size: 2} into [{name: 'size', value: 2}]. * * @module mm.core * @ngdoc method * @name $mmUtil#objectToArrayOfObjects * @param {Object} obj Object to convert. * @param {String} keyName Name of the properties where to store the keys. * @param {String} valueName Name of the properties where to store the values. * @param {Boolean} sort True to sort keys alphabetically, false otherwise. * @return {Object[]} Array of objects with the name & value of each property. */ self.objectToArrayOfObjects = function(obj, keyName, valueName, sort) { var result = [], keys = Object.keys(obj); if (sort) { keys = keys.sort(); } angular.forEach(keys, function(key) { var entry = {}; entry[keyName] = key; entry[valueName] = obj[key]; result.push(entry); }); return result; }; /** * Tests to see whether two arrays or objects have the same value at a particular key. * Missing values are replaced by '', and the values are compared with ===. * Booleans and numbers are cast to string before comparing. * * @module mm.core * @ngdoc method * @name $mmUtil#sameAtKeyMissingIsBlank * @param {Object} obj1 The first object or array. * @param {Object} obj2 The second object or array. * @param {String} key Key to check. * @return {Boolean} Whether the two objects/arrays have the same value (or lack of one) for a given key. */ self.sameAtKeyMissingIsBlank = function(obj1, obj2, key) { var value1 = typeof obj1[key] != 'undefined' ? obj1[key] : '', value2 = typeof obj2[key] != 'undefined' ? obj2[key] : ''; if (typeof value1 == 'number' || typeof value1 == 'boolean') { value1 = '' + value1; } if (typeof value2 == 'number' || typeof value2 == 'boolean') { value2 = '' + value2; } return value1 === value2; }; /** * Merge two arrays, removing duplicate values. * * @module mm.core * @ngdoc method * @name $mmUtil#mergeArraysWithoutDuplicates * @param {Array} array1 The first array. * @param {Array} array2 The second array. * @return {Array} Merged array. */ self.mergeArraysWithoutDuplicates = function(array1, array2) { return self.uniqueArray(array1.concat(array2)); }; /** * Return an array without duplicate values. * * @module mm.core * @ngdoc method * @name $mmUtil#uniqueArray * @param {Array} array The array to treat. * @return {Array} Array without duplicate values. */ self.uniqueArray = function(array) { var unique = [], len = array.length; for (var i = 0; i < len; i++) { var value = array[i]; if (unique.indexOf(value) == -1) { unique.push(value); } } return unique; }; /** * Given an error returned by a WS call (site.read, site.write), * check if the error is generated by the app or it has been returned by the WebSwervice. * * @module mm.core * @ngdoc method * @name $mmUtil#isWebServiceError * @param {String} error Error returned. * @return {Boolean} True if the error was returned by the WebService, false otherwise. */ self.isWebServiceError = function(error) { var localErrors = [ $translate.instant('mm.core.wsfunctionnotavailable'), $translate.instant('mm.core.lostconnection'), $translate.instant('mm.core.userdeleted'), $translate.instant('mm.core.unexpectederror'), $translate.instant('mm.core.networkerrormsg'), $translate.instant('mm.core.serverconnection'), $translate.instant('mm.core.errorinvalidresponse'), $translate.instant('mm.core.sitemaintenance'), $translate.instant('mm.core.upgraderunning'), $translate.instant('mm.core.nopasswordchangeforced') ]; return error && localErrors.indexOf(error) == -1; }; /** * Convenient helper to open change password page. * * @module mm.core * @ngdoc method * @name $mmUtil#openChangePassword * @param {String} siteurl Site URL to construct change password URL. * @param {String} error Error message. */ self.openChangePassword = function(siteurl, error) { var message = error + "<br>" + $translate.instant('mm.login.visitchangepassword'); self.showConfirm(message, $translate.instant('mm.core.notice')).then(function() { var changepasswordurl = siteurl + "/login/change_password.php"; self.openInApp(changepasswordurl); }); }; /** * Focus an element and open keyboard. * * @module mm.core * @ngdoc method * @name $mmUtil#focusElement * @param {Object} el DOM element to focus. * @return {Void} */ self.focusElement = function(el) { if (el && el.focus) { el.focus(); if (ionic.Platform.isAndroid() && self.supportsInputKeyboard(el)) { // On some Android versions the keyboard doesn't open automatically. $mmApp.openKeyboard(); } } }; /** * Check if an element supports input via keyboard. * * @module mm.core * @ngdoc method * @name $mmUtil#supportsInputKeyboard * @param {Object} el DOM element to check. * @return {Boolean} True if supports input using keyboard. */ self.supportsInputKeyboard = function(el) { return el && !el.disabled && (el.tagName.toLowerCase() == 'textarea' || (el.tagName.toLowerCase() == 'input' && inputSupportKeyboard.indexOf(el.type) != -1)); }; /** * Check if rich text editor is supported in the platform. * * @module mm.core * @ngdoc method * @name $mmUtil#isRichTextEditorSupported * @return {Boolean} True if supported, false otherwise. */ self.isRichTextEditorSupported = function() { // Enabled for all platforms different from iOS and Android. if (!ionic.Platform.isIOS() && !ionic.Platform.isAndroid()) { return true; } // Check Android version >= 4.4 if (ionic.Platform.isAndroid() && ionic.Platform.version() >= 4.4) { return true; } return false; }; /** * Check if rich text editor is enabled. * * @module mm.core * @ngdoc method * @name $mmUtil#isRichTextEditorEnabled * @return {Promise} Promise resolved with boolean: true if enabled, false otherwise. */ self.isRichTextEditorEnabled = function() { if (self.isRichTextEditorSupported()) { return $mmConfig.get(mmCoreSettingsRichTextEditor, true); } return $q.when(false); }; /** * Given a list of files, check if there are repeated names. * * @module mm.core * @ngdoc method * @name $mmUtil#hasRepeatedFilenames * @param {Object[]} files List of files. * @return {Mixed} String with error message if repeated, false if no repeated. */ self.hasRepeatedFilenames = function(files) { if (!files || !files.length) { return false; } var names = []; // Check if there are 2 files with the same name. for (var i = 0; i < files.length; i++) { var name = files[i].filename || files[i].name; if (names.indexOf(name) > -1) { return $translate.instant('mm.core.filenameexist', {$a: name}); } else { names.push(name); } } return false; }; return self; }; });
import React, { Component } from 'react'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; } render() { return ( <div className="search-bar"> <input value={this.state.term} onChange={event => this.onInputChange(event.target.value)} /> </div> ); } onInputChange(term) { this.setState({ term }); this.props.onSearchTermChange(term); } } export default SearchBar;
import React from "react" import { graphql } from "gatsby" import contentParser from "gatsby-wpgraphql-inline-images" const Post = props => { const pluginOptions = { wordPressUrl: `http://wpgraphql.local/`, uploadsUrl: `http://wpgraphql.local/wp-content/uploads/`, } const { // location, pageContext: { content, }, data: { wpgraphql: { support: { title } }, }, } = props return ( <div> <h1>{title}</h1> <div> {contentParser({ content }, pluginOptions)} </div> </div> ) } export default Post export const pageQuery = graphql` query GET_POST($id: ID!) { wpgraphql { support(id: $id) { title content } } } `
// app.js App({ onLaunch() { // 在应用程序启动时获取系统信息 const systemInfo = wx.getSystemInfoSync() // 屏幕宽度、高度不会变,没有必要去使用响应式的全局状态管理 hy-event-store,直接存在 app 的 globalData 中即可 this.globalData.screenWidth = systemInfo.screenWidth this.globalData.screenHeight = systemInfo.screenHeight }, globalData: { screenWidth: 0, screenHeight: 0 } })
import React, { useState } from 'react' import { useSelector, useDispatch } from 'react-redux' import { useNavigation } from '@react-navigation/native' import { View, ScrollView, VStack, FormControl, Input, Button, Text, Avatar } from 'native-base' import { updateUser } from '../features/auth' import Container from '../elements/Container' export default () => { const navigation = useNavigation() const { token, user } = useSelector((state) => state.auth) const dispatch = useDispatch() const [firstName, setFirstName] = useState(user.firstName) const [lastName, setLastName] = useState(user.lastName) const [email, setEmail] = useState(user.email) const [errors, setErrors] = useState({}) const validate = () => { if (firstName.length < 3) { setErrors({ ...errors, firstName: 'First name is too short', }) return false } if (lastName.length < 3) { setErrors({ ...errors, lastName: 'Last name is too short', }) return false } const emailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ if (!email.match(emailformat)) { setErrors({ ...errors, email: 'Email address is not valid', }) return false } return true } const onSave = () => { if (validate()) { const params = { firstName, lastName, email, } dispatch(updateUser({ token, id: user._id, params })) navigation.navigate('Profile') } } return ( <ScrollView contentContainerStyle={{ flexGrow: 1 }}> <View variant="wrapper"> <Container> <VStack flex={1} justifyContent="space-between" space={6} px={3} py={6}> <VStack space={3}> <Avatar source={{ uri: user.image }} size="2xl" alt="user portrait" position="relative" alignSelf="center" borderRadius="full" /> <FormControl> <FormControl.Label _text={{ bold: true }}>First name</FormControl.Label> <Input value={firstName} onChangeText={(value) => setFirstName(value)} bg="warmGray.100" size="md" /> {'firstName' in errors && ( <Text fontSize="xs" color="error.500" fontWeight={500}> {errors.firstName} </Text> )} </FormControl> <FormControl> <FormControl.Label _text={{ bold: true }}>Last name</FormControl.Label> <Input value={lastName} onChangeText={(value) => setLastName(value)} bg="warmGray.100" size="md" /> {'lastName' in errors && ( <Text fontSize="xs" color="error.500" fontWeight={500}> {errors.lastName} </Text> )} </FormControl> <FormControl> <FormControl.Label _text={{ bold: true }}>Email</FormControl.Label> <Input value={email} onChangeText={(value) => setEmail(value)} bg="warmGray.100" size="md" /> {'email' in errors && ( <Text fontSize="xs" color="error.500" fontWeight={500}> {errors.email} </Text> )} </FormControl> </VStack> <Button onPress={onSave} size="fixed" alignSelf="center"> Save </Button> </VStack> </Container> </View> </ScrollView> ) }
global.scriptsFolder = __dirname + "/../scripts/"; global.pagesFolder = __dirname + "/../gh-pages/"; global.winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { colorize: true, timestamp: true }); var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var github = require('./routes/github'); var app = express(); if (process.env.environment == "development") { app.use('/admin', express.static(path.join(__dirname, '/client/'))); app.use('/admin', express.static(path.join(__dirname, '/client/.tmp'))); app.use('/admin', express.static(path.join(__dirname, '/client/app'))); } if (process.env.environment == 'production') { app.use('/admin', express.static(path.join(__dirname, '/dist'))); } // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json({limit: '5mb'})); app.use(bodyParser.urlencoded({ extended: false, limit:'5mb' })); app.use(cookieParser()); app.use('/github', github); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers module.exports = app;
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Story from './../Story/index'; import { switchMode } from './actions'; import SplashScreen from '../Story/StoryLoader'; const editMode = () => <Story storyMode="edit" />; const viewMode = () => <Story storyMode="view" />; const mixedMode = () => ( <div className="Mixed"> <style global jsx>{` .Mixed { display: flex; flex-direction: row; } `}</style> <Story storyMode="edit" /> <Story storyMode="view" /> </div> ); const getMode = ({ mode }) => { switch (mode) { case 'edit': return editMode(); case 'view': return viewMode(); case 'mixed': return mixedMode(); default: return mixedMode(); } }; class Mode extends React.Component { constructor(props) { super(props); const buttons = [ { mode: 'edit', text: 'Edit', icon: 'fa-pencil' }, { mode: 'view', text: 'View', icon: 'fa-eye' }, { mode: 'mixed', text: 'Mixed', icon: 'fa-balance-scale' } ]; this.switchButtons = buttons.map(({ mode, text, icon }) => ( <button className="Label" key={mode} id={mode} onClick={this._switchMode}> <i className={`fa ${icon}`} aria-hidden="true" /> {text} </button> )); } _switchMode = ({ target }) => { this.props.switchMode(target.id); }; render() { const { mode, story } = this.props; return ( <div> <style jsx global>{` .Label { color: #555; cursor: pointer; background: #e2e2e2; padding: 0.5em; margin: 0.5em; border-radius: 3px; box-shadow: none; border: none; font-size: 1em; } .Label > i { margin-right: 0.5em; } `}</style> <div className="Bar"> {story.loaded && this.switchButtons} <SplashScreen /> </div> <style jsx>{` .Bar { position: fixed; padding: 0; top: 0; left: 0; right: 0; height: auto; background: #333; z-index: 2; } `}</style> {story.loaded ? ( getMode(mode) ) : ( <div style={{ textAlign: 'center', padding: '2em' }}> Please choose a JSON story file. </div> )} </div> ); } } export default connect( state => state, dispatch => bindActionCreators({ switchMode }, dispatch) )(Mode);
function tabuada() { let num = document.getElementById('txtn') let tab = document.getElementById('seltab') if (num.value.length == 0) { window.alert(' Por favor digite um número') } else { let n = Number(num.value) lent = c = 1 tab.innerHTML = ' ' while (c <= 10) { let iten = document.createElement('option') iten.text = `${n} x ${c} = ${n*c}` iten.value = `tab${c}` tab.appendChild(iten) c++ } } }
export class StarRatingView { constructor(element) { this.element = element; this.inputElement = element.querySelector("input"); this.createUI(); this.listenForStarMouseEvents(); } createUI() { const min = parseInt(this.inputElement.min, 10); const max = parseInt(this.inputElement.max, 10); this.starElements = []; for (let rating = min; rating <= max; rating++) { const starElement = this.createStarElement(rating); this.element.appendChild(starElement); this.starElements.push(starElement); } this.inputElement.style.display = "none"; } createStarElement(rating) { const starElement = document.createElement("div"); starElement.setAttribute("class", "star"); starElement.ratingValue = rating; return starElement; } listenForStarMouseEvents() { // Add event listener to the container element. // The events of child star elements will bubble up. this.element.addEventListener("click", this.starClicked.bind(this), false); this.element.addEventListener("mouseover", this.starMousedOver.bind(this), false); this.element.addEventListener("mouseout", this.starMousedOut.bind(this), false); } starClicked(e) { const element = e.srcElement || e.target; if (!element.classList.contains("star")) return; this.setRating(element.ratingValue); } starMousedOver(e) { // Mousing over a star will toggle the "hover" state for it and all preceeding stars. const element = e.srcElement || e.target; if (!element.classList.contains("star")) return; this.setHoverState(element.ratingValue); } starMousedOut(e) { const element = e.srcElement || e.target; if (!element.classList.contains("star")) return; this.removeHoverStates(); } setHoverState(rating) { for (let i = 0; i < rating; i++) { this.starElements[i].classList.add("hover"); } } removeHoverStates() { for (let i = 0, length = this.starElements.length; i < length; i++) { this.starElements[i].classList.remove("hover"); } } setRating(rating) { this.inputElement.value = rating; let index; const max = this.starElements.length; for (index = 0; index < rating; index++) { this.starElements[index].classList.add("selected"); } for (index = rating; index < max; index++) { this.starElements[index].classList.remove("selected"); } } } // SIG // Begin signature block // SIG // MIIaVgYJKoZIhvcNAQcCoIIaRzCCGkMCAQExCzAJBgUr // SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB // SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB // SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFIU+wdoqOupY // SIG // eEoHF9gdYGKQYQ2MoIIVJjCCBJkwggOBoAMCAQICEzMA // SIG // AACdHo0nrrjz2DgAAQAAAJ0wDQYJKoZIhvcNAQEFBQAw // SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj // SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwHhcNMTIwOTA0 // SIG // MjE0MjA5WhcNMTMwMzA0MjE0MjA5WjCBgzELMAkGA1UE // SIG // BhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV // SIG // BAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD // SIG // b3Jwb3JhdGlvbjENMAsGA1UECxMETU9QUjEeMBwGA1UE // SIG // AxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkq // SIG // hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqRJbBD7Ipxl // SIG // ohaYO8thYvp0Ka2NBhnScVgZil5XDWlibjagTv0ieeAd // SIG // xxphjvr8oxElFsjAWCwxioiuMh6I238+dFf3haQ2U8pB // SIG // 72m4aZ5tVutu5LImTXPRZHG0H9ZhhIgAIe9oWINbSY+0 // SIG // 39M11svZMJ9T/HprmoQrtyFndNT2eLZhh5iUfCrPZ+kZ // SIG // vtm6Y+08Tj59Auvzf6/PD7eBfvT76PeRSLuPPYzIB5Mc // SIG // 87115PxjICmfOfNBVDgeVGRAtISqN67zAIziDfqhsg8i // SIG // taeprtYXuTDwAiMgEPprWQ/grZ+eYIGTA0wNm2IZs7uW // SIG // vJFapniGdptszUzsErU4RwIDAQABo4IBDTCCAQkwEwYD // SIG // VR0lBAwwCgYIKwYBBQUHAwMwHQYDVR0OBBYEFN5R3Bvy // SIG // HkoFPxIcwbzDs2UskQWYMB8GA1UdIwQYMBaAFMsR6MrS // SIG // tBZYAck3LjMWFrlMmgofMFYGA1UdHwRPME0wS6BJoEeG // SIG // RWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js // SIG // L3Byb2R1Y3RzL01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEw // SIG // LmNybDBaBggrBgEFBQcBAQROMEwwSgYIKwYBBQUHMAKG // SIG // Pmh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2Vy // SIG // dHMvTWljQ29kU2lnUENBXzA4LTMxLTIwMTAuY3J0MA0G // SIG // CSqGSIb3DQEBBQUAA4IBAQAqpPfuwMMmeoNiGnicW8X9 // SIG // 7BXEp3gT0RdTKAsMAEI/OA+J3GQZhDV/SLnP63qJoc1P // SIG // qeC77UcQ/hfah4kQ0UwVoPAR/9qWz2TPgf0zp8N4k+R8 // SIG // 1W2HcdYcYeLMTmS3cz/5eyc09lI/R0PADoFwU8GWAaJL // SIG // u78qA3d7bvvQRooXKDGlBeMWirjxSmkVXTP533+UPEdF // SIG // Ha7Ki8f3iB7q/pEMn08HCe0mkm6zlBkB+F+B567aiY9/ // SIG // Wl6EX7W+fEblR6/+WCuRf4fcRh9RlczDYqG1x1/ryWlc // SIG // cZGpjVYgLDpOk/2bBo+tivhofju6eUKTOUn10F7scI1C // SIG // dcWCVZAbtVVhMIIEujCCA6KgAwIBAgIKYQKSSgAAAAAA // SIG // IDANBgkqhkiG9w0BAQUFADB3MQswCQYDVQQGEwJVUzET // SIG // MBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVk // SIG // bW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0 // SIG // aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFt // SIG // cCBQQ0EwHhcNMTIwMTA5MjIyNTU5WhcNMTMwNDA5MjIy // SIG // NTU5WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldh // SIG // c2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNV // SIG // BAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjENMAsGA1UE // SIG // CxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO // SIG // OkI4RUMtMzBBNC03MTQ0MSUwIwYDVQQDExxNaWNyb3Nv // SIG // ZnQgVGltZS1TdGFtcCBTZXJ2aWNlMIIBIjANBgkqhkiG // SIG // 9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWPD96K1R9n5OZRT // SIG // rGuPpnk4IfTRbj0VOBbBcyyZj/vgPFvhokyLsquLtPJK // SIG // x7mTUNEm9YdTsHp180cPFytnLGTrYOdKjOCLXsRWaTc6 // SIG // KgRdFwHIv6m308mro5GogeM/LbfY5MR4AHk5z/3HZOIj // SIG // EnieDHYnSY+arA504wZVVUnI7aF8cEVhfrJxFh7hwUG5 // SIG // 0tIy6VIk8zZQBNfdbzxJ1QvUdkD8ZWUTfpVROtX/uJqn // SIG // V2tLFeU3WB/cAA3FrurfgUf58FKu5s9arOAUSqZxlID6 // SIG // /bAjMGDpg2CsDiQe/xHy56VVYpXun3+eKdbNSwp2g/BD // SIG // BN8GSSDyU1pEsFF6OQIDAQABo4IBCTCCAQUwHQYDVR0O // SIG // BBYEFM0ZrGFNlGcr9q+UdVnb8FgAg6E6MB8GA1UdIwQY // SIG // MBaAFCM0+NlSRnAK7UD7dvuzK7DDNbMPMFQGA1UdHwRN // SIG // MEswSaBHoEWGQ2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNv // SIG // bS9wa2kvY3JsL3Byb2R1Y3RzL01pY3Jvc29mdFRpbWVT // SIG // dGFtcFBDQS5jcmwwWAYIKwYBBQUHAQEETDBKMEgGCCsG // SIG // AQUFBzAChjxodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20v // SIG // cGtpL2NlcnRzL01pY3Jvc29mdFRpbWVTdGFtcFBDQS5j // SIG // cnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcN // SIG // AQEFBQADggEBAFEc1t82HdyAvAKnxpnfFsiQBmkVmjK5 // SIG // 82QQ0orzYikbeY/KYKmzXcTkFi01jESb8fRcYaRBrpqL // SIG // ulDRanlqs2KMnU1RUAupjtS/ohDAR9VOdVKJHj+Wao8u // SIG // QBQGcu4/cFmSXYXtg5n6goSe5AMBIROrJ9bMcUnl2h3/ // SIG // bzwJTtWNZugMyX/uMRQCN197aeyJPkV/JUTnHxrWxRrD // SIG // SuTh8YSY50/5qZinGEbshGzsqQMK/Xx6Uh2ca6SoD5iS // SIG // pJJ4XCt4432yx9m2cH3fW3NTv6rUZlBL8Mk7lYXlwUpl // SIG // nSVYULsgVJF5OhsHXGpXKK8xx5/nwx3uR/0n13/PdNxl // SIG // xT8wggW8MIIDpKADAgECAgphMyYaAAAAAAAxMA0GCSqG // SIG // SIb3DQEBBQUAMF8xEzARBgoJkiaJk/IsZAEZFgNjb20x // SIG // GTAXBgoJkiaJk/IsZAEZFgltaWNyb3NvZnQxLTArBgNV // SIG // BAMTJE1pY3Jvc29mdCBSb290IENlcnRpZmljYXRlIEF1 // SIG // dGhvcml0eTAeFw0xMDA4MzEyMjE5MzJaFw0yMDA4MzEy // SIG // MjI5MzJaMHkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpX // SIG // YXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYD // SIG // VQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xIzAhBgNV // SIG // BAMTGk1pY3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBMIIB // SIG // IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsnJZ // SIG // XBkwZL8dmmAgIEKZdlNsPhvWb8zL8epr/pcWEODfOnSD // SIG // GrcvoDLs/97CQk4j1XIA2zVXConKriBJ9PBorE1LjaW9 // SIG // eUtxm0cH2v0l3511iM+qc0R/14Hb873yNqTJXEXcr609 // SIG // 4CholxqnpXJzVvEXlOT9NZRyoNZ2Xx53RYOFOBbQc1sF // SIG // umdSjaWyaS/aGQv+knQp4nYvVN0UMFn40o1i/cvJX0Yx // SIG // ULknE+RAMM9yKRAoIsc3Tj2gMj2QzaE4BoVcTlaCKCoF // SIG // MrdL109j59ItYvFFPeesCAD2RqGe0VuMJlPoeqpK8kbP // SIG // Nzw4nrR3XKUXno3LEY9WPMGsCV8D0wIDAQABo4IBXjCC // SIG // AVowDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUyxHo // SIG // ytK0FlgByTcuMxYWuUyaCh8wCwYDVR0PBAQDAgGGMBIG // SIG // CSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYBBAGCNxUCBBYE // SIG // FP3RMU7TJoqV4ZhgO6gxb6Y8vNgtMBkGCSsGAQQBgjcU // SIG // AgQMHgoAUwB1AGIAQwBBMB8GA1UdIwQYMBaAFA6sgmBA // SIG // VieX5SUT/CrhClOVWeSkMFAGA1UdHwRJMEcwRaBDoEGG // SIG // P2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js // SIG // L3Byb2R1Y3RzL21pY3Jvc29mdHJvb3RjZXJ0LmNybDBU // SIG // BggrBgEFBQcBAQRIMEYwRAYIKwYBBQUHMAKGOGh0dHA6 // SIG // Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWlj // SIG // cm9zb2Z0Um9vdENlcnQuY3J0MA0GCSqGSIb3DQEBBQUA // SIG // A4ICAQBZOT5/Jkav629AsTK1ausOL26oSffrX3XtTDst // SIG // 10OtC/7L6S0xoyPMfFCYgCFdrD0vTLqiqFac43C7uLT4 // SIG // ebVJcvc+6kF/yuEMF2nLpZwgLfoLUMRWzS3jStK8cOeo // SIG // DaIDpVbguIpLV/KVQpzx8+/u44YfNDy4VprwUyOFKqSC // SIG // HJPilAcd8uJO+IyhyugTpZFOyBvSj3KVKnFtmxr4HPBT // SIG // 1mfMIv9cHc2ijL0nsnljVkSiUc356aNYVt2bAkVEL1/0 // SIG // 2q7UgjJu/KSVE+Traeepoiy+yCsQDmWOmdv1ovoSJgll // SIG // OJTxeh9Ku9HhVujQeJYYXMk1Fl/dkx1Jji2+rTREHO4Q // SIG // FRoAXd01WyHOmMcJ7oUOjE9tDhNOPXwpSJxy0fNsysHs // SIG // cKNXkld9lI2gG0gDWvfPo2cKdKU27S0vF8jmcjcS9G+x // SIG // PGeC+VKyjTMWZR4Oit0Q3mT0b85G1NMX6XnEBLTT+yzf // SIG // H4qerAr7EydAreT54al/RrsHYEdlYEBOsELsTu2zdnnY // SIG // CjQJbRyAMR/iDlTd5aH75UcQrWSY/1AWLny/BSF64pVB // SIG // J2nDk4+VyY3YmyGuDVyc8KKuhmiDDGotu3ZrAB2WrfIW // SIG // e/YWgyS5iM9qqEcxL5rc43E91wB+YkfRzojJuBj6DnKN // SIG // waM9rwJAav9pm5biEKgQtDdQCNbDPTCCBgcwggPvoAMC // SIG // AQICCmEWaDQAAAAAABwwDQYJKoZIhvcNAQEFBQAwXzET // SIG // MBEGCgmSJomT8ixkARkWA2NvbTEZMBcGCgmSJomT8ixk // SIG // ARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWljcm9zb2Z0 // SIG // IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTA3 // SIG // MDQwMzEyNTMwOVoXDTIxMDQwMzEzMDMwOVowdzELMAkG // SIG // A1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAO // SIG // BgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29m // SIG // dCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWljcm9zb2Z0 // SIG // IFRpbWUtU3RhbXAgUENBMIIBIjANBgkqhkiG9w0BAQEF // SIG // AAOCAQ8AMIIBCgKCAQEAn6Fssd/bSJIqfGsuGeG94uPF // SIG // mVEjUK3O3RhOJA/u0afRTK10MCAR6wfVVJUVSZQbQpKu // SIG // mFwwJtoAa+h7veyJBw/3DgSY8InMH8szJIed8vRnHCz8 // SIG // e+eIHernTqOhwSNTyo36Rc8J0F6v0LBCBKL5pmyTZ9co // SIG // 3EZTsIbQ5ShGLieshk9VUgzkAyz7apCQMG6H81kwnfp+ // SIG // 1pez6CGXfvjSE/MIt1NtUrRFkJ9IAEpHZhEnKWaol+TT // SIG // BoFKovmEpxFHFAmCn4TtVXj+AZodUAiFABAwRu233iNG // SIG // u8QtVJ+vHnhBMXfMm987g5OhYQK1HQ2x/PebsgHOIktU // SIG // //kFw8IgCwIDAQABo4IBqzCCAacwDwYDVR0TAQH/BAUw // SIG // AwEB/zAdBgNVHQ4EFgQUIzT42VJGcArtQPt2+7MrsMM1 // SIG // sw8wCwYDVR0PBAQDAgGGMBAGCSsGAQQBgjcVAQQDAgEA // SIG // MIGYBgNVHSMEgZAwgY2AFA6sgmBAVieX5SUT/CrhClOV // SIG // WeSkoWOkYTBfMRMwEQYKCZImiZPyLGQBGRYDY29tMRkw // SIG // FwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0wKwYDVQQD // SIG // EyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRo // SIG // b3JpdHmCEHmtFqFKoKWtTHNY9AcTLmUwUAYDVR0fBEkw // SIG // RzBFoEOgQYY/aHR0cDovL2NybC5taWNyb3NvZnQuY29t // SIG // L3BraS9jcmwvcHJvZHVjdHMvbWljcm9zb2Z0cm9vdGNl // SIG // cnQuY3JsMFQGCCsGAQUFBwEBBEgwRjBEBggrBgEFBQcw // SIG // AoY4aHR0cDovL3d3dy5taWNyb3NvZnQuY29tL3BraS9j // SIG // ZXJ0cy9NaWNyb3NvZnRSb290Q2VydC5jcnQwEwYDVR0l // SIG // BAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcNAQEFBQADggIB // SIG // ABCXisNcA0Q23em0rXfbznlRTQGxLnRxW20ME6vOvnuP // SIG // uC7UEqKMbWK4VwLLTiATUJndekDiV7uvWJoc4R0Bhqy7 // SIG // ePKL0Ow7Ae7ivo8KBciNSOLwUxXdT6uS5OeNatWAweaU // SIG // 8gYvhQPpkSokInD79vzkeJkuDfcH4nC8GE6djmsKcpW4 // SIG // oTmcZy3FUQ7qYlw/FpiLID/iBxoy+cwxSnYxPStyC8jq // SIG // cD3/hQoT38IKYY7w17gX606Lf8U1K16jv+u8fQtCe9RT // SIG // ciHuMMq7eGVcWwEXChQO0toUmPU8uWZYsy0v5/mFhsxR // SIG // VuidcJRsrDlM1PZ5v6oYemIp76KbKTQGdxpiyT0ebR+C // SIG // 8AvHLLvPQ7Pl+ex9teOkqHQ1uE7FcSMSJnYLPFKMcVpG // SIG // QxS8s7OwTWfIn0L/gHkhgJ4VMGboQhJeGsieIiHQQ+kr // SIG // 6bv0SMws1NgygEwmKkgkX1rqVu+m3pmdyjpvvYEndAYR // SIG // 7nYhv5uCwSdUtrFqPYmhdmG0bqETpr+qR/ASb/2KMmyy // SIG // /t9RyIwjyWa9nR2HEmQCPS2vWY+45CHltbDKY7R4VAXU // SIG // QS5QrJSwpXirs6CWdRrZkocTdSIvMqgIbqBbjCW/oO+E // SIG // yiHW6x5PyZruSeD3AWVviQt9yGnI5m7qp5fOMSn/DsVb // SIG // XNhNG6HY+i+ePy5VFmvJE6P9MYIEnDCCBJgCAQEwgZAw // SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj // SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0ECEzMAAACdHo0n // SIG // rrjz2DgAAQAAAJ0wCQYFKw4DAhoFAKCBvjAZBgkqhkiG // SIG // 9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgEL // SIG // MQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQU // SIG // Nt5IbhKp3Pda+XseiuYa6NPtYr4wXgYKKwYBBAGCNwIB // SIG // DDFQME6gJoAkAE0AaQBjAHIAbwBzAG8AZgB0ACAATABl // SIG // AGEAcgBuAGkAbgBnoSSAImh0dHA6Ly93d3cubWljcm9z // SIG // b2Z0LmNvbS9sZWFybmluZyAwDQYJKoZIhvcNAQEBBQAE // SIG // ggEAuIFa/FoPUsBlYCquD3jpW1RN9hUo17vm54GMJBWk // SIG // pUFSta0xEqpnwivWZPlGt5DreMQ6w/woHplD4SlEZ4aY // SIG // BLFnVddP3lNPS2g0hzeo0vCtIjbiFAKOqP+nYdF7Up6S // SIG // rkqjNxSd6tPvJFSmoAIPwljWxuGusoQN/jqRsvvg4vyc // SIG // 8bFAvNPzphFM1YUiq1lMTbi3/ZtVop0MDKlPmmiIpeln // SIG // 0X7HZyGFy4g+r8aVzuBamJp+rHw8hs/KbV7BOtp8FZ0A // SIG // gbUwfaj1pe4gVcnLwBLlX+0DndJIDNhXx01YzgT4nK79 // SIG // qx3CwkxwXvDEiWBoaoeC+vKxByaTNSymWeKh8aGCAh8w // SIG // ggIbBgkqhkiG9w0BCQYxggIMMIICCAIBATCBhTB3MQsw // SIG // CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ // SIG // MA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z // SIG // b2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3Nv // SIG // ZnQgVGltZS1TdGFtcCBQQ0ECCmECkkoAAAAAACAwCQYF // SIG // Kw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0B // SIG // BwEwHAYJKoZIhvcNAQkFMQ8XDTEyMTExNTAwMDgwOFow // SIG // IwYJKoZIhvcNAQkEMRYEFDr7feQDGEZN55yvPA7FY2qQ // SIG // JYh2MA0GCSqGSIb3DQEBBQUABIIBALF6VbjoFsMykGA9 // SIG // dgM/p0Ar1Rxp28kQo91bHvIuhjcQtPX6/6zOej8iGWHF // SIG // CimIaDODqt0KIzEIjHE9zbF34uhpxk01mkY84rPW58AX // SIG // LeEL9tfvqnu4wdMlQhD0OMqIEBdKzFhEEEkuanHptqpX // SIG // tJ+GApAGBUp3TDRvgBeTFFMLbxwr0+NILtdG5XxThXKl // SIG // Xku5YP5Qk/D77x1MY8hUYJsog0GQbjOf+otOF2hBA8aj // SIG // iDsz282Q1Bltyja2g/ikcMVUApFj1aYk3XI2gZtt8GrS // SIG // 4biHRXp8FjAPDmXLubnoTwkQ7U7OVLIRqwITV8JpjcBc // SIG // GXdEb9WfnD2lvhm+VbA= // SIG // End signature block
(function () { function d(a, b) { l.call(this, a, b); this.actualConfig = this.originalConfig = this.removedButtons = null; this.emptyVisible = !1; this.state = "edit"; this.toolbarButtons = [{ text: {active: "Hide empty toolbar groups", inactive: "Show empty toolbar groups"}, group: "edit", position: "left", cssClass: "button-a-soft", clickCallback: function (a, b) { a[a.hasClass("button-a-background") ? "removeClass" : "addClass"]("button-a-background"); this._toggleVisibilityEmptyElements(); this.emptyVisible ? a.setText(b.text.active) : a.setText(b.text.inactive) } }, { text: "Add row separator", group: "edit", position: "left", cssClass: "button-a-soft", clickCallback: function () { this._addSeparator() } }, { text: "Select config", group: "config", position: "left", cssClass: "button-a-soft", clickCallback: function () { this.configContainer.findOne("textarea").$.select() } }, { text: "Back to configurator", group: "config", position: "right", cssClass: "button-a-background", clickCallback: function () { if ("paste" === this.state) { var a = this.configContainer.findOne("textarea").getValue(); (a = d.evaluateToolbarGroupsConfig(a)) ? this.setConfig(a) : alert("Your pasted config is wrong.") } this.state = "edit"; this._showConfigurationTool(); this.showToolbarBtnsByGroupName(this.state) } }, { text: 'Get toolbar \x3cspan class\x3d"highlight"\x3econfig\x3c/span\x3e', group: "edit", position: "right", cssClass: "button-a-background icon-pos-left icon-download", clickCallback: function () { this.state = "config"; this._showConfig(); this.showToolbarBtnsByGroupName(this.state) } }]; this.cachedActiveElement = null } var l = ToolbarConfigurator.AbstractToolbarModifier; ToolbarConfigurator.ToolbarModifier = d; d.prototype = Object.create(ToolbarConfigurator.AbstractToolbarModifier.prototype); d.prototype.getActualConfig = function () { var a = l.prototype.getActualConfig.call(this); if (a.toolbarGroups)for (var b = a.toolbarGroups.length, c = 0; c < b; c += 1)a.toolbarGroups[c] = d.parseGroupToConfigValue(a.toolbarGroups[c]); return a }; d.prototype._onInit = function (a, b, c) { c = !0 === c; l.prototype._onInit.call(this, void 0, b); this.removedButtons = []; c ? this.removedButtons = this.actualConfig.removeButtons ? this.actualConfig.removeButtons.split(",") : [] : "removeButtons"in this.originalConfig ? this.removedButtons = this.originalConfig.removeButtons ? this.originalConfig.removeButtons.split(",") : [] : (this.originalConfig.removeButtons = "", this.removedButtons = []); this.actualConfig.toolbarGroups || (this.actualConfig.toolbarGroups = this.fullToolbarEditor.getFullToolbarGroupsConfig()); this._fixGroups(this.actualConfig); this._calculateTotalBtns(); this._createModifier(); this._refreshMoveBtnsAvalibility(); this._refreshBtnTabIndexes(); "function" === typeof a && a(this.mainContainer) }; d.prototype._showConfigurationTool = function () { this.configContainer.addClass("hidden"); this.modifyContainer.removeClass("hidden") }; d.prototype._showConfig = function () { var a = this.getActualConfig(), b, c; if (a.toolbarGroups) { b = a.toolbarGroups; for (var e = this.cfg.trimEmptyGroups, f = [], g = b.length, m = 0; m < g; m++) { var h = b[m]; if ("/" === h)f.push("'/'"); else { if (e)for (var k = h.groups.length; k--;)0 === d.getTotalSubGroupButtonsNumber(h.groups[k], this.fullToolbarEditor) && h.groups.splice(k, 1); e && 0 === h.groups.length || f.push(l.stringifyJSONintoOneLine(h, { addSpaces: !0, noQuotesOnKey: !0, singleQuotes: !0 })) } } b = "\n\t\t" + f.join(",\n\t\t") } a.removeButtons && (c = a.removeButtons); a = ['\x3ctextarea class\x3d"configCode" readonly\x3eCKEDITOR.editorConfig \x3d function( config ) {\n', b ? "\tconfig.toolbarGroups \x3d [" + b + "\n\t];" : "", c ? "\n\n" : "", c ? "\tconfig.removeButtons \x3d '" + c + "';" : "", "\n};\x3c/textarea\x3e"].join(""); this.modifyContainer.addClass("hidden"); this.configContainer.removeClass("hidden"); this.configContainer.setHtml(a) }; d.prototype._toggleVisibilityEmptyElements = function () { this.modifyContainer.hasClass("empty-visible") ? (this.modifyContainer.removeClass("empty-visible"), this.emptyVisible = !1) : (this.modifyContainer.addClass("empty-visible"), this.emptyVisible = !0); this._refreshMoveBtnsAvalibility() }; d.prototype._createModifier = function () { function a() { b._highlightGroup(this.data("name")) } var b = this; l.prototype._createModifier.call(this); this.modifyContainer.setHtml(this._toolbarConfigToListString()); var c = this.modifyContainer.find('li[data-type\x3d"group"]'); this.modifyContainer.on("mouseleave", function () { this._dehighlightActiveToolGroup() }, this); for (var e = c.count(), f = 0; f < e; f += 1)c.getItem(f).on("mouseenter", a); CKEDITOR.document.on("keypress", function (a) { a = a.data.$.keyCode; a = 32 === a || 13 === a; var c = new CKEDITOR.dom.element(CKEDITOR.document.$.activeElement); c.getAscendant(function (a) { return a.$ === b.mainContainer.$ }) && a && "button" === c.data("type") && c.findOne("input").$.click() }); this.modifyContainer.on("click", function (a) { var c = a.data.$, e = new CKEDITOR.dom.element(c.target || c.srcElement); if (a = d.getGroupOrSeparatorLiAncestor(e)) { b.cachedActiveElement = document.activeElement; if (e.$ instanceof HTMLInputElement)b._handleCheckboxClicked(e); else if (e.$ instanceof HTMLButtonElement && (c.preventDefault ? c.preventDefault() : c.returnValue = !1, (c = b._handleAnchorClicked(e.$)) && "remove" == c.action))return; c = a.data("type"); a = a.data("name"); b._setActiveElement(c, a); b.cachedActiveElement && b.cachedActiveElement.focus() } }); this.toolbarContainer || (this._createToolbar(), this.toolbarContainer.insertBefore(this.mainContainer.getChildren().getItem(0))); this.showToolbarBtnsByGroupName("edit"); this.configContainer || (this.configContainer = new CKEDITOR.dom.element("div"), this.configContainer.addClass("configContainer"), this.configContainer.addClass("hidden"), this.mainContainer.append(this.configContainer)); return this.mainContainer }; d.prototype.showToolbarBtnsByGroupName = function (a) { if (this.toolbarContainer)for (var b = this.toolbarContainer.find("button"), c = b.count(), e = 0; e < c; e += 1) { var d = b.getItem(e); d.data("group") == a ? d.removeClass("hidden") : d.addClass("hidden") } }; d.parseGroupToConfigValue = function (a) { if ("separator" == a.type)return "/"; var b = a.groups, c = b.length; delete a.totalBtns; for (var e = 0; e < c; e += 1)b[e] = b[e].name; return a }; d.getGroupOrSeparatorLiAncestor = function (a) { return a.$ instanceof HTMLLIElement && "group" == a.data("type") ? a : d.getFirstAncestor(a, function (a) { a = a.data("type"); return "group" == a || "separator" == a }) }; d.prototype._setActiveElement = function (a, b) { this.currentActive && this.currentActive.elem.removeClass("active"); if (null === a)this._dehighlightActiveToolGroup(), this.currentActive = null; else { var c = this.mainContainer.findOne('ul[data-type\x3dtable-body] li[data-type\x3d"' + a + '"][data-name\x3d"' + b + '"]'); c.addClass("active"); this.currentActive = {type: a, name: b, elem: c}; "group" == a && this._highlightGroup(b); "separator" == a && this._dehighlightActiveToolGroup() } }; d.prototype.getActiveToolGroup = function () { return this.editorInstance.container ? this.editorInstance.container.findOne(".cke_toolgroup.active, .cke_toolbar.active") : null }; d.prototype._dehighlightActiveToolGroup = function () { var a = this.getActiveToolGroup(); a && a.removeClass("active"); this.editorInstance.container && this.editorInstance.container.removeClass("some-toolbar-active") }; d.prototype._highlightGroup = function (a) { this.editorInstance.container && (a = this.getFirstEnabledButtonInGroup(a), a = this.editorInstance.container.findOne(".cke_button__" + a + ", .cke_combo__" + a), this._dehighlightActiveToolGroup(), this.editorInstance.container && this.editorInstance.container.addClass("some-toolbar-active"), a && (a = d.getFirstAncestor(a, function (a) { return a.hasClass("cke_toolbar") })) && a.addClass("active")) }; d.prototype.getFirstEnabledButtonInGroup = function (a) { var b = this.actualConfig.toolbarGroups; a = this.getGroupIndex(a); b = b[a]; if (-1 === a)return null; a = b.groups ? b.groups.length : 0; for (var c = 0; c < a; c += 1) { var e = this.getFirstEnabledButtonInSubgroup(b.groups[c].name); if (e)return e } return null }; d.prototype.getFirstEnabledButtonInSubgroup = function (a) { for (var b = (a = this.fullToolbarEditor.buttonsByGroup[a]) ? a.length : 0, c = 0; c < b; c += 1) { var e = a[c].name; if (!this.isButtonRemoved(e))return e } return null }; d.prototype._handleCheckboxClicked = function (a) { var b = a.getAscendant("li").data("name"); a.$.checked ? this._removeButtonFromRemoved(b) : this._addButtonToRemoved(b) }; d.prototype._handleAnchorClicked = function (a) { a = new CKEDITOR.dom.element(a); var b = a.getAscendant("li"), c = b.getAscendant("ul"), e = b.data("type"), d = b.data("name"), g = a.data("direction"), m = "up" === g ? b.getPrevious() : b.getNext(), h; if (a.hasClass("disabled"))return null; if (a.hasClass("remove"))return b.remove(), this._removeSeparator(b.data("name")), this._setActiveElement(null), {action: "remove"}; if (!a.hasClass("move") || !m)return {action: null}; if ("group" === e || "separator" === e)h = this._moveGroup(g, d); "subgroup" === e && (h = b.getAscendant("li").data("name"), h = this._moveSubgroup(g, h, d)); "up" === g && b.insertBefore(c.getChild(h)); "down" === g && b.insertAfter(c.getChild(h)); for (var k; b = "up" === g ? b.getPrevious() : b.getNext();)if (this.emptyVisible || !b.hasClass("empty")) { k = b; break } k || (k = '[data-direction\x3d"' + ("up" === g ? "down" : "up") + '"]', this.cachedActiveElement = a.getParent().findOne(k)); this._refreshMoveBtnsAvalibility(); this._refreshBtnTabIndexes(); return {action: "move"} }; d.prototype._refreshMoveBtnsAvalibility = function () { function a(a) { var c = a.count(); for (d = 0; d < c; d += 1)b._disableElementsInList(a.getItem(d)) } for (var b = this, c = this.mainContainer.find("ul[data-type\x3dtable-body] li \x3e p \x3e span \x3e button.move.disabled"), e = c.count(), d = 0; d < e; d += 1)c.getItem(d).removeClass("disabled"); a(this.mainContainer.find("ul[data-type\x3dtable-body]")); a(this.mainContainer.find("ul[data-type\x3dtable-body] \x3e li \x3e ul")) }; d.prototype._refreshBtnTabIndexes = function () { for (var a = this.mainContainer.find('[data-tab\x3d"true"]'), b = a.count(), c = 0; c < b; c++) { var e = a.getItem(c), d = e.hasClass("disabled"); e.setAttribute("tabindex", d ? -1 : c) } }; d.prototype._disableElementsInList = function (a) { function b(a) { return !a.hasClass("empty") } if (a.getChildren().count()) { var c; this.emptyVisible ? (c = a.getFirst(), a = a.getLast()) : (c = a.getFirst(b), a = a.getLast(b)); if (c)var e = c.findOne('p button[data-direction\x3d"up"]'); if (a)var d = a.findOne('p button[data-direction\x3d"down"]'); e && (e.addClass("disabled"), e.setAttribute("tabindex", "-1")); d && (d.addClass("disabled"), d.setAttribute("tabindex", "-1")) } }; d.prototype.getGroupIndex = function (a) { for (var b = this.actualConfig.toolbarGroups, c = b.length, d = 0; d < c; d += 1)if (b[d].name === a)return d; return -1 }; d.prototype._addSeparator = function () { var a = this._determineSeparatorToAddIndex(), b = d.createSeparatorLiteral(), c = CKEDITOR.dom.element.createFromHtml(d.getToolbarSeparatorString(b)); this.actualConfig.toolbarGroups.splice(a, 0, b); c.insertBefore(this.modifyContainer.findOne("ul[data-type\x3dtable-body]").getChild(a)); this._setActiveElement("separator", b.name); this._refreshMoveBtnsAvalibility(); this._refreshBtnTabIndexes(); this._refreshEditor() }; d.prototype._removeSeparator = function (a) { var b = CKEDITOR.tools.indexOf(this.actualConfig.toolbarGroups, function (b) { return "separator" == b.type && b.name == a }); this.actualConfig.toolbarGroups.splice(b, 1); this._refreshMoveBtnsAvalibility(); this._refreshBtnTabIndexes(); this._refreshEditor() }; d.prototype._determineSeparatorToAddIndex = function () { return this.currentActive ? ("group" == this.currentActive.elem.data("type") || "separator" == this.currentActive.elem.data("type") ? this.currentActive.elem : this.currentActive.elem.getAscendant("li")).getIndex() : 0 }; d.prototype._moveElement = function (a, b, c) { function e(a) { return a.totalBtns || "separator" == a.type } c = this.emptyVisible ? "down" == c ? b + 1 : b - 1 : d.getFirstElementIndexWith(a, b, c, e); return d.moveTo(c - b, a, b) }; d.prototype._moveGroup = function (a, b) { var c = this.getGroupIndex(b), c = this._moveElement(this.actualConfig.toolbarGroups, c, a); this._refreshMoveBtnsAvalibility(); this._refreshBtnTabIndexes(); this._refreshEditor(); return c }; d.prototype._moveSubgroup = function (a, b, c) { b = this.getGroupIndex(b); b = this.actualConfig.toolbarGroups[b]; var d = CKEDITOR.tools.indexOf(b.groups, function (a) { return a.name == c }); a = this._moveElement(b.groups, d, a); this._refreshEditor(); return a }; d.prototype._calculateTotalBtns = function () { for (var a = this.actualConfig.toolbarGroups, b = a.length; b--;) { var c = a[b], e = d.getTotalGroupButtonsNumber(c, this.fullToolbarEditor); "separator" != c.type && (c.totalBtns = e) } }; d.prototype._addButtonToRemoved = function (a) { if (-1 != CKEDITOR.tools.indexOf(this.removedButtons, a))throw"Button already added to removed"; this.removedButtons.push(a); this.actualConfig.removeButtons = this.removedButtons.join(","); this._refreshEditor() }; d.prototype._removeButtonFromRemoved = function (a) { a = CKEDITOR.tools.indexOf(this.removedButtons, a); if (-1 === a)throw"Trying to remove button from removed, but not found"; this.removedButtons.splice(a, 1); this.actualConfig.removeButtons = this.removedButtons.join(","); this._refreshEditor() }; d.parseGroupToConfigValue = function (a) { if ("separator" == a.type)return "/"; var b = a.groups, c = b.length; delete a.totalBtns; for (var d = 0; d < c; d += 1)b[d] = b[d].name; return a }; d.getGroupOrSeparatorLiAncestor = function (a) { return a.$ instanceof HTMLLIElement && "group" == a.data("type") ? a : d.getFirstAncestor(a, function (a) { a = a.data("type"); return "group" == a || "separator" == a }) }; d.createSeparatorLiteral = function () { return {type: "separator", name: "separator" + CKEDITOR.tools.getNextNumber()} }; d.prototype._toolbarConfigToListString = function () { for (var a = this.actualConfig.toolbarGroups || [], b = '\x3cul data-type\x3d"table-body"\x3e', c = a.length, e = 0; e < c; e += 1)var f = a[e], b = "separator" === f.type ? b + d.getToolbarSeparatorString(f) : b + this._getToolbarGroupString(f); b += "\x3c/ul\x3e"; return d.getToolbarHeaderString() + b }; d.prototype._getToolbarGroupString = function (a) { var b = a.groups, c; c = "" + ['\x3cli data-type\x3d"group" data-name\x3d"', a.name, '" ', a.totalBtns ? "" : 'class\x3d"empty"', "\x3e"].join(""); c += d.getToolbarElementPreString(a) + "\x3cul\x3e"; a = b.length; for (var e = 0; e < a; e += 1) { var f = b[e]; c += this._getToolbarSubgroupString(f, this.fullToolbarEditor.buttonsByGroup[f.name]) } return c + "\x3c/ul\x3e\x3c/li\x3e" }; d.getToolbarSeparatorString = function (a) { return ['\x3cli data-type\x3d"', a.type, '" data-name\x3d"', a.name, '"\x3e', d.getToolbarElementPreString("row separator"), "\x3c/li\x3e"].join("") }; d.getToolbarHeaderString = function () { return '\x3cul data-type\x3d"table-header"\x3e\x3cli data-type\x3d"header"\x3e\x3cp\x3eToolbars\x3c/p\x3e\x3cul\x3e\x3cli\x3e\x3cp\x3eToolbar groups\x3c/p\x3e\x3cp\x3eToolbar group items\x3c/p\x3e\x3c/li\x3e\x3c/ul\x3e\x3c/li\x3e\x3c/ul\x3e' }; d.getFirstAncestor = function (a, b) { for (var c = a.getParents(), d = c.length; d--;)if (b(c[d]))return c[d]; return null }; d.getFirstElementIndexWith = function (a, b, c, d) { for (; "up" === c ? b-- : ++b < a.length;)if (d(a[b]))return b; return -1 }; d.moveTo = function (a, b, c) { var d; -1 !== c && (d = b.splice(c, 1)[0]); a = c + a; b.splice(a, 0, d); return a }; d.getTotalSubGroupButtonsNumber = function (a, b) { var c = b.buttonsByGroup["string" == typeof a ? a : a.name]; return c ? c.length : 0 }; d.getTotalGroupButtonsNumber = function (a, b) { for (var c = 0, e = a.groups, f = e ? e.length : 0, g = 0; g < f; g += 1)c += d.getTotalSubGroupButtonsNumber(e[g], b); return c }; d.prototype._getToolbarSubgroupString = function (a, b) { var c; c = "" + ['\x3cli data-type\x3d"subgroup" data-name\x3d"', a.name, '" ', a.totalBtns ? "" : 'class\x3d"empty" ', "\x3e"].join(""); c += d.getToolbarElementPreString(a.name); c += "\x3cul\x3e"; for (var e = b ? b.length : 0, f = 0; f < e; f += 1)c += this.getButtonString(b[f]); return c += "\x3c/ul\x3e\x3c/li\x3e" }; d.prototype._getConfigButtonName = function (a) { var b = this.fullToolbarEditor.editorInstance.ui.items, c; for (c in b)if (b[c].name == a)return c; return null }; d.prototype.isButtonRemoved = function (a) { return -1 != CKEDITOR.tools.indexOf(this.removedButtons, this._getConfigButtonName(a)) }; d.prototype.getButtonString = function (a) { var b = this.isButtonRemoved(a.name) ? "" : 'checked\x3d"checked"'; return ['\x3cli data-tab\x3d"true" data-type\x3d"button" data-name\x3d"', this._getConfigButtonName(a.name), '"\x3e\x3clabel title\x3d"', a.label, '" \x3e\x3cinput tabindex\x3d"-1"type\x3d"checkbox"', b, "/\x3e", a.$.getOuterHtml(), "\x3c/label\x3e\x3c/li\x3e"].join("") }; d.getToolbarElementPreString = function (a) { a = a.name ? a.name : a; return ['\x3cp\x3e\x3cspan\x3e\x3cbutton title\x3d"Move element upward" data-tab\x3d"true" data-direction\x3d"up" class\x3d"move icon-up-big"\x3e\x3c/button\x3e\x3cbutton title\x3d"Move element downward" data-tab\x3d"true" data-direction\x3d"down" class\x3d"move icon-down-big"\x3e\x3c/button\x3e', "row separator" == a ? '\x3cbutton title\x3d"Remove element" data-tab\x3d"true" class\x3d"remove icon-trash"\x3e\x3c/button\x3e' : "", a, "\x3c/span\x3e\x3c/p\x3e"].join("") }; d.evaluateToolbarGroupsConfig = function (a) { return a = function (a) { var c = {}, d; try { d = eval("(" + a + ")") } catch (f) { try { d = eval(a) } catch (g) { return null } } return c.toolbarGroups && "number" === typeof c.toolbarGroups.length ? JSON.stringify(c) : d && "number" === typeof d.length ? JSON.stringify({toolbarGroups: d}) : d && d.toolbarGroups ? JSON.stringify(d) : null }(a) }; return d })();
# Copyright (c) 2018 Cisco and/or its affiliates. # 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. """Keywords to manipulate bridge domain configuration using Honeycomb REST API. The keywords make possible to put and get configuration data and to get operational data. """ from resources.libraries.python.HTTPRequest import HTTPCodes from resources.libraries.python.honeycomb.HoneycombSetup import HoneycombError from resources.libraries.python.honeycomb.HoneycombUtil \ import DataRepresentation from resources.libraries.python.honeycomb.HoneycombUtil \ import HoneycombUtil as HcUtil class BridgeDomainKeywords(object): """Keywords to manipulate bridge domain configuration. Implements keywords which get configuration and operational data about bridge domains and put the bridge domains' parameters using Honeycomb REST API. """ PARAMS = ("flood", "forward", "learn", "unknown-unicast-flood", "arp-termination") def __init__(self): pass @staticmethod def _configure_bd(node, bd_name, data, data_representation=DataRepresentation.JSON): """Send bridge domain configuration data and check the response. :param node: Honeycomb node. :param bd_name: The name of bridge domain. :param data: Configuration data to be sent in PUT request. :param data_representation: How the data is represented. :type node: dict :type bd_name: str :type data: dict :type data_representation: DataRepresentation :returns: Content of response. :rtype: bytearray :raises HoneycombError: If the status code in response on PUT is not 200 = OK. """ status_code, resp = HcUtil.\ put_honeycomb_data(node, "config_bridge_domain", data, data_representation=data_representation) if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED): raise HoneycombError( "The configuration of bridge domain '{0}' was not successful. " "Status code: {1}.".format(bd_name, status_code)) return resp @staticmethod def _set_bd_properties(node, bd_name, path, new_value=None): """Set bridge domain properties. This method reads bridge domain configuration data, creates, changes or removes the requested data and puts it back to Honeycomb. :param node: Honeycomb node. :param bd_name: The name of bridge domain. :param path: Path to data we want to change, create or remove. :param new_value: The new value to be set. If None, the item will be removed. :type node: dict :type bd_name: str :type path: tuple :type new_value: str, dict or list :returns: Content of response. :rtype: bytearray :raises HoneycombError: If it is not possible to get or set the data. """ status_code, resp = HcUtil.\ get_honeycomb_data(node, "config_bridge_domain") if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED): raise HoneycombError( "Not possible to get configuration information about the " "bridge domains. Status code: {0}.".format(status_code)) if new_value: new_data = HcUtil.set_item_value(resp, path, new_value) else: new_data = HcUtil.remove_item(resp, path) return BridgeDomainKeywords._configure_bd(node, bd_name, new_data) @staticmethod def _create_bd_structure(bd_name, **kwargs): """Create the bridge domain data structure as it is expected by Honeycomb REST API. :param bd_name: Bridge domain name. :param kwargs: Parameters and their values. The accepted parameters are defined in BridgeDomainKeywords.PARAMS. :type bd_name: str :type kwargs: dict :returns: Bridge domain data structure. :rtype: dict """ bd_structure = {"name": bd_name} for param, value in kwargs.items(): if param not in BridgeDomainKeywords.PARAMS: raise HoneycombError("The parameter {0} is invalid.". format(param)) bd_structure[param] = str(value) return bd_structure @staticmethod def get_all_bds_cfg_data(node): """Get configuration data about all bridge domains from Honeycomb. :param node: Honeycomb node. :type node: dict :returns: Configuration data about all bridge domains from Honeycomb. :rtype: list :raises HoneycombError: If it is not possible to get configuration data. """ status_code, resp = HcUtil.\ get_honeycomb_data(node, "config_bridge_domain") if status_code != HTTPCodes.OK: raise HoneycombError( "Not possible to get configuration information about the " "bridge domains. Status code: {0}.".format(status_code)) try: return resp["bridge-domains"]["bridge-domain"] except (KeyError, TypeError): return [] @staticmethod def get_bd_cfg_data(node, bd_name): """Get configuration data about the given bridge domain from Honeycomb. :param node: Honeycomb node. :param bd_name: The name of bridge domain. :type node: dict :type bd_name: str :returns: Configuration data about the given bridge domain from Honeycomb. :rtype: dict """ intfs = BridgeDomainKeywords.get_all_bds_cfg_data(node) for intf in intfs: if intf["name"] == bd_name: return intf return {} @staticmethod def get_all_bds_oper_data(node): """Get operational data about all bridge domains from Honeycomb. :param node: Honeycomb node. :type node: dict :returns: Operational data about all bridge domains from Honeycomb. :rtype: list :raises HoneycombError: If it is not possible to get operational data. """ status_code, resp = HcUtil.\ get_honeycomb_data(node, "oper_bridge_domains") if status_code != HTTPCodes.OK: raise HoneycombError( "Not possible to get operational information about the " "bridge domains. Status code: {0}.".format(status_code)) try: return resp["bridge-domains-state"]["bridge-domain"] except (KeyError, TypeError): return [] @staticmethod def get_bd_oper_data(node, bd_name): """Get operational data about the given bridge domain from Honeycomb. :param node: Honeycomb node. :param bd_name: The name of bridge domain. :type node: dict :type bd_name: str :returns: Operational data about the given bridge domain from Honeycomb. :rtype: dict """ intfs = BridgeDomainKeywords.get_all_bds_oper_data(node) for intf in intfs: if intf["name"] == bd_name: return intf return {} @staticmethod def add_first_bd(node, bd_name, **kwargs): """Add the first bridge domain. If there are any other bridge domains configured, they will be removed. :param node: Honeycomb node. :param bd_name: Bridge domain name. :param kwargs: Parameters and their values. The accepted parameters are defined in BridgeDomainKeywords.PARAMS :type node: dict :type bd_name: str :type kwargs: dict :returns: Bridge domain data structure. :rtype: dict """ new_bd = BridgeDomainKeywords._create_bd_structure(bd_name, **kwargs) bridge_domain = {"bridge-domains": {"bridge-domain": [new_bd, ]}} return BridgeDomainKeywords._configure_bd(node, bd_name, bridge_domain) @staticmethod def add_bd(node, bd_name, **kwargs): """Add a bridge domain. :param node: Honeycomb node. :param bd_name: Bridge domain name. :param kwargs: Parameters and their values. The accepted parameters are defined in BridgeDomainKeywords.PARAMS :type node: dict :type bd_name: str :type kwargs: dict :returns: Bridge domain data structure. :rtype: dict """ path = ("bridge-domains", "bridge-domain") new_bd = BridgeDomainKeywords._create_bd_structure(bd_name, **kwargs) bridge_domain = [new_bd, ] return BridgeDomainKeywords._set_bd_properties(node, bd_name, path, bridge_domain) @staticmethod def remove_all_bridge_domains(node): """Remove all bridge domains. :param node: Honeycomb node. :type node: dict :returns: Content of response. :rtype: bytearray :raises HoneycombError: If it is not possible to remove all bridge domains. """ data = {"bridge-domains": {"bridge-domain": []}} status_code, resp = HcUtil.\ put_honeycomb_data(node, "config_bridge_domain", data) if status_code not in (HTTPCodes.OK, HTTPCodes.ACCEPTED): raise HoneycombError("Not possible to remove all bridge domains. " "Status code: {0}.".format(status_code)) return resp @staticmethod def remove_bridge_domain(node, bd_name): """Remove a bridge domain. :param node: Honeycomb node. :param bd_name: The name of bridge domain to be removed. :type node: dict :type bd_name: str :returns: Content of response. :rtype: bytearray :raises HoneycombError: If it is not possible to remove the bridge domain. """ path = ("bridge-domains", ("bridge-domain", "name", bd_name)) status_code, resp = HcUtil.\ get_honeycomb_data(node, "config_bridge_domain") if status_code != HTTPCodes.OK: raise HoneycombError( "Not possible to get configuration information about the " "bridge domains. Status code: {0}.".format(status_code)) new_data = HcUtil.remove_item(resp, path) status_code, resp = HcUtil.\ put_honeycomb_data(node, "config_bridge_domain", new_data) if status_code != HTTPCodes.OK: raise HoneycombError("Not possible to remove bridge domain {0}. " "Status code: {1}.". format(bd_name, status_code)) return resp @staticmethod def configure_bridge_domain(node, bd_name, param, value): """Configure a bridge domain. :param node: Honeycomb node. :param bd_name: Bridge domain name. :param param: Parameter to set, change or remove. The accepted parameters are defined in BridgeDomainKeywords.PARAMS :param value: The new value to be set, change or remove. If None, the item will be removed. :type node: dict :type bd_name: str :type param: str :type value: str :returns: Content of response. :rtype: bytearray """ if param not in BridgeDomainKeywords.PARAMS: raise HoneycombError("The parameter {0} is invalid.".format(param)) path = ("bridge-domains", ("bridge-domain", "name", bd_name), param) return BridgeDomainKeywords.\ _set_bd_properties(node, bd_name, path, value) @staticmethod def add_l2_fib_entry(node, bd_name, l2_fib_entry): """Add an L2 FIB entry to the bridge domain's list of L2 FIB entries. :param node: Honeycomb node. :param bd_name: Bridge domain's name. :param l2_fib_entry: L2 FIB entry to be added to the L2 FIB table. :type node: dict :type bd_name: str :type l2_fib_entry: dict :returns: Content of response. :rtype: bytearray """ path = ("bridge-domains", ("bridge-domain", "name", bd_name), "l2-fib-table", "l2-fib-entry") new_l2_fib_entry = [l2_fib_entry, ] return BridgeDomainKeywords._set_bd_properties( node, bd_name, path, new_l2_fib_entry) @staticmethod def modify_l2_fib_entry(node, bd_name, mac, param, value): """Modify an existing L2 FIB entry in the bridge domain's L2 FIB table. The L2 FIB entry is specified by MAC address. :param node: Honeycomb node. :param bd_name: Bridge domain's name. :param mac: MAC address used as the key in L2 FIB data structure. :param param: The parameter to be modified. :param value: The new value of the parameter. :type node: dict :type bd_name: str :type mac: str :type param: str :type value: str or int :returns: Content of response. :rtype: bytearray """ path = ("bridge-domains", ("bridge-domain", "name", bd_name), "l2-fib-table", ("l2-fib-entry", "phys-address", mac), param) return BridgeDomainKeywords._set_bd_properties( node, bd_name, path, value) @staticmethod def remove_l2_fib_entry(node, bd_name, mac): """Remove an L2 FIB entry from bridge domain's L2 FIB table. The entry is specified by MAC address. :param node: Honeycomb node. :param bd_name: Bridge domain's name. :param mac: MAC address used as the key in L2 FIB data structure. :type node: dict :type bd_name: str :type mac: str :returns: Content of response. :rtype: bytearray :raises HoneycombError: If it is not possible to remove the specified entry. """ path = ("bridge-domains", ("bridge-domain", "name", bd_name), "l2-fib-table", ("l2-fib-entry", "phys-address", str(mac))) status_code, resp = HcUtil.\ get_honeycomb_data(node, "config_bridge_domain") if status_code != HTTPCodes.OK: raise HoneycombError("Not possible to get configuration information" " about the L2 FIB entry {0} from bridge " "domain {1}. Status code: {2}.". format(mac, bd_name, status_code)) new_data = HcUtil.remove_item(resp, path) status_code, resp = HcUtil.\ put_honeycomb_data(node, "config_bridge_domain", new_data) if status_code != HTTPCodes.OK: raise HoneycombError("Not possible to remove L2 FIB entry {0} from " "bridge domain {1}. Status code: {2}.". format(mac, bd_name, status_code)) return resp @staticmethod def remove_all_l2_fib_entries(node, bd_name): """Remove all entries from the bridge domain's L2 FIB table. :param node: Honeycomb node. :param bd_name: Bridge domain's name. :type node: dict :type bd_name: str :returns: Content of response. :rtype: bytearray """ path = ("bridge-domains", ("bridge-domain", "name", bd_name), "l2-fib-table") return BridgeDomainKeywords._set_bd_properties( node, bd_name, path, None) @staticmethod def get_all_l2_fib_entries(node, bd_name): """Retrieves all entries from the bridge domain's L2 FIB table. :param node: Honeycomb node. :param bd_name: Bridge domain's name. :type node: dict :type bd_name: str :returns: Bridge domain's L2 FIB table or empty list if the table does not exist or it is empty. :rtype: list """ bd_data = BridgeDomainKeywords.get_bd_oper_data(node, bd_name) try: return bd_data["l2-fib-table"]["l2-fib-entry"] except KeyError: return [] @staticmethod def get_l2_fib_entry(node, bd_name, mac): """Retrieves an entry from bridge domain's L2 FIB table. The entry is specified by MAC address. :param node: Honeycomb node. :param bd_name: Bridge domain's name. :param mac: MAC address used as the key in L2 FIB data structure. :type node: dict :type bd_name: str :type mac: str :returns: The requested entry from bridge domain's L2 FIB table or empty dictionary if it does not exist in the L2 FIB table. :rtype: dict """ l2_fib = BridgeDomainKeywords.get_all_l2_fib_entries(node, bd_name) for entry in l2_fib: if entry["phys-address"] == mac: return entry return {}
''' Compute concordance index ''' # Modules # ======================================================================================================================= import os import sys import glob import subprocess import tqdm import importlib os.chdir('/nfs/research1/gerstung/sds/sds-ukb-cancer/projects/ProbCox/') import pandas as pd import numpy as np from multiprocessing import Pool import torch from torch.distributions import constraints from torch.utils.data import Dataset, DataLoader, Sampler import pyro import pyro.distributions as dist from pyro.optim import Adam from pyro.infer import SVI, Trace_ELBO from pyro.infer.mcmc import MCMC, NUTS import matplotlib.pyplot as plt import probcox import warnings warnings.filterwarnings("ignore") dtype = torch.FloatTensor np.random.seed(87) torch.manual_seed(34) ROOT_DIR = '/nfs/research1/gerstung/sds/sds-ukb-cancer/' # Concordance # ======================================================================================================================= #train dd = torch.load(ROOT_DIR + 'projects/ProbCox/output/prediction_train') ci_train = pcox.metrics(surv=dd['Surv'], linpred=dd['Pred'],processes=12).concordance() # valid dd = torch.load(ROOT_DIR + 'projects/ProbCox/output/prediction_valid') ci_valid = pcox.metrics(surv=dd['Surv'], linpred=dd['Pred'],processes=12).concordance() # test dd = torch.load(ROOT_DIR + 'projects/ProbCox/output/prediction_test') ci_test = pcox.metrics(surv=dd['Surv'], linpred=dd['Pred'],processes=12).concordance() torch.save({'ci_train': ci_train, 'ci_valid': ci_valid, 'ci_test': ci_test}, ROOT_DIR + 'projects/ProbCox/output/concordance')
/** * Main JS file for Paperleaf behaviours */ /* globals jQuery, document */ (function ($, undefined) { "use strict"; var $document = $(document); $document.ready(function () { /** * FitVids.js for responsive videos */ var $postContent = $(".post-content"); $postContent.fitVids(); /** * Masonry grid */ var $grid = $('.js-grid').imagesLoaded( function() { $grid.masonry({ itemSelector : '.post', percentPosition : true, transitionDuration : '0.25s' }); $.force_appear(); }); /** * Add class to elements that appear in viewport */ $('.post--grid').appear(); $('.post--grid').on('appear', function(event, $all_appeared_elements) { $(this).addClass('animate'); }); /** * Preloader */ $('body').imagesLoaded( function() { $('.js-loader').fadeOut(250); }); /** * Handle sidebar height for phones and tablets */ $(window).on('resize', function(event) { sidebarHeight(); }); sidebarHeight(); $('.js-toggle-nav').on('click', function(event) { event.preventDefault(); $(this).toggleClass('open'); $('.js-nav').toggleClass('is-visible'); }); }); })(jQuery); function sidebarHeight() { var innerHeight = jQuery('.js-sidebar-inner').height(); var footerHeight = jQuery('.js-sidebar-footer').height(); var windowHeight = jQuery(window).height(); var switchClass = ( innerHeight + footerHeight + 192 ) > windowHeight ? true : false; if ( switchClass ) { jQuery('.js-sidebar-footer').addClass('sidebar-footer-static'); } else { jQuery('.js-sidebar-footer').removeClass('sidebar-footer-static'); } }
/* eslint-disable react/jsx-no-bind */ import React, { Component } from 'react'; import { render } from 'react-dom'; import FrequencyMeter from 'react-fm'; class App extends Component { static propTypes = { audioContext: React.PropTypes.object, fileName: React.PropTypes.string }; static defaultProps = { audioContext: new AudioContext(), fileName: '1kHz_44100Hz_16bit_05sec.mp3' }; constructor(props) { super(props); this.state = { audioSource: null, audioBuffer: null }; } componentDidMount() { getAudio(this.props.fileName, (data) => { this.props.audioContext.decodeAudioData(data, (audioBuffer) => { this.setState({ audioBuffer }); }); }); } play() { const { audioContext } = this.props; const { audioBuffer, audioSource } = this.state; if (audioBuffer) { if (audioSource) { this.stop(); this.setState({ audioSource: null }); } const audioSource1 = audioContext.createBufferSource(); this.setState({ audioSource: audioSource1 }); audioSource1.buffer = audioBuffer; audioSource1.connect(audioContext.destination); audioSource1.start(0, 0); } } stop() { const { audioSource } = this.state; if (audioSource) { audioSource.stop(); } } render() { return ( <div> <button onClick={this.play.bind(this)}>Play</button> <button onClick={this.stop.bind(this)}>Stop</button> <FrequencyMeter audioSource={this.state.audioSource} /> </div>); } } function getAudio(fileName, callback) { const xhr = new XMLHttpRequest(); xhr.onload = () => { callback(xhr.response); }; xhr.open('GET', fileName, true); xhr.responseType = 'arraybuffer'; xhr.send(); } render(<App />, document.getElementById('example'));
export default "<meta charset=\"utf-8\"><span style=\"font-size:14px;font-family:Arial;color:#252525;background-color:#ffffff;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;\" id=\"docs-internal-guid-af43648c-43e0-a996-6b08-68384b28b868\">XXX</span>";
const HashTagModel = require("./hashTagModel"); const HashTagMaster = require("../hashTagMaster/hashTagMasterModel"); const HashTagMasterService = require("../hashTagMaster/hashTagMasterService"); const createHashTag = (body,callback)=>{ if(body.hashTagId != null || body.hashTagId != undefined){ let newTag ={ hashTagId:body.hashTagId, memberId:body.memberId, createdBy:body.memberId, updatedBy:body.memberId } HashTagModel.create(newTag,(err,newHashTagModel)=>{ if(err){ callback(err,null) }else{ HashTagMaster.update({_id:body.hashTagId},{$inc:{count:1}},(err,data)=>{ console.log(data) }) callback(null,newHashTagModel) } }) }else{ HashTagMasterService.createHashTag({memberId:body.memberId,hashTagName:body.hashTagName},(err,newHashTagMasterObj)=>{ if(err){ callback(err,null) }else{ let newTag ={ hashTagId:newHashTagMasterObj._id, memberId:newHashTagMasterObj.memberId, createdBy:newHashTagMasterObj.memberId, updatedBy:newHashTagMasterObj.memberId } HashTagModel.create(newTag,(err,newHashTagModel)=>{ if(err){ callback(err,null) }else{ HashTagMaster.update({_id:newHashTagModel._id},{$inc:{count:1}},(err,data)=>{ console.log(data) }) callback(null,newHashTagModel) } }) } }) } } const editHashTag = (id,body,callback)=>{ HashTagModel.findByIdAndUpdate(id,{$set:body},(err,updateHashTagModel)=>{ if(err){ callback(err,null) }else{ callback(null,updateHashTagModel) } }) } const getHashTagsbyId = (param,callback)=>{ let id = param.id; HashTagModel.findById(id,(err,updateHashTagModel)=>{ if(err){ callback(err,null) }else{ callback(null,updateHashTagModel) } }) } const getHashTagsbyMemberId = (param,callback)=>{ let memberId = param.memberId; HashTagModel.findOne({memberId:memberId},(err,allHashTagsBymember)=>{ if(err){ callback(err,null) }else{ callback(null,allHashTagsBymember) } }) } const getAllHashTag = (callback)=>{ HashTagModel.find({},(err,allHashTags)=>{ if(err){ callback(err,null) }else{ callback(null,allHashTags) } }) } module.exports = { createHashTag:createHashTag, editHashTag:editHashTag, getHashTagsbyId:getHashTagsbyId, getHashTagsbyMemberId:getHashTagsbyMemberId, getAllHashTag:getAllHashTag };
// Copyright 2018 Bartosz Jaroszewski // SPDX-License-Identifier: GPL-2.0-or-later // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. const GLib = imports.gi.GLib; function spawn(command, callback) { let [status, pid] = GLib.spawn_async( null, ['/usr/bin/env', 'bash', '-c', command], null, GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD, null ); // ensure we always close the pid to avoid zombie processes GLib.child_watch_add( GLib.PRIORITY_DEFAULT, pid, (_pid, _status) => { try { if (callback) { callback(_pid, _status); } } finally { GLib.spawn_close_pid(_pid); } }); } function isDebugModeEnabled() { return new Settings().isDebugModeEnabled(); } var Logger = class Logger { constructor(settings) { this._enabled = settings.isDebugModeEnabled(); } info(message) { if (!this._enabled) return; log(`[bluetooth-quick-connect] ${message}`); } warn(message) { log(`[bluetooth-quick-connect WARNING] ${message}`); } }; function addSignalsHelperMethods(prototype) { prototype._connectSignal = function (subject, signal_name, method) { if (!this._signals) this._signals = []; let signal_id = subject.connect(signal_name, method); this._signals.push({ subject: subject, signal_id: signal_id }); } prototype._disconnectSignals = function () { if (!this._signals) return; this._signals.forEach((signal) => { signal.subject.disconnect(signal.signal_id); }); this._signals = []; }; }
import mock from libmproxy import controller class TestMaster: def test_default_handler(self): m = controller.Master(None) msg = mock.MagicMock() m.handle("type", msg) assert msg.reply.call_count == 1
import PropTypes from 'prop-types'; import React from 'react'; import { Grid } from 'react-flexbox-grid/lib'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import { sendPasswordReset } from '../../actions/userActions'; import ChangePasswordForm from './ChangePasswordForm'; import { addNotice } from '../../actions/appActions'; import { LEVEL_ERROR } from '../common/Notice'; const localMessages = { tite: { id: 'user.resetPassword.title', defaultMessage: 'Reset Your Password' }, button: { id: 'user.resetPassword.button', defaultMessage: 'Reset Your Password' }, failed: { id: 'user.resetPassword.failed', defaultMessage: 'Sorry, something went wrong.' }, badToken: { id: 'user.resetPassword.badToken', defaultMessage: 'That is an invalid reset token. Check to see if you have a newer link from us in your email.' }, }; const ResetPasswordContainer = (props) => { const { handlePasswordReset } = props; return ( <Grid> <ChangePasswordForm titleMsg={localMessages.tite} buttonMsg={localMessages.button} onSubmit={handlePasswordReset} /> </Grid> ); }; ResetPasswordContainer.propTypes = { // form router location: PropTypes.object.isRequired, // from dispatch handlePasswordReset: PropTypes.func.isRequired, }; const mapDispatchToProps = (dispatch, ownProps) => ({ handlePasswordReset: (values) => { // this link came from the email, so we need to grab the props to submit off of the url const { email } = ownProps.location.query; const passwordResetToken = ownProps.location.query.password_reset_token; // send the request to reset the password return dispatch(sendPasswordReset({ ...values, email, password_reset_token: passwordResetToken })) .then((response) => { if (response.success) { // the token was ok // and the pswd change worked if (response.success === 1) { return dispatch(push('/user/reset-password-success')); // them them it worked } // or it failed return dispatch(addNotice({ message: localMessages.failed, level: LEVEL_ERROR })); } if (response.message.includes('Password reset token is invalid')) { // the token was not valid return dispatch(addNotice({ message: localMessages.badToken, level: LEVEL_ERROR })); } // someone else bad happened return dispatch(addNotice({ message: localMessages.failed, level: LEVEL_ERROR })); }); }, }); export default connect(null, mapDispatchToProps)( ResetPasswordContainer );
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.preDeployPullBackend = void 0; const amplify_app_1 = require("amplify-app"); const node_fetch_1 = __importDefault(require("node-fetch")); const path_1 = __importDefault(require("path")); const fs_extra_1 = __importDefault(require("fs-extra")); const amplify_cli_core_1 = require("amplify-cli-core"); async function preDeployPullBackend(context, sandboxId) { const providerPlugin = await Promise.resolve().then(() => __importStar(require(context.amplify.getProviderPlugins(context).awscloudformation))); const url = `${providerPlugin.adminBackendMap['us-east-1'].appStateUrl}/AppState/${sandboxId}`; const res = await node_fetch_1.default(`${url}`); const resJson = await res.json(); const appNotFoundMessage = 'Requested app was not found'; if (resJson.message === appNotFoundMessage) { context.print.error(appNotFoundMessage); context.usageData.emitError(new amplify_cli_core_1.AppNotFoundError(appNotFoundMessage)); process.exitCode = 1; return; } if (resJson.appId) { const deployedErrorMessage = `This app is already deployed. You can pull it using "amplify pull --appId ${resJson.appId}"`; context.print.error(deployedErrorMessage); context.usageData.emitError(new amplify_cli_core_1.AppAlreadyDeployedError(deployedErrorMessage)); process.exitCode = 1; return; } if (!resJson.schema) { const missingSchemaMessage = 'No GraphQL schema found in the app.'; context.print.error(missingSchemaMessage); context.usageData.emitError(new amplify_cli_core_1.SchemaDoesNotExistError(missingSchemaMessage)); process.exitCode = 1; return; } const amplifyDirPath = amplify_cli_core_1.pathManager.getBackendDirPath(process.cwd()); if (!fs_extra_1.default.existsSync(amplifyDirPath)) { await amplify_app_1.run({ skipEnvCheck: true }); } replaceSchema(resJson.schema); await context.amplify.invokePluginMethod(context, 'codegen', null, 'generateModels', [context]); } exports.preDeployPullBackend = preDeployPullBackend; function replaceSchema(schema) { const schemaFilePath = path_1.default.join(process.cwd(), 'amplify', 'backend', 'api', 'amplifyDatasource', 'schema.graphql'); fs_extra_1.default.writeFileSync(schemaFilePath, schema); } //# sourceMappingURL=pre-deployment-pull.js.map
// TODO: in future try to replace most inline compability checks with polyfills for code readability // element.textContent polyfill. // Unsupporting browsers: IE8 if (Object.defineProperty && Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(Element.prototype, "textContent") && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) { (function() { var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText"); Object.defineProperty(Element.prototype, "textContent", { get: function() { return innerText.get.call(this); }, set: function(s) { return innerText.set.call(this, s); } } ); })(); } // isArray polyfill for ie8 if(!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; };/** * @license wysihtml5x v0.4.15 * https://github.com/Edicy/wysihtml5 * * Author: Christopher Blum (https://github.com/tiff) * Secondary author of extended features: Oliver Pulges (https://github.com/pulges) * * Copyright (C) 2012 XING AG * Licensed under the MIT license (MIT) * */ var wysihtml5 = { version: "0.4.15", // namespaces commands: {}, dom: {}, quirks: {}, toolbar: {}, lang: {}, selection: {}, views: {}, INVISIBLE_SPACE: "\uFEFF", EMPTY_FUNCTION: function() {}, ELEMENT_NODE: 1, TEXT_NODE: 3, BACKSPACE_KEY: 8, ENTER_KEY: 13, ESCAPE_KEY: 27, SPACE_KEY: 32, DELETE_KEY: 46 }; ;/** * Rangy, a cross-browser JavaScript range and selection library * http://code.google.com/p/rangy/ * * Copyright 2014, Tim Down * Licensed under the MIT license. * Version: 1.3alpha.20140804 * Build date: 4 August 2014 */ (function(factory, global) { if (typeof define == "function" && define.amd) { // AMD. Register as an anonymous module. define(factory); /* TODO: look into this properly. } else if (typeof exports == "object") { // Node/CommonJS style for Browserify module.exports = factory; */ } else { // No AMD or CommonJS support so we place Rangy in a global variable global.rangy = factory(); } })(function() { var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined"; // Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START // are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113. var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; // Minimal set of methods required for DOM Level 2 Range compliance var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore", "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents", "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"]; var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"]; // Subset of TextRange's full set of methods that we're interested in var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "moveToElementText", "parentElement", "select", "setEndPoint", "getBoundingClientRect"]; /*----------------------------------------------------------------------------------------------------------------*/ // Trio of functions taken from Peter Michaux's article: // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(o, p) { var t = typeof o[p]; return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown"; } function isHostObject(o, p) { return !!(typeof o[p] == OBJECT && o[p]); } function isHostProperty(o, p) { return typeof o[p] != UNDEFINED; } // Creates a convenience function to save verbose repeated calls to tests functions function createMultiplePropertyTest(testFunc) { return function(o, props) { var i = props.length; while (i--) { if (!testFunc(o, props[i])) { return false; } } return true; }; } // Next trio of functions are a convenience to save verbose repeated calls to previous two functions var areHostMethods = createMultiplePropertyTest(isHostMethod); var areHostObjects = createMultiplePropertyTest(isHostObject); var areHostProperties = createMultiplePropertyTest(isHostProperty); function isTextRange(range) { return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties); } function getBody(doc) { return isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0]; } var modules = {}; var api = { version: "1.3alpha.20140804", initialized: false, supported: true, util: { isHostMethod: isHostMethod, isHostObject: isHostObject, isHostProperty: isHostProperty, areHostMethods: areHostMethods, areHostObjects: areHostObjects, areHostProperties: areHostProperties, isTextRange: isTextRange, getBody: getBody }, features: {}, modules: modules, config: { alertOnFail: true, alertOnWarn: false, preferTextRange: false, autoInitialize: (typeof rangyAutoInitialize == UNDEFINED) ? true : rangyAutoInitialize } }; function consoleLog(msg) { if (isHostObject(window, "console") && isHostMethod(window.console, "log")) { window.console.log(msg); } } function alertOrLog(msg, shouldAlert) { if (shouldAlert) { window.alert(msg); } else { consoleLog(msg); } } function fail(reason) { api.initialized = true; api.supported = false; alertOrLog("Rangy is not supported on this page in your browser. Reason: " + reason, api.config.alertOnFail); } api.fail = fail; function warn(msg) { alertOrLog("Rangy warning: " + msg, api.config.alertOnWarn); } api.warn = warn; // Add utility extend() method if ({}.hasOwnProperty) { api.util.extend = function(obj, props, deep) { var o, p; for (var i in props) { if (props.hasOwnProperty(i)) { o = obj[i]; p = props[i]; if (deep && o !== null && typeof o == "object" && p !== null && typeof p == "object") { api.util.extend(o, p, true); } obj[i] = p; } } // Special case for toString, which does not show up in for...in loops in IE <= 8 if (props.hasOwnProperty("toString")) { obj.toString = props.toString; } return obj; }; } else { fail("hasOwnProperty not supported"); } // Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not (function() { var el = document.createElement("div"); el.appendChild(document.createElement("span")); var slice = [].slice; var toArray; try { if (slice.call(el.childNodes, 0)[0].nodeType == 1) { toArray = function(arrayLike) { return slice.call(arrayLike, 0); }; } } catch (e) {} if (!toArray) { toArray = function(arrayLike) { var arr = []; for (var i = 0, len = arrayLike.length; i < len; ++i) { arr[i] = arrayLike[i]; } return arr; }; } api.util.toArray = toArray; })(); // Very simple event handler wrapper function that doesn't attempt to solve issues such as "this" handling or // normalization of event properties var addListener; if (isHostMethod(document, "addEventListener")) { addListener = function(obj, eventType, listener) { obj.addEventListener(eventType, listener, false); }; } else if (isHostMethod(document, "attachEvent")) { addListener = function(obj, eventType, listener) { obj.attachEvent("on" + eventType, listener); }; } else { fail("Document does not have required addEventListener or attachEvent method"); } api.util.addListener = addListener; var initListeners = []; function getErrorDesc(ex) { return ex.message || ex.description || String(ex); } // Initialization function init() { if (api.initialized) { return; } var testRange; var implementsDomRange = false, implementsTextRange = false; // First, perform basic feature tests if (isHostMethod(document, "createRange")) { testRange = document.createRange(); if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) { implementsDomRange = true; } } var body = getBody(document); if (!body || body.nodeName.toLowerCase() != "body") { fail("No body element found"); return; } if (body && isHostMethod(body, "createTextRange")) { testRange = body.createTextRange(); if (isTextRange(testRange)) { implementsTextRange = true; } } if (!implementsDomRange && !implementsTextRange) { fail("Neither Range nor TextRange are available"); return; } api.initialized = true; api.features = { implementsDomRange: implementsDomRange, implementsTextRange: implementsTextRange }; // Initialize modules var module, errorMessage; for (var moduleName in modules) { if ( (module = modules[moduleName]) instanceof Module ) { module.init(module, api); } } // Call init listeners for (var i = 0, len = initListeners.length; i < len; ++i) { try { initListeners[i](api); } catch (ex) { errorMessage = "Rangy init listener threw an exception. Continuing. Detail: " + getErrorDesc(ex); consoleLog(errorMessage); } } } // Allow external scripts to initialize this library in case it's loaded after the document has loaded api.init = init; // Execute listener immediately if already initialized api.addInitListener = function(listener) { if (api.initialized) { listener(api); } else { initListeners.push(listener); } }; var shimListeners = []; api.addShimListener = function(listener) { shimListeners.push(listener); }; function shim(win) { win = win || window; init(); // Notify listeners for (var i = 0, len = shimListeners.length; i < len; ++i) { shimListeners[i](win); } } api.shim = api.createMissingNativeApi = shim; function Module(name, dependencies, initializer) { this.name = name; this.dependencies = dependencies; this.initialized = false; this.supported = false; this.initializer = initializer; } Module.prototype = { init: function() { var requiredModuleNames = this.dependencies || []; for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) { moduleName = requiredModuleNames[i]; requiredModule = modules[moduleName]; if (!requiredModule || !(requiredModule instanceof Module)) { throw new Error("required module '" + moduleName + "' not found"); } requiredModule.init(); if (!requiredModule.supported) { throw new Error("required module '" + moduleName + "' not supported"); } } // Now run initializer this.initializer(this); }, fail: function(reason) { this.initialized = true; this.supported = false; throw new Error("Module '" + this.name + "' failed to load: " + reason); }, warn: function(msg) { api.warn("Module " + this.name + ": " + msg); }, deprecationNotice: function(deprecated, replacement) { api.warn("DEPRECATED: " + deprecated + " in module " + this.name + "is deprecated. Please use " + replacement + " instead"); }, createError: function(msg) { return new Error("Error in Rangy " + this.name + " module: " + msg); } }; function createModule(isCore, name, dependencies, initFunc) { var newModule = new Module(name, dependencies, function(module) { if (!module.initialized) { module.initialized = true; try { initFunc(api, module); module.supported = true; } catch (ex) { var errorMessage = "Module '" + name + "' failed to load: " + getErrorDesc(ex); consoleLog(errorMessage); } } }); modules[name] = newModule; } api.createModule = function(name) { // Allow 2 or 3 arguments (second argument is an optional array of dependencies) var initFunc, dependencies; if (arguments.length == 2) { initFunc = arguments[1]; dependencies = []; } else { initFunc = arguments[2]; dependencies = arguments[1]; } var module = createModule(false, name, dependencies, initFunc); // Initialize the module immediately if the core is already initialized if (api.initialized) { module.init(); } }; api.createCoreModule = function(name, dependencies, initFunc) { createModule(true, name, dependencies, initFunc); }; /*----------------------------------------------------------------------------------------------------------------*/ // Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately function RangePrototype() {} api.RangePrototype = RangePrototype; api.rangePrototype = new RangePrototype(); function SelectionPrototype() {} api.selectionPrototype = new SelectionPrototype(); /*----------------------------------------------------------------------------------------------------------------*/ // Wait for document to load before running tests var docReady = false; var loadHandler = function(e) { if (!docReady) { docReady = true; if (!api.initialized && api.config.autoInitialize) { init(); } } }; // Test whether we have window and document objects that we will need if (typeof window == UNDEFINED) { fail("No window found"); return; } if (typeof document == UNDEFINED) { fail("No document found"); return; } if (isHostMethod(document, "addEventListener")) { document.addEventListener("DOMContentLoaded", loadHandler, false); } // Add a fallback in case the DOMContentLoaded event isn't supported addListener(window, "load", loadHandler); /*----------------------------------------------------------------------------------------------------------------*/ // DOM utility methods used by Rangy api.createCoreModule("DomUtil", [], function(api, module) { var UNDEF = "undefined"; var util = api.util; // Perform feature tests if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) { module.fail("document missing a Node creation method"); } if (!util.isHostMethod(document, "getElementsByTagName")) { module.fail("document missing getElementsByTagName method"); } var el = document.createElement("div"); if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) { module.fail("Incomplete Element implementation"); } // innerHTML is required for Range's createContextualFragment method if (!util.isHostProperty(el, "innerHTML")) { module.fail("Element is missing innerHTML property"); } var textNode = document.createTextNode("test"); if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) || !util.areHostProperties(textNode, ["data"]))) { module.fail("Incomplete Text Node implementation"); } /*----------------------------------------------------------------------------------------------------------------*/ // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that // contains just the document as a single element and the value searched for is the document. var arrayContains = /*Array.prototype.indexOf ? function(arr, val) { return arr.indexOf(val) > -1; }:*/ function(arr, val) { var i = arr.length; while (i--) { if (arr[i] === val) { return true; } } return false; }; // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI function isHtmlNamespace(node) { var ns; return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml"); } function parentElement(node) { var parent = node.parentNode; return (parent.nodeType == 1) ? parent : null; } function getNodeIndex(node) { var i = 0; while( (node = node.previousSibling) ) { ++i; } return i; } function getNodeLength(node) { switch (node.nodeType) { case 7: case 10: return 0; case 3: case 8: return node.length; default: return node.childNodes.length; } } function getCommonAncestor(node1, node2) { var ancestors = [], n; for (n = node1; n; n = n.parentNode) { ancestors.push(n); } for (n = node2; n; n = n.parentNode) { if (arrayContains(ancestors, n)) { return n; } } return null; } function isAncestorOf(ancestor, descendant, selfIsAncestor) { var n = selfIsAncestor ? descendant : descendant.parentNode; while (n) { if (n === ancestor) { return true; } else { n = n.parentNode; } } return false; } function isOrIsAncestorOf(ancestor, descendant) { return isAncestorOf(ancestor, descendant, true); } function getClosestAncestorIn(node, ancestor, selfIsAncestor) { var p, n = selfIsAncestor ? node : node.parentNode; while (n) { p = n.parentNode; if (p === ancestor) { return n; } n = p; } return null; } function isCharacterDataNode(node) { var t = node.nodeType; return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment } function isTextOrCommentNode(node) { if (!node) { return false; } var t = node.nodeType; return t == 3 || t == 8 ; // Text or Comment } function insertAfter(node, precedingNode) { var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode; if (nextNode) { parent.insertBefore(node, nextNode); } else { parent.appendChild(node); } return node; } // Note that we cannot use splitText() because it is bugridden in IE 9. function splitDataNode(node, index, positionsToPreserve) { var newNode = node.cloneNode(false); newNode.deleteData(0, index); node.deleteData(index, node.length - index); insertAfter(newNode, node); // Preserve positions if (positionsToPreserve) { for (var i = 0, position; position = positionsToPreserve[i++]; ) { // Handle case where position was inside the portion of node after the split point if (position.node == node && position.offset > index) { position.node = newNode; position.offset -= index; } // Handle the case where the position is a node offset within node's parent else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) { ++position.offset; } } } return newNode; } function getDocument(node) { if (node.nodeType == 9) { return node; } else if (typeof node.ownerDocument != UNDEF) { return node.ownerDocument; } else if (typeof node.document != UNDEF) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); } else { throw module.createError("getDocument: no document found for node"); } } function getWindow(node) { var doc = getDocument(node); if (typeof doc.defaultView != UNDEF) { return doc.defaultView; } else if (typeof doc.parentWindow != UNDEF) { return doc.parentWindow; } else { throw module.createError("Cannot get a window object for node"); } } function getIframeDocument(iframeEl) { if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument; } else if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow.document; } else { throw module.createError("getIframeDocument: No Document object found for iframe element"); } } function getIframeWindow(iframeEl) { if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow; } else if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument.defaultView; } else { throw module.createError("getIframeWindow: No Window object found for iframe element"); } } // This looks bad. Is it worth it? function isWindow(obj) { return obj && util.isHostMethod(obj, "setTimeout") && util.isHostObject(obj, "document"); } function getContentDocument(obj, module, methodName) { var doc; if (!obj) { doc = document; } // Test if a DOM node has been passed and obtain a document object for it if so else if (util.isHostProperty(obj, "nodeType")) { doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == "iframe") ? getIframeDocument(obj) : getDocument(obj); } // Test if the doc parameter appears to be a Window object else if (isWindow(obj)) { doc = obj.document; } if (!doc) { throw module.createError(methodName + "(): Parameter must be a Window object or DOM node"); } return doc; } function getRootContainer(node) { var parent; while ( (parent = node.parentNode) ) { node = parent; } return node; } function comparePoints(nodeA, offsetA, nodeB, offsetB) { // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing var nodeC, root, childA, childB, n; if (nodeA == nodeB) { // Case 1: nodes are the same return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) { // Case 2: node C (container B or an ancestor) is a child node of A return offsetA <= getNodeIndex(nodeC) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) { // Case 3: node C (container A or an ancestor) is a child node of B return getNodeIndex(nodeC) < offsetB ? -1 : 1; } else { root = getCommonAncestor(nodeA, nodeB); if (!root) { throw new Error("comparePoints error: nodes have no common ancestor"); } // Case 4: containers are siblings or descendants of siblings childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true); childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true); if (childA === childB) { // This shouldn't be possible throw module.createError("comparePoints got to case 4 and childA and childB are the same!"); } else { n = root.firstChild; while (n) { if (n === childA) { return -1; } else if (n === childB) { return 1; } n = n.nextSibling; } } } } /*----------------------------------------------------------------------------------------------------------------*/ // Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried var crashyTextNodes = false; function isBrokenNode(node) { var n; try { n = node.parentNode; return false; } catch (e) { return true; } } (function() { var el = document.createElement("b"); el.innerHTML = "1"; var textNode = el.firstChild; el.innerHTML = "<br>"; crashyTextNodes = isBrokenNode(textNode); api.features.crashyTextNodes = crashyTextNodes; })(); /*----------------------------------------------------------------------------------------------------------------*/ function inspectNode(node) { if (!node) { return "[No node]"; } if (crashyTextNodes && isBrokenNode(node)) { return "[Broken node]"; } if (isCharacterDataNode(node)) { return '"' + node.data + '"'; } if (node.nodeType == 1) { var idAttr = node.id ? ' id="' + node.id + '"' : ""; return "<" + node.nodeName + idAttr + ">[index:" + getNodeIndex(node) + ",length:" + node.childNodes.length + "][" + (node.innerHTML || "[innerHTML not supported]").slice(0, 25) + "]"; } return node.nodeName; } function fragmentFromNodeChildren(node) { var fragment = getDocument(node).createDocumentFragment(), child; while ( (child = node.firstChild) ) { fragment.appendChild(child); } return fragment; } var getComputedStyleProperty; if (typeof window.getComputedStyle != UNDEF) { getComputedStyleProperty = function(el, propName) { return getWindow(el).getComputedStyle(el, null)[propName]; }; } else if (typeof document.documentElement.currentStyle != UNDEF) { getComputedStyleProperty = function(el, propName) { return el.currentStyle[propName]; }; } else { module.fail("No means of obtaining computed style properties found"); } function NodeIterator(root) { this.root = root; this._next = root; } NodeIterator.prototype = { _current: null, hasNext: function() { return !!this._next; }, next: function() { var n = this._current = this._next; var child, next; if (this._current) { child = n.firstChild; if (child) { this._next = child; } else { next = null; while ((n !== this.root) && !(next = n.nextSibling)) { n = n.parentNode; } this._next = next; } } return this._current; }, detach: function() { this._current = this._next = this.root = null; } }; function createIterator(root) { return new NodeIterator(root); } function DomPosition(node, offset) { this.node = node; this.offset = offset; } DomPosition.prototype = { equals: function(pos) { return !!pos && this.node === pos.node && this.offset == pos.offset; }, inspect: function() { return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]"; }, toString: function() { return this.inspect(); } }; function DOMException(codeName) { this.code = this[codeName]; this.codeName = codeName; this.message = "DOMException: " + this.codeName; } DOMException.prototype = { INDEX_SIZE_ERR: 1, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INVALID_STATE_ERR: 11, INVALID_NODE_TYPE_ERR: 24 }; DOMException.prototype.toString = function() { return this.message; }; api.dom = { arrayContains: arrayContains, isHtmlNamespace: isHtmlNamespace, parentElement: parentElement, getNodeIndex: getNodeIndex, getNodeLength: getNodeLength, getCommonAncestor: getCommonAncestor, isAncestorOf: isAncestorOf, isOrIsAncestorOf: isOrIsAncestorOf, getClosestAncestorIn: getClosestAncestorIn, isCharacterDataNode: isCharacterDataNode, isTextOrCommentNode: isTextOrCommentNode, insertAfter: insertAfter, splitDataNode: splitDataNode, getDocument: getDocument, getWindow: getWindow, getIframeWindow: getIframeWindow, getIframeDocument: getIframeDocument, getBody: util.getBody, isWindow: isWindow, getContentDocument: getContentDocument, getRootContainer: getRootContainer, comparePoints: comparePoints, isBrokenNode: isBrokenNode, inspectNode: inspectNode, getComputedStyleProperty: getComputedStyleProperty, fragmentFromNodeChildren: fragmentFromNodeChildren, createIterator: createIterator, DomPosition: DomPosition }; api.DOMException = DOMException; }); /*----------------------------------------------------------------------------------------------------------------*/ // Pure JavaScript implementation of DOM Range api.createCoreModule("DomRange", ["DomUtil"], function(api, module) { var dom = api.dom; var util = api.util; var DomPosition = dom.DomPosition; var DOMException = api.DOMException; var isCharacterDataNode = dom.isCharacterDataNode; var getNodeIndex = dom.getNodeIndex; var isOrIsAncestorOf = dom.isOrIsAncestorOf; var getDocument = dom.getDocument; var comparePoints = dom.comparePoints; var splitDataNode = dom.splitDataNode; var getClosestAncestorIn = dom.getClosestAncestorIn; var getNodeLength = dom.getNodeLength; var arrayContains = dom.arrayContains; var getRootContainer = dom.getRootContainer; var crashyTextNodes = api.features.crashyTextNodes; /*----------------------------------------------------------------------------------------------------------------*/ // Utility functions function isNonTextPartiallySelected(node, range) { return (node.nodeType != 3) && (isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer)); } function getRangeDocument(range) { return range.document || getDocument(range.startContainer); } function getBoundaryBeforeNode(node) { return new DomPosition(node.parentNode, getNodeIndex(node)); } function getBoundaryAfterNode(node) { return new DomPosition(node.parentNode, getNodeIndex(node) + 1); } function insertNodeAtPosition(node, n, o) { var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node; if (isCharacterDataNode(n)) { if (o == n.length) { dom.insertAfter(node, n); } else { n.parentNode.insertBefore(node, o == 0 ? n : splitDataNode(n, o)); } } else if (o >= n.childNodes.length) { n.appendChild(node); } else { n.insertBefore(node, n.childNodes[o]); } return firstNodeInserted; } function rangesIntersect(rangeA, rangeB, touchingIsIntersecting) { assertRangeValid(rangeA); assertRangeValid(rangeB); if (getRangeDocument(rangeB) != getRangeDocument(rangeA)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } var startComparison = comparePoints(rangeA.startContainer, rangeA.startOffset, rangeB.endContainer, rangeB.endOffset), endComparison = comparePoints(rangeA.endContainer, rangeA.endOffset, rangeB.startContainer, rangeB.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; } function cloneSubtree(iterator) { var partiallySelected; for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { partiallySelected = iterator.isPartiallySelectedSubtree(); node = node.cloneNode(!partiallySelected); if (partiallySelected) { subIterator = iterator.getSubtreeIterator(); node.appendChild(cloneSubtree(subIterator)); subIterator.detach(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function iterateSubtree(rangeIterator, func, iteratorState) { var it, n; iteratorState = iteratorState || { stop: false }; for (var node, subRangeIterator; node = rangeIterator.next(); ) { if (rangeIterator.isPartiallySelectedSubtree()) { if (func(node) === false) { iteratorState.stop = true; return; } else { // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of // the node selected by the Range. subRangeIterator = rangeIterator.getSubtreeIterator(); iterateSubtree(subRangeIterator, func, iteratorState); subRangeIterator.detach(); if (iteratorState.stop) { return; } } } else { // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its // descendants it = dom.createIterator(node); while ( (n = it.next()) ) { if (func(n) === false) { iteratorState.stop = true; return; } } } } } function deleteSubtree(iterator) { var subIterator; while (iterator.next()) { if (iterator.isPartiallySelectedSubtree()) { subIterator = iterator.getSubtreeIterator(); deleteSubtree(subIterator); subIterator.detach(); } else { iterator.remove(); } } } function extractSubtree(iterator) { for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { if (iterator.isPartiallySelectedSubtree()) { node = node.cloneNode(false); subIterator = iterator.getSubtreeIterator(); node.appendChild(extractSubtree(subIterator)); subIterator.detach(); } else { iterator.remove(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function getNodesInRange(range, nodeTypes, filter) { var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex; var filterExists = !!filter; if (filterNodeTypes) { regex = new RegExp("^(" + nodeTypes.join("|") + ")$"); } var nodes = []; iterateSubtree(new RangeIterator(range, false), function(node) { if (filterNodeTypes && !regex.test(node.nodeType)) { return; } if (filterExists && !filter(node)) { return; } // Don't include a boundary container if it is a character data node and the range does not contain any // of its character data. See issue 190. var sc = range.startContainer; if (node == sc && isCharacterDataNode(sc) && range.startOffset == sc.length) { return; } var ec = range.endContainer; if (node == ec && isCharacterDataNode(ec) && range.endOffset == 0) { return; } nodes.push(node); }); return nodes; } function inspect(range) { var name = (typeof range.getName == "undefined") ? "Range" : range.getName(); return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " + dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]"; } /*----------------------------------------------------------------------------------------------------------------*/ // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange) function RangeIterator(range, clonePartiallySelectedTextNodes) { this.range = range; this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes; if (!range.collapsed) { this.sc = range.startContainer; this.so = range.startOffset; this.ec = range.endContainer; this.eo = range.endOffset; var root = range.commonAncestorContainer; if (this.sc === this.ec && isCharacterDataNode(this.sc)) { this.isSingleCharacterDataNode = true; this._first = this._last = this._next = this.sc; } else { this._first = this._next = (this.sc === root && !isCharacterDataNode(this.sc)) ? this.sc.childNodes[this.so] : getClosestAncestorIn(this.sc, root, true); this._last = (this.ec === root && !isCharacterDataNode(this.ec)) ? this.ec.childNodes[this.eo - 1] : getClosestAncestorIn(this.ec, root, true); } } } RangeIterator.prototype = { _current: null, _next: null, _first: null, _last: null, isSingleCharacterDataNode: false, reset: function() { this._current = null; this._next = this._first; }, hasNext: function() { return !!this._next; }, next: function() { // Move to next node var current = this._current = this._next; if (current) { this._next = (current !== this._last) ? current.nextSibling : null; // Check for partially selected text nodes if (isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) { if (current === this.ec) { (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo); } if (this._current === this.sc) { (current = current.cloneNode(true)).deleteData(0, this.so); } } } return current; }, remove: function() { var current = this._current, start, end; if (isCharacterDataNode(current) && (current === this.sc || current === this.ec)) { start = (current === this.sc) ? this.so : 0; end = (current === this.ec) ? this.eo : current.length; if (start != end) { current.deleteData(start, end - start); } } else { if (current.parentNode) { current.parentNode.removeChild(current); } else { } } }, // Checks if the current node is partially selected isPartiallySelectedSubtree: function() { var current = this._current; return isNonTextPartiallySelected(current, this.range); }, getSubtreeIterator: function() { var subRange; if (this.isSingleCharacterDataNode) { subRange = this.range.cloneRange(); subRange.collapse(false); } else { subRange = new Range(getRangeDocument(this.range)); var current = this._current; var startContainer = current, startOffset = 0, endContainer = current, endOffset = getNodeLength(current); if (isOrIsAncestorOf(current, this.sc)) { startContainer = this.sc; startOffset = this.so; } if (isOrIsAncestorOf(current, this.ec)) { endContainer = this.ec; endOffset = this.eo; } updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset); } return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes); }, detach: function() { this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null; } }; /*----------------------------------------------------------------------------------------------------------------*/ var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10]; var rootContainerNodeTypes = [2, 9, 11]; var readonlyNodeTypes = [5, 6, 10, 12]; var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11]; var surroundNodeTypes = [1, 3, 4, 5, 7, 8]; function createAncestorFinder(nodeTypes) { return function(node, selfIsAncestor) { var t, n = selfIsAncestor ? node : node.parentNode; while (n) { t = n.nodeType; if (arrayContains(nodeTypes, t)) { return n; } n = n.parentNode; } return null; }; } var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] ); var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes); var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] ); function assertNoDocTypeNotationEntityAncestor(node, allowSelf) { if (getDocTypeNotationEntityAncestor(node, allowSelf)) { throw new DOMException("INVALID_NODE_TYPE_ERR"); } } function assertValidNodeType(node, invalidTypes) { if (!arrayContains(invalidTypes, node.nodeType)) { throw new DOMException("INVALID_NODE_TYPE_ERR"); } } function assertValidOffset(node, offset) { if (offset < 0 || offset > (isCharacterDataNode(node) ? node.length : node.childNodes.length)) { throw new DOMException("INDEX_SIZE_ERR"); } } function assertSameDocumentOrFragment(node1, node2) { if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } function assertNodeNotReadOnly(node) { if (getReadonlyAncestor(node, true)) { throw new DOMException("NO_MODIFICATION_ALLOWED_ERR"); } } function assertNode(node, codeName) { if (!node) { throw new DOMException(codeName); } } function isOrphan(node) { return (crashyTextNodes && dom.isBrokenNode(node)) || !arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true); } function isValidOffset(node, offset) { return offset <= (isCharacterDataNode(node) ? node.length : node.childNodes.length); } function isRangeValid(range) { return (!!range.startContainer && !!range.endContainer && !isOrphan(range.startContainer) && !isOrphan(range.endContainer) && isValidOffset(range.startContainer, range.startOffset) && isValidOffset(range.endContainer, range.endOffset)); } function assertRangeValid(range) { if (!isRangeValid(range)) { throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")"); } } /*----------------------------------------------------------------------------------------------------------------*/ // Test the browser's innerHTML support to decide how to implement createContextualFragment var styleEl = document.createElement("style"); var htmlParsingConforms = false; try { styleEl.innerHTML = "<b>x</b>"; htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node } catch (e) { // IE 6 and 7 throw } api.features.htmlParsingConforms = htmlParsingConforms; var createContextualFragment = htmlParsingConforms ? // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See // discussion and base code for this implementation at issue 67. // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface // Thanks to Aleks Williams. function(fragmentStr) { // "Let node the context object's start's node." var node = this.startContainer; var doc = getDocument(node); // "If the context object's start's node is null, raise an INVALID_STATE_ERR // exception and abort these steps." if (!node) { throw new DOMException("INVALID_STATE_ERR"); } // "Let element be as follows, depending on node's interface:" // Document, Document Fragment: null var el = null; // "Element: node" if (node.nodeType == 1) { el = node; // "Text, Comment: node's parentElement" } else if (isCharacterDataNode(node)) { el = dom.parentElement(node); } // "If either element is null or element's ownerDocument is an HTML document // and element's local name is "html" and element's namespace is the HTML // namespace" if (el === null || ( el.nodeName == "HTML" && dom.isHtmlNamespace(getDocument(el).documentElement) && dom.isHtmlNamespace(el) )) { // "let element be a new Element with "body" as its local name and the HTML // namespace as its namespace."" el = doc.createElement("body"); } else { el = el.cloneNode(false); } // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm." // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm." // "In either case, the algorithm must be invoked with fragment as the input // and element as the context element." el.innerHTML = fragmentStr; // "If this raises an exception, then abort these steps. Otherwise, let new // children be the nodes returned." // "Let fragment be a new DocumentFragment." // "Append all new children to fragment." // "Return fragment." return dom.fragmentFromNodeChildren(el); } : // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that // previous versions of Rangy used (with the exception of using a body element rather than a div) function(fragmentStr) { var doc = getRangeDocument(this); var el = doc.createElement("body"); el.innerHTML = fragmentStr; return dom.fragmentFromNodeChildren(el); }; function splitRangeBoundaries(range, positionsToPreserve) { assertRangeValid(range); var sc = range.startContainer, so = range.startOffset, ec = range.endContainer, eo = range.endOffset; var startEndSame = (sc === ec); if (isCharacterDataNode(ec) && eo > 0 && eo < ec.length) { splitDataNode(ec, eo, positionsToPreserve); } if (isCharacterDataNode(sc) && so > 0 && so < sc.length) { sc = splitDataNode(sc, so, positionsToPreserve); if (startEndSame) { eo -= so; ec = sc; } else if (ec == sc.parentNode && eo >= getNodeIndex(sc)) { eo++; } so = 0; } range.setStartAndEnd(sc, so, ec, eo); } function rangeToHtml(range) { assertRangeValid(range); var container = range.commonAncestorContainer.parentNode.cloneNode(false); container.appendChild( range.cloneContents() ); return container.innerHTML; } /*----------------------------------------------------------------------------------------------------------------*/ var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; var s2s = 0, s2e = 1, e2e = 2, e2s = 3; var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3; util.extend(api.rangePrototype, { compareBoundaryPoints: function(how, range) { assertRangeValid(this); assertSameDocumentOrFragment(this.startContainer, range.startContainer); var nodeA, offsetA, nodeB, offsetB; var prefixA = (how == e2s || how == s2s) ? "start" : "end"; var prefixB = (how == s2e || how == s2s) ? "start" : "end"; nodeA = this[prefixA + "Container"]; offsetA = this[prefixA + "Offset"]; nodeB = range[prefixB + "Container"]; offsetB = range[prefixB + "Offset"]; return comparePoints(nodeA, offsetA, nodeB, offsetB); }, insertNode: function(node) { assertRangeValid(this); assertValidNodeType(node, insertableNodeTypes); assertNodeNotReadOnly(this.startContainer); if (isOrIsAncestorOf(node, this.startContainer)) { throw new DOMException("HIERARCHY_REQUEST_ERR"); } // No check for whether the container of the start of the Range is of a type that does not allow // children of the type of node: the browser's DOM implementation should do this for us when we attempt // to add the node var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset); this.setStartBefore(firstNodeInserted); }, cloneContents: function() { assertRangeValid(this); var clone, frag; if (this.collapsed) { return getRangeDocument(this).createDocumentFragment(); } else { if (this.startContainer === this.endContainer && isCharacterDataNode(this.startContainer)) { clone = this.startContainer.cloneNode(true); clone.data = clone.data.slice(this.startOffset, this.endOffset); frag = getRangeDocument(this).createDocumentFragment(); frag.appendChild(clone); return frag; } else { var iterator = new RangeIterator(this, true); clone = cloneSubtree(iterator); iterator.detach(); } return clone; } }, canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, surroundContents: function(node) { assertValidNodeType(node, surroundNodeTypes); if (!this.canSurroundContents()) { throw new DOMException("INVALID_STATE_ERR"); } // Extract the contents var content = this.extractContents(); // Clear the children of the node if (node.hasChildNodes()) { while (node.lastChild) { node.removeChild(node.lastChild); } } // Insert the new node and add the extracted contents insertNodeAtPosition(node, this.startContainer, this.startOffset); node.appendChild(content); this.selectNode(node); }, cloneRange: function() { assertRangeValid(this); var range = new Range(getRangeDocument(this)); var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = this[prop]; } return range; }, toString: function() { assertRangeValid(this); var sc = this.startContainer; if (sc === this.endContainer && isCharacterDataNode(sc)) { return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : ""; } else { var textParts = [], iterator = new RangeIterator(this, true); iterateSubtree(iterator, function(node) { // Accept only text or CDATA nodes, not comments if (node.nodeType == 3 || node.nodeType == 4) { textParts.push(node.data); } }); iterator.detach(); return textParts.join(""); } }, // The methods below are all non-standard. The following batch were introduced by Mozilla but have since // been removed from Mozilla. compareNode: function(node) { assertRangeValid(this); var parent = node.parentNode; var nodeIndex = getNodeIndex(node); if (!parent) { throw new DOMException("NOT_FOUND_ERR"); } var startComparison = this.comparePoint(parent, nodeIndex), endComparison = this.comparePoint(parent, nodeIndex + 1); if (startComparison < 0) { // Node starts before return (endComparison > 0) ? n_b_a : n_b; } else { return (endComparison > 0) ? n_a : n_i; } }, comparePoint: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); if (comparePoints(node, offset, this.startContainer, this.startOffset) < 0) { return -1; } else if (comparePoints(node, offset, this.endContainer, this.endOffset) > 0) { return 1; } return 0; }, createContextualFragment: createContextualFragment, toHtml: function() { return rangeToHtml(this); }, // touchingIsIntersecting determines whether this method considers a node that borders a range intersects // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default) intersectsNode: function(node, touchingIsIntersecting) { assertRangeValid(this); assertNode(node, "NOT_FOUND_ERR"); if (getDocument(node) !== getRangeDocument(this)) { return false; } var parent = node.parentNode, offset = getNodeIndex(node); assertNode(parent, "NOT_FOUND_ERR"); var startComparison = comparePoints(parent, offset, this.endContainer, this.endOffset), endComparison = comparePoints(parent, offset + 1, this.startContainer, this.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; }, isPointInRange: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); return (comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) && (comparePoints(node, offset, this.endContainer, this.endOffset) <= 0); }, // The methods below are non-standard and invented by me. // Sharing a boundary start-to-end or end-to-start does not count as intersection. intersectsRange: function(range) { return rangesIntersect(this, range, false); }, // Sharing a boundary start-to-end or end-to-start does count as intersection. intersectsOrTouchesRange: function(range) { return rangesIntersect(this, range, true); }, intersection: function(range) { if (this.intersectsRange(range)) { var startComparison = comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset), endComparison = comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset); var intersectionRange = this.cloneRange(); if (startComparison == -1) { intersectionRange.setStart(range.startContainer, range.startOffset); } if (endComparison == 1) { intersectionRange.setEnd(range.endContainer, range.endOffset); } return intersectionRange; } return null; }, union: function(range) { if (this.intersectsOrTouchesRange(range)) { var unionRange = this.cloneRange(); if (comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) { unionRange.setStart(range.startContainer, range.startOffset); } if (comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) { unionRange.setEnd(range.endContainer, range.endOffset); } return unionRange; } else { throw new DOMException("Ranges do not intersect"); } }, containsNode: function(node, allowPartial) { if (allowPartial) { return this.intersectsNode(node, false); } else { return this.compareNode(node) == n_i; } }, containsNodeContents: function(node) { return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, getNodeLength(node)) <= 0; }, containsRange: function(range) { var intersection = this.intersection(range); return intersection !== null && range.equals(intersection); }, containsNodeText: function(node) { var nodeRange = this.cloneRange(); nodeRange.selectNode(node); var textNodes = nodeRange.getNodes([3]); if (textNodes.length > 0) { nodeRange.setStart(textNodes[0], 0); var lastTextNode = textNodes.pop(); nodeRange.setEnd(lastTextNode, lastTextNode.length); return this.containsRange(nodeRange); } else { return this.containsNodeContents(node); } }, getNodes: function(nodeTypes, filter) { assertRangeValid(this); return getNodesInRange(this, nodeTypes, filter); }, getDocument: function() { return getRangeDocument(this); }, collapseBefore: function(node) { this.setEndBefore(node); this.collapse(false); }, collapseAfter: function(node) { this.setStartAfter(node); this.collapse(true); }, getBookmark: function(containerNode) { var doc = getRangeDocument(this); var preSelectionRange = api.createRange(doc); containerNode = containerNode || dom.getBody(doc); preSelectionRange.selectNodeContents(containerNode); var range = this.intersection(preSelectionRange); var start = 0, end = 0; if (range) { preSelectionRange.setEnd(range.startContainer, range.startOffset); start = preSelectionRange.toString().length; end = start + range.toString().length; } return { start: start, end: end, containerNode: containerNode }; }, moveToBookmark: function(bookmark) { var containerNode = bookmark.containerNode; var charIndex = 0; this.setStart(containerNode, 0); this.collapse(true); var nodeStack = [containerNode], node, foundStart = false, stop = false; var nextCharIndex, i, childNodes; while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) { nextCharIndex = charIndex + node.length; if (!foundStart && bookmark.start >= charIndex && bookmark.start <= nextCharIndex) { this.setStart(node, bookmark.start - charIndex); foundStart = true; } if (foundStart && bookmark.end >= charIndex && bookmark.end <= nextCharIndex) { this.setEnd(node, bookmark.end - charIndex); stop = true; } charIndex = nextCharIndex; } else { childNodes = node.childNodes; i = childNodes.length; while (i--) { nodeStack.push(childNodes[i]); } } } }, getName: function() { return "DomRange"; }, equals: function(range) { return Range.rangesEqual(this, range); }, isValid: function() { return isRangeValid(this); }, inspect: function() { return inspect(this); }, detach: function() { // In DOM4, detach() is now a no-op. } }); function copyComparisonConstantsToObject(obj) { obj.START_TO_START = s2s; obj.START_TO_END = s2e; obj.END_TO_END = e2e; obj.END_TO_START = e2s; obj.NODE_BEFORE = n_b; obj.NODE_AFTER = n_a; obj.NODE_BEFORE_AND_AFTER = n_b_a; obj.NODE_INSIDE = n_i; } function copyComparisonConstants(constructor) { copyComparisonConstantsToObject(constructor); copyComparisonConstantsToObject(constructor.prototype); } function createRangeContentRemover(remover, boundaryUpdater) { return function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer; var iterator = new RangeIterator(this, true); // Work out where to position the range after content removal var node, boundary; if (sc !== root) { node = getClosestAncestorIn(sc, root, true); boundary = getBoundaryAfterNode(node); sc = boundary.node; so = boundary.offset; } // Check none of the range is read-only iterateSubtree(iterator, assertNodeNotReadOnly); iterator.reset(); // Remove the content var returnValue = remover(iterator); iterator.detach(); // Move to the new position boundaryUpdater(this, sc, so, sc, so); return returnValue; }; } function createPrototypeRange(constructor, boundaryUpdater) { function createBeforeAfterNodeSetter(isBefore, isStart) { return function(node) { assertValidNodeType(node, beforeAfterNodeTypes); assertValidNodeType(getRootContainer(node), rootContainerNodeTypes); var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node); (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset); }; } function setRangeStart(range, node, offset) { var ec = range.endContainer, eo = range.endOffset; if (node !== range.startContainer || offset !== range.startOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(ec) || comparePoints(node, offset, ec, eo) == 1) { ec = node; eo = offset; } boundaryUpdater(range, node, offset, ec, eo); } } function setRangeEnd(range, node, offset) { var sc = range.startContainer, so = range.startOffset; if (node !== range.endContainer || offset !== range.endOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(sc) || comparePoints(node, offset, sc, so) == -1) { sc = node; so = offset; } boundaryUpdater(range, sc, so, node, offset); } } // Set up inheritance var F = function() {}; F.prototype = api.rangePrototype; constructor.prototype = new F(); util.extend(constructor.prototype, { setStart: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeStart(this, node, offset); }, setEnd: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeEnd(this, node, offset); }, /** * Convenience method to set a range's start and end boundaries. Overloaded as follows: * - Two parameters (node, offset) creates a collapsed range at that position * - Three parameters (node, startOffset, endOffset) creates a range contained with node starting at * startOffset and ending at endOffset * - Four parameters (startNode, startOffset, endNode, endOffset) creates a range starting at startOffset in * startNode and ending at endOffset in endNode */ setStartAndEnd: function() { var args = arguments; var sc = args[0], so = args[1], ec = sc, eo = so; switch (args.length) { case 3: eo = args[2]; break; case 4: ec = args[2]; eo = args[3]; break; } boundaryUpdater(this, sc, so, ec, eo); }, setBoundary: function(node, offset, isStart) { this["set" + (isStart ? "Start" : "End")](node, offset); }, setStartBefore: createBeforeAfterNodeSetter(true, true), setStartAfter: createBeforeAfterNodeSetter(false, true), setEndBefore: createBeforeAfterNodeSetter(true, false), setEndAfter: createBeforeAfterNodeSetter(false, false), collapse: function(isStart) { assertRangeValid(this); if (isStart) { boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset); } else { boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset); } }, selectNodeContents: function(node) { assertNoDocTypeNotationEntityAncestor(node, true); boundaryUpdater(this, node, 0, node, getNodeLength(node)); }, selectNode: function(node) { assertNoDocTypeNotationEntityAncestor(node, false); assertValidNodeType(node, beforeAfterNodeTypes); var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node); boundaryUpdater(this, start.node, start.offset, end.node, end.offset); }, extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater), deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater), canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && isNonTextPartiallySelected(iterator._first, this) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, splitBoundaries: function() { splitRangeBoundaries(this); }, splitBoundariesPreservingPositions: function(positionsToPreserve) { splitRangeBoundaries(this, positionsToPreserve); }, normalizeBoundaries: function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset; var mergeForward = function(node) { var sibling = node.nextSibling; if (sibling && sibling.nodeType == node.nodeType) { ec = node; eo = node.length; node.appendData(sibling.data); sibling.parentNode.removeChild(sibling); } }; var mergeBackward = function(node) { var sibling = node.previousSibling; if (sibling && sibling.nodeType == node.nodeType) { sc = node; var nodeLength = node.length; so = sibling.length; node.insertData(0, sibling.data); sibling.parentNode.removeChild(sibling); if (sc == ec) { eo += so; ec = sc; } else if (ec == node.parentNode) { var nodeIndex = getNodeIndex(node); if (eo == nodeIndex) { ec = node; eo = nodeLength; } else if (eo > nodeIndex) { eo--; } } } }; var normalizeStart = true; if (isCharacterDataNode(ec)) { if (ec.length == eo) { mergeForward(ec); } } else { if (eo > 0) { var endNode = ec.childNodes[eo - 1]; if (endNode && isCharacterDataNode(endNode)) { mergeForward(endNode); } } normalizeStart = !this.collapsed; } if (normalizeStart) { if (isCharacterDataNode(sc)) { if (so == 0) { mergeBackward(sc); } } else { if (so < sc.childNodes.length) { var startNode = sc.childNodes[so]; if (startNode && isCharacterDataNode(startNode)) { mergeBackward(startNode); } } } } else { sc = ec; so = eo; } boundaryUpdater(this, sc, so, ec, eo); }, collapseToPoint: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); this.setStartAndEnd(node, offset); } }); copyComparisonConstants(constructor); } /*----------------------------------------------------------------------------------------------------------------*/ // Updates commonAncestorContainer and collapsed after boundary change function updateCollapsedAndCommonAncestor(range) { range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); range.commonAncestorContainer = range.collapsed ? range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer); } function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) { range.startContainer = startContainer; range.startOffset = startOffset; range.endContainer = endContainer; range.endOffset = endOffset; range.document = dom.getDocument(startContainer); updateCollapsedAndCommonAncestor(range); } function Range(doc) { this.startContainer = doc; this.startOffset = 0; this.endContainer = doc; this.endOffset = 0; this.document = doc; updateCollapsedAndCommonAncestor(this); } createPrototypeRange(Range, updateBoundaries); util.extend(Range, { rangeProperties: rangeProperties, RangeIterator: RangeIterator, copyComparisonConstants: copyComparisonConstants, createPrototypeRange: createPrototypeRange, inspect: inspect, toHtml: rangeToHtml, getRangeDocument: getRangeDocument, rangesEqual: function(r1, r2) { return r1.startContainer === r2.startContainer && r1.startOffset === r2.startOffset && r1.endContainer === r2.endContainer && r1.endOffset === r2.endOffset; } }); api.DomRange = Range; }); /*----------------------------------------------------------------------------------------------------------------*/ // Wrappers for the browser's native DOM Range and/or TextRange implementation api.createCoreModule("WrappedRange", ["DomRange"], function(api, module) { var WrappedRange, WrappedTextRange; var dom = api.dom; var util = api.util; var DomPosition = dom.DomPosition; var DomRange = api.DomRange; var getBody = dom.getBody; var getContentDocument = dom.getContentDocument; var isCharacterDataNode = dom.isCharacterDataNode; /*----------------------------------------------------------------------------------------------------------------*/ if (api.features.implementsDomRange) { // This is a wrapper around the browser's native DOM Range. It has two aims: // - Provide workarounds for specific browser bugs // - provide convenient extensions, which are inherited from Rangy's DomRange (function() { var rangeProto; var rangeProperties = DomRange.rangeProperties; function updateRangeProperties(range) { var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = range.nativeRange[prop]; } // Fix for broken collapsed property in IE 9. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); } function updateNativeRange(range, startContainer, startOffset, endContainer, endOffset) { var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset); var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset); var nativeRangeDifferent = !range.equals(range.nativeRange); // Always set both boundaries for the benefit of IE9 (see issue 35) if (startMoved || endMoved || nativeRangeDifferent) { range.setEnd(endContainer, endOffset); range.setStart(startContainer, startOffset); } } var createBeforeAfterNodeSetter; WrappedRange = function(range) { if (!range) { throw module.createError("WrappedRange: Range must be specified"); } this.nativeRange = range; updateRangeProperties(this); }; DomRange.createPrototypeRange(WrappedRange, updateNativeRange); rangeProto = WrappedRange.prototype; rangeProto.selectNode = function(node) { this.nativeRange.selectNode(node); updateRangeProperties(this); }; rangeProto.cloneContents = function() { return this.nativeRange.cloneContents(); }; // Due to a long-standing Firefox bug that I have not been able to find a reliable way to detect, // insertNode() is never delegated to the native range. rangeProto.surroundContents = function(node) { this.nativeRange.surroundContents(node); updateRangeProperties(this); }; rangeProto.collapse = function(isStart) { this.nativeRange.collapse(isStart); updateRangeProperties(this); }; rangeProto.cloneRange = function() { return new WrappedRange(this.nativeRange.cloneRange()); }; rangeProto.refresh = function() { updateRangeProperties(this); }; rangeProto.toString = function() { return this.nativeRange.toString(); }; // Create test range and node for feature detection var testTextNode = document.createTextNode("test"); getBody(document).appendChild(testTextNode); var range = document.createRange(); /*--------------------------------------------------------------------------------------------------------*/ // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and // correct for it range.setStart(testTextNode, 0); range.setEnd(testTextNode, 0); try { range.setStart(testTextNode, 1); rangeProto.setStart = function(node, offset) { this.nativeRange.setStart(node, offset); updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { this.nativeRange.setEnd(node, offset); updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name) { return function(node) { this.nativeRange[name](node); updateRangeProperties(this); }; }; } catch(ex) { rangeProto.setStart = function(node, offset) { try { this.nativeRange.setStart(node, offset); } catch (ex) { this.nativeRange.setEnd(node, offset); this.nativeRange.setStart(node, offset); } updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { try { this.nativeRange.setEnd(node, offset); } catch (ex) { this.nativeRange.setStart(node, offset); this.nativeRange.setEnd(node, offset); } updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name, oppositeName) { return function(node) { try { this.nativeRange[name](node); } catch (ex) { this.nativeRange[oppositeName](node); this.nativeRange[name](node); } updateRangeProperties(this); }; }; } rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore"); rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter"); rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore"); rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter"); /*--------------------------------------------------------------------------------------------------------*/ // Always use DOM4-compliant selectNodeContents implementation: it's simpler and less code than testing // whether the native implementation can be trusted rangeProto.selectNodeContents = function(node) { this.setStartAndEnd(node, 0, dom.getNodeLength(node)); }; /*--------------------------------------------------------------------------------------------------------*/ // Test for and correct WebKit bug that has the behaviour of compareBoundaryPoints round the wrong way for // constants START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738 range.selectNodeContents(testTextNode); range.setEnd(testTextNode, 3); var range2 = document.createRange(); range2.selectNodeContents(testTextNode); range2.setEnd(testTextNode, 4); range2.setStart(testTextNode, 2); if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 && range.compareBoundaryPoints(range.END_TO_START, range2) == 1) { // This is the wrong way round, so correct for it rangeProto.compareBoundaryPoints = function(type, range) { range = range.nativeRange || range; if (type == range.START_TO_END) { type = range.END_TO_START; } else if (type == range.END_TO_START) { type = range.START_TO_END; } return this.nativeRange.compareBoundaryPoints(type, range); }; } else { rangeProto.compareBoundaryPoints = function(type, range) { return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range); }; } /*--------------------------------------------------------------------------------------------------------*/ // Test for IE 9 deleteContents() and extractContents() bug and correct it. See issue 107. var el = document.createElement("div"); el.innerHTML = "123"; var textNode = el.firstChild; var body = getBody(document); body.appendChild(el); range.setStart(textNode, 1); range.setEnd(textNode, 2); range.deleteContents(); if (textNode.data == "13") { // Behaviour is correct per DOM4 Range so wrap the browser's implementation of deleteContents() and // extractContents() rangeProto.deleteContents = function() { this.nativeRange.deleteContents(); updateRangeProperties(this); }; rangeProto.extractContents = function() { var frag = this.nativeRange.extractContents(); updateRangeProperties(this); return frag; }; } else { } body.removeChild(el); body = null; /*--------------------------------------------------------------------------------------------------------*/ // Test for existence of createContextualFragment and delegate to it if it exists if (util.isHostMethod(range, "createContextualFragment")) { rangeProto.createContextualFragment = function(fragmentStr) { return this.nativeRange.createContextualFragment(fragmentStr); }; } /*--------------------------------------------------------------------------------------------------------*/ // Clean up getBody(document).removeChild(testTextNode); rangeProto.getName = function() { return "WrappedRange"; }; api.WrappedRange = WrappedRange; api.createNativeRange = function(doc) { doc = getContentDocument(doc, module, "createNativeRange"); return doc.createRange(); }; })(); } if (api.features.implementsTextRange) { /* This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement() method. For example, in the following (where pipes denote the selection boundaries): <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul> var range = document.selection.createRange(); alert(range.parentElement().id); // Should alert "ul" but alerts "b" This method returns the common ancestor node of the following: - the parentElement() of the textRange - the parentElement() of the textRange after calling collapse(true) - the parentElement() of the textRange after calling collapse(false) */ var getTextRangeContainerElement = function(textRange) { var parentEl = textRange.parentElement(); var range = textRange.duplicate(); range.collapse(true); var startEl = range.parentElement(); range = textRange.duplicate(); range.collapse(false); var endEl = range.parentElement(); var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl); return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer); }; var textRangeIsCollapsed = function(textRange) { return textRange.compareEndPoints("StartToEnd", textRange) == 0; }; // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started // out as an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) // but has grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange // bugs, handling for inputs and images, plus optimizations. var getTextRangeBoundaryPosition = function(textRange, wholeRangeContainerElement, isStart, isCollapsed, startInfo) { var workingRange = textRange.duplicate(); workingRange.collapse(isStart); var containerElement = workingRange.parentElement(); // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so // check for that if (!dom.isOrIsAncestorOf(wholeRangeContainerElement, containerElement)) { containerElement = wholeRangeContainerElement; } // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx if (!containerElement.canHaveHTML) { var pos = new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement)); return { boundaryPosition: pos, nodeInfo: { nodeIndex: pos.offset, containerElement: pos.node } }; } var workingNode = dom.getDocument(containerElement).createElement("span"); // Workaround for HTML5 Shiv's insane violation of document.createElement(). See Rangy issue 104 and HTML5 // Shiv issue 64: https://github.com/aFarkas/html5shiv/issues/64 if (workingNode.parentNode) { workingNode.parentNode.removeChild(workingNode); } var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd"; var previousNode, nextNode, boundaryPosition, boundaryNode; var start = (startInfo && startInfo.containerElement == containerElement) ? startInfo.nodeIndex : 0; var childNodeCount = containerElement.childNodes.length; var end = childNodeCount; // Check end first. Code within the loop assumes that the endth child node of the container is definitely // after the range boundary. var nodeIndex = end; while (true) { if (nodeIndex == childNodeCount) { containerElement.appendChild(workingNode); } else { containerElement.insertBefore(workingNode, containerElement.childNodes[nodeIndex]); } workingRange.moveToElementText(workingNode); comparison = workingRange.compareEndPoints(workingComparisonType, textRange); if (comparison == 0 || start == end) { break; } else if (comparison == -1) { if (end == start + 1) { // We know the endth child node is after the range boundary, so we must be done. break; } else { start = nodeIndex; } } else { end = (end == start + 1) ? start : nodeIndex; } nodeIndex = Math.floor((start + end) / 2); containerElement.removeChild(workingNode); } // We've now reached or gone past the boundary of the text range we're interested in // so have identified the node we want boundaryNode = workingNode.nextSibling; if (comparison == -1 && boundaryNode && isCharacterDataNode(boundaryNode)) { // This is a character data node (text, comment, cdata). The working range is collapsed at the start of // the node containing the text range's boundary, so we move the end of the working range to the // boundary point and measure the length of its text to get the boundary's offset within the node. workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange); var offset; if (/[\r\n]/.test(boundaryNode.data)) { /* For the particular case of a boundary within a text node containing rendered line breaks (within a <pre> element, for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts: - Each line break is represented as \r in the text node's data/nodeValue properties - Each line break is represented as \r\n in the TextRange's 'text' property - The 'text' property of the TextRange does not contain trailing line breaks To get round the problem presented by the final fact above, we can use the fact that TextRange's moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily the same as the number of characters it was instructed to move. The simplest approach is to use this to store the characters moved when moving both the start and end of the range to the start of the document body and subtracting the start offset from the end offset (the "move-negative-gazillion" method). However, this is extremely slow when the document is large and the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same problem. Another approach that works is to use moveStart() to move the start boundary of the range up to the end boundary one character at a time and incrementing a counter with the value returned by the moveStart() call. However, the check for whether the start boundary has reached the end boundary is expensive, so this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of the range within the document). The approach used below is a hybrid of the two methods above. It uses the fact that a string containing the TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the text of the TextRange, so the start of the range is moved that length initially and then a character at a time to make up for any trailing line breaks not contained in the 'text' property. This has good performance in most situations compared to the previous two methods. */ var tempRange = workingRange.duplicate(); var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length; offset = tempRange.moveStart("character", rangeLength); while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) { offset++; tempRange.moveStart("character", 1); } } else { offset = workingRange.text.length; } boundaryPosition = new DomPosition(boundaryNode, offset); } else { // If the boundary immediately follows a character data node and this is the end boundary, we should favour // a position within that, and likewise for a start boundary preceding a character data node previousNode = (isCollapsed || !isStart) && workingNode.previousSibling; nextNode = (isCollapsed || isStart) && workingNode.nextSibling; if (nextNode && isCharacterDataNode(nextNode)) { boundaryPosition = new DomPosition(nextNode, 0); } else if (previousNode && isCharacterDataNode(previousNode)) { boundaryPosition = new DomPosition(previousNode, previousNode.data.length); } else { boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode)); } } // Clean up workingNode.parentNode.removeChild(workingNode); return { boundaryPosition: boundaryPosition, nodeInfo: { nodeIndex: nodeIndex, containerElement: containerElement } }; }; // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that // node. This function started out as an optimized version of code found in Tim Cameron Ryan's IERange // (http://code.google.com/p/ierange/) var createBoundaryTextRange = function(boundaryPosition, isStart) { var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset; var doc = dom.getDocument(boundaryPosition.node); var workingNode, childNodes, workingRange = getBody(doc).createTextRange(); var nodeIsDataNode = isCharacterDataNode(boundaryPosition.node); if (nodeIsDataNode) { boundaryNode = boundaryPosition.node; boundaryParent = boundaryNode.parentNode; } else { childNodes = boundaryPosition.node.childNodes; boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null; boundaryParent = boundaryPosition.node; } // Position the range immediately before the node containing the boundary workingNode = doc.createElement("span"); // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within // the element rather than immediately before or after it workingNode.innerHTML = "&#feff;"; // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12 if (boundaryNode) { boundaryParent.insertBefore(workingNode, boundaryNode); } else { boundaryParent.appendChild(workingNode); } workingRange.moveToElementText(workingNode); workingRange.collapse(!isStart); // Clean up boundaryParent.removeChild(workingNode); // Move the working range to the text offset, if required if (nodeIsDataNode) { workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset); } return workingRange; }; /*------------------------------------------------------------------------------------------------------------*/ // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a // prototype WrappedTextRange = function(textRange) { this.textRange = textRange; this.refresh(); }; WrappedTextRange.prototype = new DomRange(document); WrappedTextRange.prototype.refresh = function() { var start, end, startBoundary; // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that. var rangeContainerElement = getTextRangeContainerElement(this.textRange); if (textRangeIsCollapsed(this.textRange)) { end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true).boundaryPosition; } else { startBoundary = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false); start = startBoundary.boundaryPosition; // An optimization used here is that if the start and end boundaries have the same parent element, the // search scope for the end boundary can be limited to exclude the portion of the element that precedes // the start boundary end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false, startBoundary.nodeInfo).boundaryPosition; } this.setStart(start.node, start.offset); this.setEnd(end.node, end.offset); }; WrappedTextRange.prototype.getName = function() { return "WrappedTextRange"; }; DomRange.copyComparisonConstants(WrappedTextRange); var rangeToTextRange = function(range) { if (range.collapsed) { return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); } else { var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false); var textRange = getBody( DomRange.getRangeDocument(range) ).createTextRange(); textRange.setEndPoint("StartToStart", startRange); textRange.setEndPoint("EndToEnd", endRange); return textRange; } }; WrappedTextRange.rangeToTextRange = rangeToTextRange; WrappedTextRange.prototype.toTextRange = function() { return rangeToTextRange(this); }; api.WrappedTextRange = WrappedTextRange; // IE 9 and above have both implementations and Rangy makes both available. The next few lines sets which // implementation to use by default. if (!api.features.implementsDomRange || api.config.preferTextRange) { // Add WrappedTextRange as the Range property of the global object to allow expression like Range.END_TO_END to work var globalObj = (function() { return this; })(); if (typeof globalObj.Range == "undefined") { globalObj.Range = WrappedTextRange; } api.createNativeRange = function(doc) { doc = getContentDocument(doc, module, "createNativeRange"); return getBody(doc).createTextRange(); }; api.WrappedRange = WrappedTextRange; } } api.createRange = function(doc) { doc = getContentDocument(doc, module, "createRange"); return new api.WrappedRange(api.createNativeRange(doc)); }; api.createRangyRange = function(doc) { doc = getContentDocument(doc, module, "createRangyRange"); return new DomRange(doc); }; api.createIframeRange = function(iframeEl) { module.deprecationNotice("createIframeRange()", "createRange(iframeEl)"); return api.createRange(iframeEl); }; api.createIframeRangyRange = function(iframeEl) { module.deprecationNotice("createIframeRangyRange()", "createRangyRange(iframeEl)"); return api.createRangyRange(iframeEl); }; api.addShimListener(function(win) { var doc = win.document; if (typeof doc.createRange == "undefined") { doc.createRange = function() { return api.createRange(doc); }; } doc = win = null; }); }); /*----------------------------------------------------------------------------------------------------------------*/ // This module creates a selection object wrapper that conforms as closely as possible to the Selection specification // in the HTML Editing spec (http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections) api.createCoreModule("WrappedSelection", ["DomRange", "WrappedRange"], function(api, module) { api.config.checkSelectionRanges = true; var BOOLEAN = "boolean"; var NUMBER = "number"; var dom = api.dom; var util = api.util; var isHostMethod = util.isHostMethod; var DomRange = api.DomRange; var WrappedRange = api.WrappedRange; var DOMException = api.DOMException; var DomPosition = dom.DomPosition; var getNativeSelection; var selectionIsCollapsed; var features = api.features; var CONTROL = "Control"; var getDocument = dom.getDocument; var getBody = dom.getBody; var rangesEqual = DomRange.rangesEqual; // Utility function to support direction parameters in the API that may be a string ("backward" or "forward") or a // Boolean (true for backwards). function isDirectionBackward(dir) { return (typeof dir == "string") ? /^backward(s)?$/i.test(dir) : !!dir; } function getWindow(win, methodName) { if (!win) { return window; } else if (dom.isWindow(win)) { return win; } else if (win instanceof WrappedSelection) { return win.win; } else { var doc = dom.getContentDocument(win, module, methodName); return dom.getWindow(doc); } } function getWinSelection(winParam) { return getWindow(winParam, "getWinSelection").getSelection(); } function getDocSelection(winParam) { return getWindow(winParam, "getDocSelection").document.selection; } function winSelectionIsBackward(sel) { var backward = false; if (sel.anchorNode) { backward = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1); } return backward; } // Test for the Range/TextRange and Selection features required // Test for ability to retrieve selection var implementsWinGetSelection = isHostMethod(window, "getSelection"), implementsDocSelection = util.isHostObject(document, "selection"); features.implementsWinGetSelection = implementsWinGetSelection; features.implementsDocSelection = implementsDocSelection; var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange); if (useDocumentSelection) { getNativeSelection = getDocSelection; api.isSelectionValid = function(winParam) { var doc = getWindow(winParam, "isSelectionValid").document, nativeSel = doc.selection; // Check whether the selection TextRange is actually contained within the correct document return (nativeSel.type != "None" || getDocument(nativeSel.createRange().parentElement()) == doc); }; } else if (implementsWinGetSelection) { getNativeSelection = getWinSelection; api.isSelectionValid = function() { return true; }; } else { module.fail("Neither document.selection or window.getSelection() detected."); } api.getNativeSelection = getNativeSelection; var testSelection = getNativeSelection(); var testRange = api.createNativeRange(document); var body = getBody(document); // Obtaining a range from a selection var selectionHasAnchorAndFocus = util.areHostProperties(testSelection, ["anchorNode", "focusNode", "anchorOffset", "focusOffset"]); features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus; // Test for existence of native selection extend() method var selectionHasExtend = isHostMethod(testSelection, "extend"); features.selectionHasExtend = selectionHasExtend; // Test if rangeCount exists var selectionHasRangeCount = (typeof testSelection.rangeCount == NUMBER); features.selectionHasRangeCount = selectionHasRangeCount; var selectionSupportsMultipleRanges = false; var collapsedNonEditableSelectionsSupported = true; var addRangeBackwardToNative = selectionHasExtend ? function(nativeSelection, range) { var doc = DomRange.getRangeDocument(range); var endRange = api.createRange(doc); endRange.collapseToPoint(range.endContainer, range.endOffset); nativeSelection.addRange(getNativeRange(endRange)); nativeSelection.extend(range.startContainer, range.startOffset); } : null; if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) && typeof testSelection.rangeCount == NUMBER && features.implementsDomRange) { (function() { // Previously an iframe was used but this caused problems in some circumstances in IE, so tests are // performed on the current document's selection. See issue 109. // Note also that if a selection previously existed, it is wiped by these tests. This should usually be fine // because initialization usually happens when the document loads, but could be a problem for a script that // loads and initializes Rangy later. If anyone complains, code could be added to save and restore the // selection. var sel = window.getSelection(); if (sel) { // Store the current selection var originalSelectionRangeCount = sel.rangeCount; var selectionHasMultipleRanges = (originalSelectionRangeCount > 1); var originalSelectionRanges = []; var originalSelectionBackward = winSelectionIsBackward(sel); for (var i = 0; i < originalSelectionRangeCount; ++i) { originalSelectionRanges[i] = sel.getRangeAt(i); } // Create some test elements var body = getBody(document); var testEl = body.appendChild( document.createElement("div") ); testEl.contentEditable = "false"; var textNode = testEl.appendChild( document.createTextNode("\u00a0\u00a0\u00a0") ); // Test whether the native selection will allow a collapsed selection within a non-editable element var r1 = document.createRange(); r1.setStart(textNode, 1); r1.collapse(true); sel.addRange(r1); collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1); sel.removeAllRanges(); // Test whether the native selection is capable of supporting multiple ranges. if (!selectionHasMultipleRanges) { // Doing the original feature test here in Chrome 36 (and presumably later versions) prints a // console error of "Discontiguous selection is not supported." that cannot be suppressed. There's // nothing we can do about this while retaining the feature test so we have to resort to a browser // sniff. I'm not happy about it. See // https://code.google.com/p/chromium/issues/detail?id=399791 var chromeMatch = window.navigator.appVersion.match(/Chrome\/(.*?) /); if (chromeMatch && parseInt(chromeMatch[1]) >= 36) { selectionSupportsMultipleRanges = false; } else { var r2 = r1.cloneRange(); r1.setStart(textNode, 0); r2.setEnd(textNode, 3); r2.setStart(textNode, 2); sel.addRange(r1); sel.addRange(r2); selectionSupportsMultipleRanges = (sel.rangeCount == 2); } } // Clean up body.removeChild(testEl); sel.removeAllRanges(); for (i = 0; i < originalSelectionRangeCount; ++i) { if (i == 0 && originalSelectionBackward) { if (addRangeBackwardToNative) { addRangeBackwardToNative(sel, originalSelectionRanges[i]); } else { api.warn("Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend"); sel.addRange(originalSelectionRanges[i]); } } else { sel.addRange(originalSelectionRanges[i]); } } } })(); } features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges; features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported; // ControlRanges var implementsControlRange = false, testControlRange; if (body && isHostMethod(body, "createControlRange")) { testControlRange = body.createControlRange(); if (util.areHostProperties(testControlRange, ["item", "add"])) { implementsControlRange = true; } } features.implementsControlRange = implementsControlRange; // Selection collapsedness if (selectionHasAnchorAndFocus) { selectionIsCollapsed = function(sel) { return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset; }; } else { selectionIsCollapsed = function(sel) { return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false; }; } function updateAnchorAndFocusFromRange(sel, range, backward) { var anchorPrefix = backward ? "end" : "start", focusPrefix = backward ? "start" : "end"; sel.anchorNode = range[anchorPrefix + "Container"]; sel.anchorOffset = range[anchorPrefix + "Offset"]; sel.focusNode = range[focusPrefix + "Container"]; sel.focusOffset = range[focusPrefix + "Offset"]; } function updateAnchorAndFocusFromNativeSelection(sel) { var nativeSel = sel.nativeSelection; sel.anchorNode = nativeSel.anchorNode; sel.anchorOffset = nativeSel.anchorOffset; sel.focusNode = nativeSel.focusNode; sel.focusOffset = nativeSel.focusOffset; } function updateEmptySelection(sel) { sel.anchorNode = sel.focusNode = null; sel.anchorOffset = sel.focusOffset = 0; sel.rangeCount = 0; sel.isCollapsed = true; sel._ranges.length = 0; } function getNativeRange(range) { var nativeRange; if (range instanceof DomRange) { nativeRange = api.createNativeRange(range.getDocument()); nativeRange.setEnd(range.endContainer, range.endOffset); nativeRange.setStart(range.startContainer, range.startOffset); } else if (range instanceof WrappedRange) { nativeRange = range.nativeRange; } else if (features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) { nativeRange = range; } return nativeRange; } function rangeContainsSingleElement(rangeNodes) { if (!rangeNodes.length || rangeNodes[0].nodeType != 1) { return false; } for (var i = 1, len = rangeNodes.length; i < len; ++i) { if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) { return false; } } return true; } function getSingleElementFromRange(range) { var nodes = range.getNodes(); if (!rangeContainsSingleElement(nodes)) { throw module.createError("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element"); } return nodes[0]; } // Simple, quick test which only needs to distinguish between a TextRange and a ControlRange function isTextRange(range) { return !!range && typeof range.text != "undefined"; } function updateFromTextRange(sel, range) { // Create a Range from the selected TextRange var wrappedRange = new WrappedRange(range); sel._ranges = [wrappedRange]; updateAnchorAndFocusFromRange(sel, wrappedRange, false); sel.rangeCount = 1; sel.isCollapsed = wrappedRange.collapsed; } function updateControlSelection(sel) { // Update the wrapped selection based on what's now in the native selection sel._ranges.length = 0; if (sel.docSelection.type == "None") { updateEmptySelection(sel); } else { var controlRange = sel.docSelection.createRange(); if (isTextRange(controlRange)) { // This case (where the selection type is "Control" and calling createRange() on the selection returns // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected // ControlRange have been removed from the ControlRange and removed from the document. updateFromTextRange(sel, controlRange); } else { sel.rangeCount = controlRange.length; var range, doc = getDocument(controlRange.item(0)); for (var i = 0; i < sel.rangeCount; ++i) { range = api.createRange(doc); range.selectNode(controlRange.item(i)); sel._ranges.push(range); } sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed; updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false); } } } function addRangeToControlSelection(sel, range) { var controlRange = sel.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange plus the element // contained by the supplied range var doc = getDocument(controlRange.item(0)); var newControlRange = getBody(doc).createControlRange(); for (var i = 0, len = controlRange.length; i < len; ++i) { newControlRange.add(controlRange.item(i)); } try { newControlRange.add(rangeElement); } catch (ex) { throw module.createError("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)"); } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } var getSelectionRangeAt; if (isHostMethod(testSelection, "getRangeAt")) { // try/catch is present because getRangeAt() must have thrown an error in some browser and some situation. // Unfortunately, I didn't write a comment about the specifics and am now scared to take it out. Let that be a // lesson to us all, especially me. getSelectionRangeAt = function(sel, index) { try { return sel.getRangeAt(index); } catch (ex) { return null; } }; } else if (selectionHasAnchorAndFocus) { getSelectionRangeAt = function(sel) { var doc = getDocument(sel.anchorNode); var range = api.createRange(doc); range.setStartAndEnd(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset); // Handle the case when the selection was selected backwards (from the end to the start in the // document) if (range.collapsed !== this.isCollapsed) { range.setStartAndEnd(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset); } return range; }; } function WrappedSelection(selection, docSelection, win) { this.nativeSelection = selection; this.docSelection = docSelection; this._ranges = []; this.win = win; this.refresh(); } WrappedSelection.prototype = api.selectionPrototype; function deleteProperties(sel) { sel.win = sel.anchorNode = sel.focusNode = sel._ranges = null; sel.rangeCount = sel.anchorOffset = sel.focusOffset = 0; sel.detached = true; } var cachedRangySelections = []; function actOnCachedSelection(win, action) { var i = cachedRangySelections.length, cached, sel; while (i--) { cached = cachedRangySelections[i]; sel = cached.selection; if (action == "deleteAll") { deleteProperties(sel); } else if (cached.win == win) { if (action == "delete") { cachedRangySelections.splice(i, 1); return true; } else { return sel; } } } if (action == "deleteAll") { cachedRangySelections.length = 0; } return null; } var getSelection = function(win) { // Check if the parameter is a Rangy Selection object if (win && win instanceof WrappedSelection) { win.refresh(); return win; } win = getWindow(win, "getNativeSelection"); var sel = actOnCachedSelection(win); var nativeSel = getNativeSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null; if (sel) { sel.nativeSelection = nativeSel; sel.docSelection = docSel; sel.refresh(); } else { sel = new WrappedSelection(nativeSel, docSel, win); cachedRangySelections.push( { win: win, selection: sel } ); } return sel; }; api.getSelection = getSelection; api.getIframeSelection = function(iframeEl) { module.deprecationNotice("getIframeSelection()", "getSelection(iframeEl)"); return api.getSelection(dom.getIframeWindow(iframeEl)); }; var selProto = WrappedSelection.prototype; function createControlSelection(sel, ranges) { // Ensure that the selection becomes of type "Control" var doc = getDocument(ranges[0].startContainer); var controlRange = getBody(doc).createControlRange(); for (var i = 0, el, len = ranges.length; i < len; ++i) { el = getSingleElementFromRange(ranges[i]); try { controlRange.add(el); } catch (ex) { throw module.createError("setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)"); } } controlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } // Selecting a range if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) { selProto.removeAllRanges = function() { this.nativeSelection.removeAllRanges(); updateEmptySelection(this); }; var addRangeBackward = function(sel, range) { addRangeBackwardToNative(sel.nativeSelection, range); sel.refresh(); }; if (selectionHasRangeCount) { selProto.addRange = function(range, direction) { if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { if (isDirectionBackward(direction) && selectionHasExtend) { addRangeBackward(this, range); } else { var previousRangeCount; if (selectionSupportsMultipleRanges) { previousRangeCount = this.rangeCount; } else { this.removeAllRanges(); previousRangeCount = 0; } // Clone the native range so that changing the selected range does not affect the selection. // This is contrary to the spec but is the only way to achieve consistency between browsers. See // issue 80. this.nativeSelection.addRange(getNativeRange(range).cloneRange()); // Check whether adding the range was successful this.rangeCount = this.nativeSelection.rangeCount; if (this.rangeCount == previousRangeCount + 1) { // The range was added successfully // Check whether the range that we added to the selection is reflected in the last range extracted from // the selection if (api.config.checkSelectionRanges) { var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1); if (nativeRange && !rangesEqual(nativeRange, range)) { // Happens in WebKit with, for example, a selection placed at the start of a text node range = new WrappedRange(nativeRange); } } this._ranges[this.rangeCount - 1] = range; updateAnchorAndFocusFromRange(this, range, selectionIsBackward(this.nativeSelection)); this.isCollapsed = selectionIsCollapsed(this); } else { // The range was not added successfully. The simplest thing is to refresh this.refresh(); } } } }; } else { selProto.addRange = function(range, direction) { if (isDirectionBackward(direction) && selectionHasExtend) { addRangeBackward(this, range); } else { this.nativeSelection.addRange(getNativeRange(range)); this.refresh(); } }; } selProto.setRanges = function(ranges) { if (implementsControlRange && implementsDocSelection && ranges.length > 1) { createControlSelection(this, ranges); } else { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { this.addRange(ranges[i]); } } }; } else if (isHostMethod(testSelection, "empty") && isHostMethod(testRange, "select") && implementsControlRange && useDocumentSelection) { selProto.removeAllRanges = function() { // Added try/catch as fix for issue #21 try { this.docSelection.empty(); // Check for empty() not working (issue #24) if (this.docSelection.type != "None") { // Work around failure to empty a control selection by instead selecting a TextRange and then // calling empty() var doc; if (this.anchorNode) { doc = getDocument(this.anchorNode); } else if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); if (controlRange.length) { doc = getDocument( controlRange.item(0) ); } } if (doc) { var textRange = getBody(doc).createTextRange(); textRange.select(); this.docSelection.empty(); } } } catch(ex) {} updateEmptySelection(this); }; selProto.addRange = function(range) { if (this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { api.WrappedTextRange.rangeToTextRange(range).select(); this._ranges[0] = range; this.rangeCount = 1; this.isCollapsed = this._ranges[0].collapsed; updateAnchorAndFocusFromRange(this, range, false); } }; selProto.setRanges = function(ranges) { this.removeAllRanges(); var rangeCount = ranges.length; if (rangeCount > 1) { createControlSelection(this, ranges); } else if (rangeCount) { this.addRange(ranges[0]); } }; } else { module.fail("No means of selecting a Range or TextRange was found"); return false; } selProto.getRangeAt = function(index) { if (index < 0 || index >= this.rangeCount) { throw new DOMException("INDEX_SIZE_ERR"); } else { // Clone the range to preserve selection-range independence. See issue 80. return this._ranges[index].cloneRange(); } }; var refreshSelection; if (useDocumentSelection) { refreshSelection = function(sel) { var range; if (api.isSelectionValid(sel.win)) { range = sel.docSelection.createRange(); } else { range = getBody(sel.win.document).createTextRange(); range.collapse(true); } if (sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else if (isTextRange(range)) { updateFromTextRange(sel, range); } else { updateEmptySelection(sel); } }; } else if (isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == NUMBER) { refreshSelection = function(sel) { if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else { sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount; if (sel.rangeCount) { for (var i = 0, len = sel.rangeCount; i < len; ++i) { sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i)); } updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackward(sel.nativeSelection)); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } } }; } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && features.implementsDomRange) { refreshSelection = function(sel) { var range, nativeSel = sel.nativeSelection; if (nativeSel.anchorNode) { range = getSelectionRangeAt(nativeSel, 0); sel._ranges = [range]; sel.rangeCount = 1; updateAnchorAndFocusFromNativeSelection(sel); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } }; } else { module.fail("No means of obtaining a Range or TextRange from the user's selection was found"); return false; } selProto.refresh = function(checkForChanges) { var oldRanges = checkForChanges ? this._ranges.slice(0) : null; var oldAnchorNode = this.anchorNode, oldAnchorOffset = this.anchorOffset; refreshSelection(this); if (checkForChanges) { // Check the range count first var i = oldRanges.length; if (i != this._ranges.length) { return true; } // Now check the direction. Checking the anchor position is the same is enough since we're checking all the // ranges after this if (this.anchorNode != oldAnchorNode || this.anchorOffset != oldAnchorOffset) { return true; } // Finally, compare each range in turn while (i--) { if (!rangesEqual(oldRanges[i], this._ranges[i])) { return true; } } return false; } }; // Removal of a single range var removeRangeManually = function(sel, range) { var ranges = sel.getAllRanges(); sel.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { if (!rangesEqual(range, ranges[i])) { sel.addRange(ranges[i]); } } if (!sel.rangeCount) { updateEmptySelection(sel); } }; if (implementsControlRange && implementsDocSelection) { selProto.removeRange = function(range) { if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange minus the // element contained by the supplied range var doc = getDocument(controlRange.item(0)); var newControlRange = getBody(doc).createControlRange(); var el, removed = false; for (var i = 0, len = controlRange.length; i < len; ++i) { el = controlRange.item(i); if (el !== rangeElement || removed) { newControlRange.add(controlRange.item(i)); } else { removed = true; } } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(this); } else { removeRangeManually(this, range); } }; } else { selProto.removeRange = function(range) { removeRangeManually(this, range); }; } // Detecting if a selection is backward var selectionIsBackward; if (!useDocumentSelection && selectionHasAnchorAndFocus && features.implementsDomRange) { selectionIsBackward = winSelectionIsBackward; selProto.isBackward = function() { return selectionIsBackward(this); }; } else { selectionIsBackward = selProto.isBackward = function() { return false; }; } // Create an alias for backwards compatibility. From 1.3, everything is "backward" rather than "backwards" selProto.isBackwards = selProto.isBackward; // Selection stringifier // This is conformant to the old HTML5 selections draft spec but differs from WebKit and Mozilla's implementation. // The current spec does not yet define this method. selProto.toString = function() { var rangeTexts = []; for (var i = 0, len = this.rangeCount; i < len; ++i) { rangeTexts[i] = "" + this._ranges[i]; } return rangeTexts.join(""); }; function assertNodeInSameDocument(sel, node) { if (sel.win.document != getDocument(node)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } // No current browser conforms fully to the spec for this method, so Rangy's own method is always used selProto.collapse = function(node, offset) { assertNodeInSameDocument(this, node); var range = api.createRange(node); range.collapseToPoint(node, offset); this.setSingleRange(range); this.isCollapsed = true; }; selProto.collapseToStart = function() { if (this.rangeCount) { var range = this._ranges[0]; this.collapse(range.startContainer, range.startOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; selProto.collapseToEnd = function() { if (this.rangeCount) { var range = this._ranges[this.rangeCount - 1]; this.collapse(range.endContainer, range.endOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; // The spec is very specific on how selectAllChildren should be implemented so the native implementation is // never used by Rangy. selProto.selectAllChildren = function(node) { assertNodeInSameDocument(this, node); var range = api.createRange(node); range.selectNodeContents(node); this.setSingleRange(range); }; selProto.deleteFromDocument = function() { // Sepcial behaviour required for IE's control selections if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var element; while (controlRange.length) { element = controlRange.item(0); controlRange.remove(element); element.parentNode.removeChild(element); } this.refresh(); } else if (this.rangeCount) { var ranges = this.getAllRanges(); if (ranges.length) { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { ranges[i].deleteContents(); } // The spec says nothing about what the selection should contain after calling deleteContents on each // range. Firefox moves the selection to where the final selected range was, so we emulate that this.addRange(ranges[len - 1]); } } }; // The following are non-standard extensions selProto.eachRange = function(func, returnValue) { for (var i = 0, len = this._ranges.length; i < len; ++i) { if ( func( this.getRangeAt(i) ) ) { return returnValue; } } }; selProto.getAllRanges = function() { var ranges = []; this.eachRange(function(range) { ranges.push(range); }); return ranges; }; selProto.setSingleRange = function(range, direction) { this.removeAllRanges(); this.addRange(range, direction); }; selProto.callMethodOnEachRange = function(methodName, params) { var results = []; this.eachRange( function(range) { results.push( range[methodName].apply(range, params) ); } ); return results; }; function createStartOrEndSetter(isStart) { return function(node, offset) { var range; if (this.rangeCount) { range = this.getRangeAt(0); range["set" + (isStart ? "Start" : "End")](node, offset); } else { range = api.createRange(this.win.document); range.setStartAndEnd(node, offset); } this.setSingleRange(range, this.isBackward()); }; } selProto.setStart = createStartOrEndSetter(true); selProto.setEnd = createStartOrEndSetter(false); // Add select() method to Range prototype. Any existing selection will be removed. api.rangePrototype.select = function(direction) { getSelection( this.getDocument() ).setSingleRange(this, direction); }; selProto.changeEachRange = function(func) { var ranges = []; var backward = this.isBackward(); this.eachRange(function(range) { func(range); ranges.push(range); }); this.removeAllRanges(); if (backward && ranges.length == 1) { this.addRange(ranges[0], "backward"); } else { this.setRanges(ranges); } }; selProto.containsNode = function(node, allowPartial) { return this.eachRange( function(range) { return range.containsNode(node, allowPartial); }, true ) || false; }; selProto.getBookmark = function(containerNode) { return { backward: this.isBackward(), rangeBookmarks: this.callMethodOnEachRange("getBookmark", [containerNode]) }; }; selProto.moveToBookmark = function(bookmark) { var selRanges = []; for (var i = 0, rangeBookmark, range; rangeBookmark = bookmark.rangeBookmarks[i++]; ) { range = api.createRange(this.win); range.moveToBookmark(rangeBookmark); selRanges.push(range); } if (bookmark.backward) { this.setSingleRange(selRanges[0], "backward"); } else { this.setRanges(selRanges); } }; selProto.toHtml = function() { var rangeHtmls = []; this.eachRange(function(range) { rangeHtmls.push( DomRange.toHtml(range) ); }); return rangeHtmls.join(""); }; if (features.implementsTextRange) { selProto.getNativeTextRange = function() { var sel, textRange; if ( (sel = this.docSelection) ) { var range = sel.createRange(); if (isTextRange(range)) { return range; } else { throw module.createError("getNativeTextRange: selection is a control selection"); } } else if (this.rangeCount > 0) { return api.WrappedTextRange.rangeToTextRange( this.getRangeAt(0) ); } else { throw module.createError("getNativeTextRange: selection contains no range"); } }; } function inspect(sel) { var rangeInspects = []; var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset); var focus = new DomPosition(sel.focusNode, sel.focusOffset); var name = (typeof sel.getName == "function") ? sel.getName() : "Selection"; if (typeof sel.rangeCount != "undefined") { for (var i = 0, len = sel.rangeCount; i < len; ++i) { rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i)); } } return "[" + name + "(Ranges: " + rangeInspects.join(", ") + ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]"; } selProto.getName = function() { return "WrappedSelection"; }; selProto.inspect = function() { return inspect(this); }; selProto.detach = function() { actOnCachedSelection(this.win, "delete"); deleteProperties(this); }; WrappedSelection.detachAll = function() { actOnCachedSelection(null, "deleteAll"); }; WrappedSelection.inspect = inspect; WrappedSelection.isDirectionBackward = isDirectionBackward; api.Selection = WrappedSelection; api.selectionPrototype = selProto; api.addShimListener(function(win) { if (typeof win.getSelection == "undefined") { win.getSelection = function() { return getSelection(win); }; } win = null; }); }); /*----------------------------------------------------------------------------------------------------------------*/ return api; }, this);;/** * Selection save and restore module for Rangy. * Saves and restores user selections using marker invisible elements in the DOM. * * Part of Rangy, a cross-browser JavaScript range and selection library * http://code.google.com/p/rangy/ * * Depends on Rangy core. * * Copyright 2014, Tim Down * Licensed under the MIT license. * Version: 1.3alpha.20140804 * Build date: 4 August 2014 */ (function(factory, global) { if (typeof define == "function" && define.amd) { // AMD. Register as an anonymous module with a dependency on Rangy. define(["rangy"], factory); /* } else if (typeof exports == "object") { // Node/CommonJS style for Browserify module.exports = factory; */ } else { // No AMD or CommonJS support so we use the rangy global variable factory(global.rangy); } })(function(rangy) { rangy.createModule("SaveRestore", ["WrappedRange"], function(api, module) { var dom = api.dom; var markerTextChar = "\ufeff"; function gEBI(id, doc) { return (doc || document).getElementById(id); } function insertRangeBoundaryMarker(range, atStart) { var markerId = "selectionBoundary_" + (+new Date()) + "_" + ("" + Math.random()).slice(2); var markerEl; var doc = dom.getDocument(range.startContainer); // Clone the Range and collapse to the appropriate boundary point var boundaryRange = range.cloneRange(); boundaryRange.collapse(atStart); // Create the marker element containing a single invisible character using DOM methods and insert it markerEl = doc.createElement("span"); markerEl.id = markerId; markerEl.style.lineHeight = "0"; markerEl.style.display = "none"; markerEl.className = "rangySelectionBoundary"; markerEl.appendChild(doc.createTextNode(markerTextChar)); boundaryRange.insertNode(markerEl); return markerEl; } function setRangeBoundary(doc, range, markerId, atStart) { var markerEl = gEBI(markerId, doc); if (markerEl) { range[atStart ? "setStartBefore" : "setEndBefore"](markerEl); markerEl.parentNode.removeChild(markerEl); } else { module.warn("Marker element has been removed. Cannot restore selection."); } } function compareRanges(r1, r2) { return r2.compareBoundaryPoints(r1.START_TO_START, r1); } function saveRange(range, backward) { var startEl, endEl, doc = api.DomRange.getRangeDocument(range), text = range.toString(); if (range.collapsed) { endEl = insertRangeBoundaryMarker(range, false); return { document: doc, markerId: endEl.id, collapsed: true }; } else { endEl = insertRangeBoundaryMarker(range, false); startEl = insertRangeBoundaryMarker(range, true); return { document: doc, startMarkerId: startEl.id, endMarkerId: endEl.id, collapsed: false, backward: backward, toString: function() { return "original text: '" + text + "', new text: '" + range.toString() + "'"; } }; } } function restoreRange(rangeInfo, normalize) { var doc = rangeInfo.document; if (typeof normalize == "undefined") { normalize = true; } var range = api.createRange(doc); if (rangeInfo.collapsed) { var markerEl = gEBI(rangeInfo.markerId, doc); if (markerEl) { markerEl.style.display = "inline"; var previousNode = markerEl.previousSibling; // Workaround for issue 17 if (previousNode && previousNode.nodeType == 3) { markerEl.parentNode.removeChild(markerEl); range.collapseToPoint(previousNode, previousNode.length); } else { range.collapseBefore(markerEl); markerEl.parentNode.removeChild(markerEl); } } else { module.warn("Marker element has been removed. Cannot restore selection."); } } else { setRangeBoundary(doc, range, rangeInfo.startMarkerId, true); setRangeBoundary(doc, range, rangeInfo.endMarkerId, false); } if (normalize) { range.normalizeBoundaries(); } return range; } function saveRanges(ranges, backward) { var rangeInfos = [], range, doc; // Order the ranges by position within the DOM, latest first, cloning the array to leave the original untouched ranges = ranges.slice(0); ranges.sort(compareRanges); for (var i = 0, len = ranges.length; i < len; ++i) { rangeInfos[i] = saveRange(ranges[i], backward); } // Now that all the markers are in place and DOM manipulation over, adjust each range's boundaries to lie // between its markers for (i = len - 1; i >= 0; --i) { range = ranges[i]; doc = api.DomRange.getRangeDocument(range); if (range.collapsed) { range.collapseAfter(gEBI(rangeInfos[i].markerId, doc)); } else { range.setEndBefore(gEBI(rangeInfos[i].endMarkerId, doc)); range.setStartAfter(gEBI(rangeInfos[i].startMarkerId, doc)); } } return rangeInfos; } function saveSelection(win) { if (!api.isSelectionValid(win)) { module.warn("Cannot save selection. This usually happens when the selection is collapsed and the selection document has lost focus."); return null; } var sel = api.getSelection(win); var ranges = sel.getAllRanges(); var backward = (ranges.length == 1 && sel.isBackward()); var rangeInfos = saveRanges(ranges, backward); // Ensure current selection is unaffected if (backward) { sel.setSingleRange(ranges[0], "backward"); } else { sel.setRanges(ranges); } return { win: win, rangeInfos: rangeInfos, restored: false }; } function restoreRanges(rangeInfos) { var ranges = []; // Ranges are in reverse order of appearance in the DOM. We want to restore earliest first to avoid // normalization affecting previously restored ranges. var rangeCount = rangeInfos.length; for (var i = rangeCount - 1; i >= 0; i--) { ranges[i] = restoreRange(rangeInfos[i], true); } return ranges; } function restoreSelection(savedSelection, preserveDirection) { if (!savedSelection.restored) { var rangeInfos = savedSelection.rangeInfos; var sel = api.getSelection(savedSelection.win); var ranges = restoreRanges(rangeInfos), rangeCount = rangeInfos.length; if (rangeCount == 1 && preserveDirection && api.features.selectionHasExtend && rangeInfos[0].backward) { sel.removeAllRanges(); sel.addRange(ranges[0], true); } else { sel.setRanges(ranges); } savedSelection.restored = true; } } function removeMarkerElement(doc, markerId) { var markerEl = gEBI(markerId, doc); if (markerEl) { markerEl.parentNode.removeChild(markerEl); } } function removeMarkers(savedSelection) { var rangeInfos = savedSelection.rangeInfos; for (var i = 0, len = rangeInfos.length, rangeInfo; i < len; ++i) { rangeInfo = rangeInfos[i]; if (rangeInfo.collapsed) { removeMarkerElement(savedSelection.doc, rangeInfo.markerId); } else { removeMarkerElement(savedSelection.doc, rangeInfo.startMarkerId); removeMarkerElement(savedSelection.doc, rangeInfo.endMarkerId); } } } api.util.extend(api, { saveRange: saveRange, restoreRange: restoreRange, saveRanges: saveRanges, restoreRanges: restoreRanges, saveSelection: saveSelection, restoreSelection: restoreSelection, removeMarkerElement: removeMarkerElement, removeMarkers: removeMarkers }); }); }, this);;/* Base.js, version 1.1a Copyright 2006-2010, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ var Base = function() { // dummy }; Base.extend = function(_instance, _static) { // subclass var extend = Base.prototype.extend; // build the prototype Base._prototyping = true; var proto = new this; extend.call(proto, _instance); proto.base = function() { // call this method from any other method to invoke that method's ancestor }; delete Base._prototyping; // create the wrapper for the constructor function //var constructor = proto.constructor.valueOf(); //-dean var constructor = proto.constructor; var klass = proto.constructor = function() { if (!Base._prototyping) { if (this._constructing || this.constructor == klass) { // instantiation this._constructing = true; constructor.apply(this, arguments); delete this._constructing; } else if (arguments[0] != null) { // casting return (arguments[0].extend || extend).call(arguments[0], proto); } } }; // build the class interface klass.ancestor = this; klass.extend = this.extend; klass.forEach = this.forEach; klass.implement = this.implement; klass.prototype = proto; klass.toString = this.toString; klass.valueOf = function(type) { //return (type == "object") ? klass : constructor; //-dean return (type == "object") ? klass : constructor.valueOf(); }; extend.call(klass, _static); // class initialisation if (typeof klass.init == "function") klass.init(); return klass; }; Base.prototype = { extend: function(source, value) { if (arguments.length > 1) { // extending with a name/value pair var ancestor = this[source]; if (ancestor && (typeof value == "function") && // overriding a method? // the valueOf() comparison is to avoid circular references (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && /\bbase\b/.test(value)) { // get the underlying method var method = value.valueOf(); // override value = function() { var previous = this.base || Base.prototype.base; this.base = ancestor; var returnValue = method.apply(this, arguments); this.base = previous; return returnValue; }; // point to the underlying method value.valueOf = function(type) { return (type == "object") ? value : method; }; value.toString = Base.toString; } this[source] = value; } else if (source) { // extending with an object literal var extend = Base.prototype.extend; // if this object has a customised extend method then use it if (!Base._prototyping && typeof this != "function") { extend = this.extend || extend; } var proto = {toSource: null}; // do the "toString" and other methods manually var hidden = ["constructor", "toString", "valueOf"]; // if we are prototyping then include the constructor var i = Base._prototyping ? 0 : 1; while (key = hidden[i++]) { if (source[key] != proto[key]) { extend.call(this, key, source[key]); } } // copy each of the source object's properties to this object for (var key in source) { if (!proto[key]) extend.call(this, key, source[key]); } } return this; } }; // initialise Base = Base.extend({ constructor: function() { this.extend(arguments[0]); } }, { ancestor: Object, version: "1.1", forEach: function(object, block, context) { for (var key in object) { if (this.prototype[key] === undefined) { block.call(context, object[key], key, object); } } }, implement: function() { for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == "function") { // if it's a function, call it arguments[i](this.prototype); } else { // add the interface using the extend method this.prototype.extend(arguments[i]); } } return this; }, toString: function() { return String(this.valueOf()); } });;/** * Detect browser support for specific features */ wysihtml5.browser = (function() { var userAgent = navigator.userAgent, testElement = document.createElement("div"), // Browser sniffing is unfortunately needed since some behaviors are impossible to feature detect isGecko = userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1, isWebKit = userAgent.indexOf("AppleWebKit/") !== -1, isChrome = userAgent.indexOf("Chrome/") !== -1, isOpera = userAgent.indexOf("Opera/") !== -1; function iosVersion(userAgent) { return +((/ipad|iphone|ipod/.test(userAgent) && userAgent.match(/ os (\d+).+? like mac os x/)) || [undefined, 0])[1]; } function androidVersion(userAgent) { return +(userAgent.match(/android (\d+)/) || [undefined, 0])[1]; } function isIE(version, equation) { var rv = -1, re; if (navigator.appName == 'Microsoft Internet Explorer') { re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); } else if (navigator.appName == 'Netscape') { re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})"); } if (re && re.exec(navigator.userAgent) != null) { rv = parseFloat(RegExp.$1); } if (rv === -1) { return false; } if (!version) { return true; } if (!equation) { return version === rv; } if (equation === "<") { return version < rv; } if (equation === ">") { return version > rv; } if (equation === "<=") { return version <= rv; } if (equation === ">=") { return version >= rv; } } return { // Static variable needed, publicly accessible, to be able override it in unit tests USER_AGENT: userAgent, /** * Exclude browsers that are not capable of displaying and handling * contentEditable as desired: * - iPhone, iPad (tested iOS 4.2.2) and Android (tested 2.2) refuse to make contentEditables focusable * - IE < 8 create invalid markup and crash randomly from time to time * * @return {Boolean} */ supported: function() { var userAgent = this.USER_AGENT.toLowerCase(), // Essential for making html elements editable hasContentEditableSupport = "contentEditable" in testElement, // Following methods are needed in order to interact with the contentEditable area hasEditingApiSupport = document.execCommand && document.queryCommandSupported && document.queryCommandState, // document selector apis are only supported by IE 8+, Safari 4+, Chrome and Firefox 3.5+ hasQuerySelectorSupport = document.querySelector && document.querySelectorAll, // contentEditable is unusable in mobile browsers (tested iOS 4.2.2, Android 2.2, Opera Mobile, WebOS 3.05) isIncompatibleMobileBrowser = (this.isIos() && iosVersion(userAgent) < 5) || (this.isAndroid() && androidVersion(userAgent) < 4) || userAgent.indexOf("opera mobi") !== -1 || userAgent.indexOf("hpwos/") !== -1; return hasContentEditableSupport && hasEditingApiSupport && hasQuerySelectorSupport && !isIncompatibleMobileBrowser; }, isTouchDevice: function() { return this.supportsEvent("touchmove"); }, isIos: function() { return (/ipad|iphone|ipod/i).test(this.USER_AGENT); }, isAndroid: function() { return this.USER_AGENT.indexOf("Android") !== -1; }, /** * Whether the browser supports sandboxed iframes * Currently only IE 6+ offers such feature <iframe security="restricted"> * * http://msdn.microsoft.com/en-us/library/ms534622(v=vs.85).aspx * http://blogs.msdn.com/b/ie/archive/2008/01/18/using-frames-more-securely.aspx * * HTML5 sandboxed iframes are still buggy and their DOM is not reachable from the outside (except when using postMessage) */ supportsSandboxedIframes: function() { return isIE(); }, /** * IE6+7 throw a mixed content warning when the src of an iframe * is empty/unset or about:blank * window.querySelector is implemented as of IE8 */ throwsMixedContentWarningWhenIframeSrcIsEmpty: function() { return !("querySelector" in document); }, /** * Whether the caret is correctly displayed in contentEditable elements * Firefox sometimes shows a huge caret in the beginning after focusing */ displaysCaretInEmptyContentEditableCorrectly: function() { return isIE(); }, /** * Opera and IE are the only browsers who offer the css value * in the original unit, thx to the currentStyle object * All other browsers provide the computed style in px via window.getComputedStyle */ hasCurrentStyleProperty: function() { return "currentStyle" in testElement; }, /** * Firefox on OSX navigates through history when hitting CMD + Arrow right/left */ hasHistoryIssue: function() { return isGecko && navigator.platform.substr(0, 3) === "Mac"; }, /** * Whether the browser inserts a <br> when pressing enter in a contentEditable element */ insertsLineBreaksOnReturn: function() { return isGecko; }, supportsPlaceholderAttributeOn: function(element) { return "placeholder" in element; }, supportsEvent: function(eventName) { return "on" + eventName in testElement || (function() { testElement.setAttribute("on" + eventName, "return;"); return typeof(testElement["on" + eventName]) === "function"; })(); }, /** * Opera doesn't correctly fire focus/blur events when clicking in- and outside of iframe */ supportsEventsInIframeCorrectly: function() { return !isOpera; }, /** * Everything below IE9 doesn't know how to treat HTML5 tags * * @param {Object} context The document object on which to check HTML5 support * * @example * wysihtml5.browser.supportsHTML5Tags(document); */ supportsHTML5Tags: function(context) { var element = context.createElement("div"), html5 = "<article>foo</article>"; element.innerHTML = html5; return element.innerHTML.toLowerCase() === html5; }, /** * Checks whether a document supports a certain queryCommand * In particular, Opera needs a reference to a document that has a contentEditable in it's dom tree * in oder to report correct results * * @param {Object} doc Document object on which to check for a query command * @param {String} command The query command to check for * @return {Boolean} * * @example * wysihtml5.browser.supportsCommand(document, "bold"); */ supportsCommand: (function() { // Following commands are supported but contain bugs in some browsers var buggyCommands = { // formatBlock fails with some tags (eg. <blockquote>) "formatBlock": isIE(10, "<="), // When inserting unordered or ordered lists in Firefox, Chrome or Safari, the current selection or line gets // converted into a list (<ul><li>...</li></ul>, <ol><li>...</li></ol>) // IE and Opera act a bit different here as they convert the entire content of the current block element into a list "insertUnorderedList": isIE(), "insertOrderedList": isIE() }; // Firefox throws errors for queryCommandSupported, so we have to build up our own object of supported commands var supported = { "insertHTML": isGecko }; return function(doc, command) { var isBuggy = buggyCommands[command]; if (!isBuggy) { // Firefox throws errors when invoking queryCommandSupported or queryCommandEnabled try { return doc.queryCommandSupported(command); } catch(e1) {} try { return doc.queryCommandEnabled(command); } catch(e2) { return !!supported[command]; } } return false; }; })(), /** * IE: URLs starting with: * www., http://, https://, ftp://, gopher://, mailto:, new:, snews:, telnet:, wasis:, file://, * nntp://, newsrc:, ldap://, ldaps://, outlook:, mic:// and url: * will automatically be auto-linked when either the user inserts them via copy&paste or presses the * space bar when the caret is directly after such an url. * This behavior cannot easily be avoided in IE < 9 since the logic is hardcoded in the mshtml.dll * (related blog post on msdn * http://blogs.msdn.com/b/ieinternals/archive/2009/09/17/prevent-automatic-hyperlinking-in-contenteditable-html.aspx). */ doesAutoLinkingInContentEditable: function() { return isIE(); }, /** * As stated above, IE auto links urls typed into contentEditable elements * Since IE9 it's possible to prevent this behavior */ canDisableAutoLinking: function() { return this.supportsCommand(document, "AutoUrlDetect"); }, /** * IE leaves an empty paragraph in the contentEditable element after clearing it * Chrome/Safari sometimes an empty <div> */ clearsContentEditableCorrectly: function() { return isGecko || isOpera || isWebKit; }, /** * IE gives wrong results for getAttribute */ supportsGetAttributeCorrectly: function() { var td = document.createElement("td"); return td.getAttribute("rowspan") != "1"; }, /** * When clicking on images in IE, Opera and Firefox, they are selected, which makes it easy to interact with them. * Chrome and Safari both don't support this */ canSelectImagesInContentEditable: function() { return isGecko || isIE() || isOpera; }, /** * All browsers except Safari and Chrome automatically scroll the range/caret position into view */ autoScrollsToCaret: function() { return !isWebKit; }, /** * Check whether the browser automatically closes tags that don't need to be opened */ autoClosesUnclosedTags: function() { var clonedTestElement = testElement.cloneNode(false), returnValue, innerHTML; clonedTestElement.innerHTML = "<p><div></div>"; innerHTML = clonedTestElement.innerHTML.toLowerCase(); returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>"; // Cache result by overwriting current function this.autoClosesUnclosedTags = function() { return returnValue; }; return returnValue; }, /** * Whether the browser supports the native document.getElementsByClassName which returns live NodeLists */ supportsNativeGetElementsByClassName: function() { return String(document.getElementsByClassName).indexOf("[native code]") !== -1; }, /** * As of now (19.04.2011) only supported by Firefox 4 and Chrome * See https://developer.mozilla.org/en/DOM/Selection/modify */ supportsSelectionModify: function() { return "getSelection" in window && "modify" in window.getSelection(); }, /** * Opera needs a white space after a <br> in order to position the caret correctly */ needsSpaceAfterLineBreak: function() { return isOpera; }, /** * Whether the browser supports the speech api on the given element * See http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ * * @example * var input = document.createElement("input"); * if (wysihtml5.browser.supportsSpeechApiOn(input)) { * // ... * } */ supportsSpeechApiOn: function(input) { var chromeVersion = userAgent.match(/Chrome\/(\d+)/) || [undefined, 0]; return chromeVersion[1] >= 11 && ("onwebkitspeechchange" in input || "speech" in input); }, /** * IE9 crashes when setting a getter via Object.defineProperty on XMLHttpRequest or XDomainRequest * See https://connect.microsoft.com/ie/feedback/details/650112 * or try the POC http://tifftiff.de/ie9_crash/ */ crashesWhenDefineProperty: function(property) { return isIE(9) && (property === "XMLHttpRequest" || property === "XDomainRequest"); }, /** * IE is the only browser who fires the "focus" event not immediately when .focus() is called on an element */ doesAsyncFocus: function() { return isIE(); }, /** * In IE it's impssible for the user and for the selection library to set the caret after an <img> when it's the lastChild in the document */ hasProblemsSettingCaretAfterImg: function() { return isIE(); }, hasUndoInContextMenu: function() { return isGecko || isChrome || isOpera; }, /** * Opera sometimes doesn't insert the node at the right position when range.insertNode(someNode) * is used (regardless if rangy or native) * This especially happens when the caret is positioned right after a <br> because then * insertNode() will insert the node right before the <br> */ hasInsertNodeIssue: function() { return isOpera; }, /** * IE 8+9 don't fire the focus event of the <body> when the iframe gets focused (even though the caret gets set into the <body>) */ hasIframeFocusIssue: function() { return isIE(); }, /** * Chrome + Safari create invalid nested markup after paste * * <p> * foo * <p>bar</p> <!-- BOO! --> * </p> */ createsNestedInvalidMarkupAfterPaste: function() { return isWebKit; }, supportsMutationEvents: function() { return ("MutationEvent" in window); }, /** IE (at least up to 11) does not support clipboardData on event. It is on window but cannot return text/html Should actually check for clipboardData on paste event, but cannot in firefox */ supportsModenPaste: function () { return !("clipboardData" in window); } }; })(); ;wysihtml5.lang.array = function(arr) { return { /** * Check whether a given object exists in an array * * @example * wysihtml5.lang.array([1, 2]).contains(1); * // => true * * Can be used to match array with array. If intersection is found true is returned */ contains: function(needle) { if (Array.isArray(needle)) { for (var i = needle.length; i--;) { if (wysihtml5.lang.array(arr).indexOf(needle[i]) !== -1) { return true; } } return false; } else { return wysihtml5.lang.array(arr).indexOf(needle) !== -1; } }, /** * Check whether a given object exists in an array and return index * If no elelemt found returns -1 * * @example * wysihtml5.lang.array([1, 2]).indexOf(2); * // => 1 */ indexOf: function(needle) { if (arr.indexOf) { return arr.indexOf(needle); } else { for (var i=0, length=arr.length; i<length; i++) { if (arr[i] === needle) { return i; } } return -1; } }, /** * Substract one array from another * * @example * wysihtml5.lang.array([1, 2, 3, 4]).without([3, 4]); * // => [1, 2] */ without: function(arrayToSubstract) { arrayToSubstract = wysihtml5.lang.array(arrayToSubstract); var newArr = [], i = 0, length = arr.length; for (; i<length; i++) { if (!arrayToSubstract.contains(arr[i])) { newArr.push(arr[i]); } } return newArr; }, /** * Return a clean native array * * Following will convert a Live NodeList to a proper Array * @example * var childNodes = wysihtml5.lang.array(document.body.childNodes).get(); */ get: function() { var i = 0, length = arr.length, newArray = []; for (; i<length; i++) { newArray.push(arr[i]); } return newArray; }, /** * Creates a new array with the results of calling a provided function on every element in this array. * optionally this can be provided as second argument * * @example * var childNodes = wysihtml5.lang.array([1,2,3,4]).map(function (value, index, array) { return value * 2; * }); * // => [2,4,6,8] */ map: function(callback, thisArg) { if (Array.prototype.map) { return arr.map(callback, thisArg); } else { var len = arr.length >>> 0, A = new Array(len), i = 0; for (; i < len; i++) { A[i] = callback.call(thisArg, arr[i], i, arr); } return A; } }, /* ReturnS new array without duplicate entries * * @example * var uniq = wysihtml5.lang.array([1,2,3,2,1,4]).unique(); * // => [1,2,3,4] */ unique: function() { var vals = [], max = arr.length, idx = 0; while (idx < max) { if (!wysihtml5.lang.array(vals).contains(arr[idx])) { vals.push(arr[idx]); } idx++; } return vals; } }; }; ;wysihtml5.lang.Dispatcher = Base.extend( /** @scope wysihtml5.lang.Dialog.prototype */ { on: function(eventName, handler) { this.events = this.events || {}; this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(handler); return this; }, off: function(eventName, handler) { this.events = this.events || {}; var i = 0, handlers, newHandlers; if (eventName) { handlers = this.events[eventName] || [], newHandlers = []; for (; i<handlers.length; i++) { if (handlers[i] !== handler && handler) { newHandlers.push(handlers[i]); } } this.events[eventName] = newHandlers; } else { // Clean up all events this.events = {}; } return this; }, fire: function(eventName, payload) { this.events = this.events || {}; var handlers = this.events[eventName] || [], i = 0; for (; i<handlers.length; i++) { handlers[i].call(this, payload); } return this; }, // deprecated, use .on() observe: function() { return this.on.apply(this, arguments); }, // deprecated, use .off() stopObserving: function() { return this.off.apply(this, arguments); } }); ;wysihtml5.lang.object = function(obj) { return { /** * @example * wysihtml5.lang.object({ foo: 1, bar: 1 }).merge({ bar: 2, baz: 3 }).get(); * // => { foo: 1, bar: 2, baz: 3 } */ merge: function(otherObj) { for (var i in otherObj) { obj[i] = otherObj[i]; } return this; }, get: function() { return obj; }, /** * @example * wysihtml5.lang.object({ foo: 1 }).clone(); * // => { foo: 1 } * * v0.4.14 adds options for deep clone : wysihtml5.lang.object({ foo: 1 }).clone(true); */ clone: function(deep) { var newObj = {}, i; if (obj === null || !wysihtml5.lang.object(obj).isPlainObject()) { return obj; } for (i in obj) { if(obj.hasOwnProperty(i)) { if (deep) { newObj[i] = wysihtml5.lang.object(obj[i]).clone(deep); } else { newObj[i] = obj[i]; } } } return newObj; }, /** * @example * wysihtml5.lang.object([]).isArray(); * // => true */ isArray: function() { return Object.prototype.toString.call(obj) === "[object Array]"; }, /** * @example * wysihtml5.lang.object(function() {}).isFunction(); * // => true */ isFunction: function() { return Object.prototype.toString.call(obj) === '[object Function]'; }, isPlainObject: function () { return Object.prototype.toString.call(obj) === '[object Object]'; } }; }; ;(function() { var WHITE_SPACE_START = /^\s+/, WHITE_SPACE_END = /\s+$/, ENTITY_REG_EXP = /[&<>\t"]/g, ENTITY_MAP = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': "&quot;", '\t':"&nbsp; " }; wysihtml5.lang.string = function(str) { str = String(str); return { /** * @example * wysihtml5.lang.string(" foo ").trim(); * // => "foo" */ trim: function() { return str.replace(WHITE_SPACE_START, "").replace(WHITE_SPACE_END, ""); }, /** * @example * wysihtml5.lang.string("Hello #{name}").interpolate({ name: "Christopher" }); * // => "Hello Christopher" */ interpolate: function(vars) { for (var i in vars) { str = this.replace("#{" + i + "}").by(vars[i]); } return str; }, /** * @example * wysihtml5.lang.string("Hello Tom").replace("Tom").with("Hans"); * // => "Hello Hans" */ replace: function(search) { return { by: function(replace) { return str.split(search).join(replace); } }; }, /** * @example * wysihtml5.lang.string("hello<br>").escapeHTML(); * // => "hello&lt;br&gt;" */ escapeHTML: function(linebreaks, convertSpaces) { var html = str.replace(ENTITY_REG_EXP, function(c) { return ENTITY_MAP[c]; }); if (linebreaks) { html = html.replace(/(?:\r\n|\r|\n)/g, '<br />'); } if (convertSpaces) { html = html.replace(/ /gi, "&nbsp; "); } return html; } }; }; })(); ;/** * Find urls in descendant text nodes of an element and auto-links them * Inspired by http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ * * @param {Element} element Container element in which to search for urls * * @example * <div id="text-container">Please click here: www.google.com</div> * <script>wysihtml5.dom.autoLink(document.getElementById("text-container"));</script> */ (function(wysihtml5) { var /** * Don't auto-link urls that are contained in the following elements: */ IGNORE_URLS_IN = wysihtml5.lang.array(["CODE", "PRE", "A", "SCRIPT", "HEAD", "TITLE", "STYLE"]), /** * revision 1: * /(\S+\.{1}[^\s\,\.\!]+)/g * * revision 2: * /(\b(((https?|ftp):\/\/)|(www\.))[-A-Z0-9+&@#\/%?=~_|!:,.;\[\]]*[-A-Z0-9+&@#\/%=~_|])/gim * * put this in the beginning if you don't wan't to match within a word * (^|[\>\(\{\[\s\>]) */ URL_REG_EXP = /((https?:\/\/|www\.)[^\s<]{3,})/gi, TRAILING_CHAR_REG_EXP = /([^\w\/\-](,?))$/i, MAX_DISPLAY_LENGTH = 100, BRACKETS = { ")": "(", "]": "[", "}": "{" }; function autoLink(element, ignoreInClasses) { if (_hasParentThatShouldBeIgnored(element, ignoreInClasses)) { return element; } if (element === element.ownerDocument.documentElement) { element = element.ownerDocument.body; } return _parseNode(element, ignoreInClasses); } /** * This is basically a rebuild of * the rails auto_link_urls text helper */ function _convertUrlsToLinks(str) { return str.replace(URL_REG_EXP, function(match, url) { var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "", opening = BRACKETS[punctuation]; url = url.replace(TRAILING_CHAR_REG_EXP, ""); if (url.split(opening).length > url.split(punctuation).length) { url = url + punctuation; punctuation = ""; } var realUrl = url, displayUrl = url; if (url.length > MAX_DISPLAY_LENGTH) { displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "..."; } // Add http prefix if necessary if (realUrl.substr(0, 4) === "www.") { realUrl = "http://" + realUrl; } return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation; }); } /** * Creates or (if already cached) returns a temp element * for the given document object */ function _getTempElement(context) { var tempElement = context._wysihtml5_tempElement; if (!tempElement) { tempElement = context._wysihtml5_tempElement = context.createElement("div"); } return tempElement; } /** * Replaces the original text nodes with the newly auto-linked dom tree */ function _wrapMatchesInNode(textNode) { var parentNode = textNode.parentNode, nodeValue = wysihtml5.lang.string(textNode.data).escapeHTML(), tempElement = _getTempElement(parentNode.ownerDocument); // We need to insert an empty/temporary <span /> to fix IE quirks // Elsewise IE would strip white space in the beginning tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(nodeValue); tempElement.removeChild(tempElement.firstChild); while (tempElement.firstChild) { // inserts tempElement.firstChild before textNode parentNode.insertBefore(tempElement.firstChild, textNode); } parentNode.removeChild(textNode); } function _hasParentThatShouldBeIgnored(node, ignoreInClasses) { var nodeName; while (node.parentNode) { node = node.parentNode; nodeName = node.nodeName; if (node.className && wysihtml5.lang.array(node.className.split(' ')).contains(ignoreInClasses)) { return true; } if (IGNORE_URLS_IN.contains(nodeName)) { return true; } else if (nodeName === "body") { return false; } } return false; } function _parseNode(element, ignoreInClasses) { if (IGNORE_URLS_IN.contains(element.nodeName)) { return; } if (element.className && wysihtml5.lang.array(element.className.split(' ')).contains(ignoreInClasses)) { return; } if (element.nodeType === wysihtml5.TEXT_NODE && element.data.match(URL_REG_EXP)) { _wrapMatchesInNode(element); return; } var childNodes = wysihtml5.lang.array(element.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { _parseNode(childNodes[i], ignoreInClasses); } return element; } wysihtml5.dom.autoLink = autoLink; // Reveal url reg exp to the outside wysihtml5.dom.autoLink.URL_REG_EXP = URL_REG_EXP; })(wysihtml5); ;(function(wysihtml5) { var api = wysihtml5.dom; api.addClass = function(element, className) { var classList = element.classList; if (classList) { return classList.add(className); } if (api.hasClass(element, className)) { return; } element.className += " " + className; }; api.removeClass = function(element, className) { var classList = element.classList; if (classList) { return classList.remove(className); } element.className = element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " "); }; api.hasClass = function(element, className) { var classList = element.classList; if (classList) { return classList.contains(className); } var elementClassName = element.className; return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); }; })(wysihtml5); ;wysihtml5.dom.contains = (function() { var documentElement = document.documentElement; if (documentElement.contains) { return function(container, element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { element = element.parentNode; } return container !== element && container.contains(element); }; } else if (documentElement.compareDocumentPosition) { return function(container, element) { // https://developer.mozilla.org/en/DOM/Node.compareDocumentPosition return !!(container.compareDocumentPosition(element) & 16); }; } })(); ;/** * Converts an HTML fragment/element into a unordered/ordered list * * @param {Element} element The element which should be turned into a list * @param {String} listType The list type in which to convert the tree (either "ul" or "ol") * @return {Element} The created list * * @example * <!-- Assume the following dom: --> * <span id="pseudo-list"> * eminem<br> * dr. dre * <div>50 Cent</div> * </span> * * <script> * wysihtml5.dom.convertToList(document.getElementById("pseudo-list"), "ul"); * </script> * * <!-- Will result in: --> * <ul> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> */ wysihtml5.dom.convertToList = (function() { function _createListItem(doc, list) { var listItem = doc.createElement("li"); list.appendChild(listItem); return listItem; } function _createList(doc, type) { return doc.createElement(type); } function convertToList(element, listType, uneditableClass) { if (element.nodeName === "UL" || element.nodeName === "OL" || element.nodeName === "MENU") { // Already a list return element; } var doc = element.ownerDocument, list = _createList(doc, listType), lineBreaks = element.querySelectorAll("br"), lineBreaksLength = lineBreaks.length, childNodes, childNodesLength, childNode, lineBreak, parentNode, isBlockElement, isLineBreak, currentListItem, i; // First find <br> at the end of inline elements and move them behind them for (i=0; i<lineBreaksLength; i++) { lineBreak = lineBreaks[i]; while ((parentNode = lineBreak.parentNode) && parentNode !== element && parentNode.lastChild === lineBreak) { if (wysihtml5.dom.getStyle("display").from(parentNode) === "block") { parentNode.removeChild(lineBreak); break; } wysihtml5.dom.insert(lineBreak).after(lineBreak.parentNode); } } childNodes = wysihtml5.lang.array(element.childNodes).get(); childNodesLength = childNodes.length; for (i=0; i<childNodesLength; i++) { currentListItem = currentListItem || _createListItem(doc, list); childNode = childNodes[i]; isBlockElement = wysihtml5.dom.getStyle("display").from(childNode) === "block"; isLineBreak = childNode.nodeName === "BR"; // consider uneditable as an inline element if (isBlockElement && (!uneditableClass || !wysihtml5.dom.hasClass(childNode, uneditableClass))) { // Append blockElement to current <li> if empty, otherwise create a new one currentListItem = currentListItem.firstChild ? _createListItem(doc, list) : currentListItem; currentListItem.appendChild(childNode); currentListItem = null; continue; } if (isLineBreak) { // Only create a new list item in the next iteration when the current one has already content currentListItem = currentListItem.firstChild ? null : currentListItem; continue; } currentListItem.appendChild(childNode); } if (childNodes.length === 0) { _createListItem(doc, list); } element.parentNode.replaceChild(list, element); return list; } return convertToList; })(); ;/** * Copy a set of attributes from one element to another * * @param {Array} attributesToCopy List of attributes which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the attributes from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the attributes to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyAttributes(["spellcheck", "value", "placeholder"]).from(textarea).to(div).andTo(anotherDiv); * */ wysihtml5.dom.copyAttributes = function(attributesToCopy) { return { from: function(elementToCopyFrom) { return { to: function(elementToCopyTo) { var attribute, i = 0, length = attributesToCopy.length; for (; i<length; i++) { attribute = attributesToCopy[i]; if (typeof(elementToCopyFrom[attribute]) !== "undefined" && elementToCopyFrom[attribute] !== "") { elementToCopyTo[attribute] = elementToCopyFrom[attribute]; } } return { andTo: arguments.callee }; } }; } }; }; ;/** * Copy a set of styles from one element to another * Please note that this only works properly across browsers when the element from which to copy the styles * is in the dom * * Interesting article on how to copy styles * * @param {Array} stylesToCopy List of styles which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the styles from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the styles to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyStyles(["overflow-y", "width", "height"]).from(textarea).to(div).andTo(anotherDiv); * */ (function(dom) { /** * Mozilla, WebKit and Opera recalculate the computed width when box-sizing: boder-box; is set * So if an element has "width: 200px; -moz-box-sizing: border-box; border: 1px;" then * its computed css width will be 198px * * See https://bugzilla.mozilla.org/show_bug.cgi?id=520992 */ var BOX_SIZING_PROPERTIES = ["-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing"]; var shouldIgnoreBoxSizingBorderBox = function(element) { if (hasBoxSizingBorderBox(element)) { return parseInt(dom.getStyle("width").from(element), 10) < element.offsetWidth; } return false; }; var hasBoxSizingBorderBox = function(element) { var i = 0, length = BOX_SIZING_PROPERTIES.length; for (; i<length; i++) { if (dom.getStyle(BOX_SIZING_PROPERTIES[i]).from(element) === "border-box") { return BOX_SIZING_PROPERTIES[i]; } } }; dom.copyStyles = function(stylesToCopy) { return { from: function(element) { if (shouldIgnoreBoxSizingBorderBox(element)) { stylesToCopy = wysihtml5.lang.array(stylesToCopy).without(BOX_SIZING_PROPERTIES); } var cssText = "", length = stylesToCopy.length, i = 0, property; for (; i<length; i++) { property = stylesToCopy[i]; cssText += property + ":" + dom.getStyle(property).from(element) + ";"; } return { to: function(element) { dom.setStyles(cssText).on(element); return { andTo: arguments.callee }; } }; } }; }; })(wysihtml5.dom); ;/** * Event Delegation * * @example * wysihtml5.dom.delegate(document.body, "a", "click", function() { * // foo * }); */ (function(wysihtml5) { wysihtml5.dom.delegate = function(container, selector, eventName, handler) { return wysihtml5.dom.observe(container, eventName, function(event) { var target = event.target, match = wysihtml5.lang.array(container.querySelectorAll(selector)); while (target && target !== container) { if (match.contains(target)) { handler.call(target, event); break; } target = target.parentNode; } }); }; })(wysihtml5); ;// TODO: Refactor dom tree traversing here (function(wysihtml5) { wysihtml5.dom.domNode = function(node) { var defaultNodeTypes = [wysihtml5.ELEMENT_NODE, wysihtml5.TEXT_NODE]; var _isBlankText = function(node) { return node.nodeType === wysihtml5.TEXT_NODE && (/^\s*$/g).test(node.data); }; return { // var node = wysihtml5.dom.domNode(element).prev({nodeTypes: [1,3], ignoreBlankTexts: true}); prev: function(options) { var prevNode = node.previousSibling, types = (options && options.nodeTypes) ? options.nodeTypes : defaultNodeTypes; if (!prevNode) { return null; } if ( (!wysihtml5.lang.array(types).contains(prevNode.nodeType)) || // nodeTypes check. (options && options.ignoreBlankTexts && _isBlankText(prevNode)) // Blank text nodes bypassed if set ) { return wysihtml5.dom.domNode(prevNode).prev(options); } return prevNode; }, // var node = wysihtml5.dom.domNode(element).next({nodeTypes: [1,3], ignoreBlankTexts: true}); next: function(options) { var nextNode = node.nextSibling, types = (options && options.nodeTypes) ? options.nodeTypes : defaultNodeTypes; if (!nextNode) { return null; } if ( (!wysihtml5.lang.array(types).contains(nextNode.nodeType)) || // nodeTypes check. (options && options.ignoreBlankTexts && _isBlankText(nextNode)) // blank text nodes bypassed if set ) { return wysihtml5.dom.domNode(nextNode).next(options); } return nextNode; } }; }; })(wysihtml5);;/** * Returns the given html wrapped in a div element * * Fixing IE's inability to treat unknown elements (HTML5 section, article, ...) correctly * when inserted via innerHTML * * @param {String} html The html which should be wrapped in a dom element * @param {Obejct} [context] Document object of the context the html belongs to * * @example * wysihtml5.dom.getAsDom("<article>foo</article>"); */ wysihtml5.dom.getAsDom = (function() { var _innerHTMLShiv = function(html, context) { var tempElement = context.createElement("div"); tempElement.style.display = "none"; context.body.appendChild(tempElement); // IE throws an exception when trying to insert <frameset></frameset> via innerHTML try { tempElement.innerHTML = html; } catch(e) {} context.body.removeChild(tempElement); return tempElement; }; /** * Make sure IE supports HTML5 tags, which is accomplished by simply creating one instance of each element */ var _ensureHTML5Compatibility = function(context) { if (context._wysihtml5_supportsHTML5Tags) { return; } for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) { context.createElement(HTML5_ELEMENTS[i]); } context._wysihtml5_supportsHTML5Tags = true; }; /** * List of html5 tags * taken from http://simon.html5.org/html5-elements */ var HTML5_ELEMENTS = [ "abbr", "article", "aside", "audio", "bdi", "canvas", "command", "datalist", "details", "figcaption", "figure", "footer", "header", "hgroup", "keygen", "mark", "meter", "nav", "output", "progress", "rp", "rt", "ruby", "svg", "section", "source", "summary", "time", "track", "video", "wbr" ]; return function(html, context) { context = context || document; var tempElement; if (typeof(html) === "object" && html.nodeType) { tempElement = context.createElement("div"); tempElement.appendChild(html); } else if (wysihtml5.browser.supportsHTML5Tags(context)) { tempElement = context.createElement("div"); tempElement.innerHTML = html; } else { _ensureHTML5Compatibility(context); tempElement = _innerHTMLShiv(html, context); } return tempElement; }; })(); ;/** * Walks the dom tree from the given node up until it finds a match * Designed for optimal performance. * * @param {Element} node The from which to check the parent nodes * @param {Object} matchingSet Object to match against (possible properties: nodeName, className, classRegExp) * @param {Number} [levels] How many parents should the function check up from the current node (defaults to 50) * @return {null|Element} Returns the first element that matched the desiredNodeName(s) * @example * var listElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: ["MENU", "UL", "OL"] }); * // ... or ... * var unorderedListElement = wysihtml5.dom.getParentElement(document.querySelector("li"), { nodeName: "UL" }); * // ... or ... * var coloredElement = wysihtml5.dom.getParentElement(myTextNode, { nodeName: "SPAN", className: "wysiwyg-color-red", classRegExp: /wysiwyg-color-[a-z]/g }); */ wysihtml5.dom.getParentElement = (function() { function _isSameNodeName(nodeName, desiredNodeNames) { if (!desiredNodeNames || !desiredNodeNames.length) { return true; } if (typeof(desiredNodeNames) === "string") { return nodeName === desiredNodeNames; } else { return wysihtml5.lang.array(desiredNodeNames).contains(nodeName); } } function _isElement(node) { return node.nodeType === wysihtml5.ELEMENT_NODE; } function _hasClassName(element, className, classRegExp) { var classNames = (element.className || "").match(classRegExp) || []; if (!className) { return !!classNames.length; } return classNames[classNames.length - 1] === className; } function _hasStyle(element, cssStyle, styleRegExp) { var styles = (element.getAttribute('style') || "").match(styleRegExp) || []; if (!cssStyle) { return !!styles.length; } return styles[styles.length - 1] === cssStyle; } return function(node, matchingSet, levels, container) { var findByStyle = (matchingSet.cssStyle || matchingSet.styleRegExp), findByClass = (matchingSet.className || matchingSet.classRegExp); levels = levels || 50; // Go max 50 nodes upwards from current node while (levels-- && node && node.nodeName !== "BODY" && (!container || node !== container)) { if (_isElement(node) && _isSameNodeName(node.nodeName, matchingSet.nodeName) && (!findByStyle || _hasStyle(node, matchingSet.cssStyle, matchingSet.styleRegExp)) && (!findByClass || _hasClassName(node, matchingSet.className, matchingSet.classRegExp)) ) { return node; } node = node.parentNode; } return null; }; })(); ;/** * Get element's style for a specific css property * * @param {Element} element The element on which to retrieve the style * @param {String} property The CSS property to retrieve ("float", "display", "text-align", ...) * * @example * wysihtml5.dom.getStyle("display").from(document.body); * // => "block" */ wysihtml5.dom.getStyle = (function() { var stylePropertyMapping = { "float": ("styleFloat" in document.createElement("div").style) ? "styleFloat" : "cssFloat" }, REG_EXP_CAMELIZE = /\-[a-z]/g; function camelize(str) { return str.replace(REG_EXP_CAMELIZE, function(match) { return match.charAt(1).toUpperCase(); }); } return function(property) { return { from: function(element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { return; } var doc = element.ownerDocument, camelizedProperty = stylePropertyMapping[property] || camelize(property), style = element.style, currentStyle = element.currentStyle, styleValue = style[camelizedProperty]; if (styleValue) { return styleValue; } // currentStyle is no standard and only supported by Opera and IE but it has one important advantage over the standard-compliant // window.getComputedStyle, since it returns css property values in their original unit: // If you set an elements width to "50%", window.getComputedStyle will give you it's current width in px while currentStyle // gives you the original "50%". // Opera supports both, currentStyle and window.getComputedStyle, that's why checking for currentStyle should have higher prio if (currentStyle) { try { return currentStyle[camelizedProperty]; } catch(e) { //ie will occasionally fail for unknown reasons. swal.firelowing exception } } var win = doc.defaultView || doc.parentWindow, needsOverflowReset = (property === "height" || property === "width") && element.nodeName === "TEXTAREA", originalOverflow, returnValue; if (win.getComputedStyle) { // Chrome and Safari both calculate a wrong width and height for textareas when they have scroll bars // therfore we remove and restore the scrollbar and calculate the value in between if (needsOverflowReset) { originalOverflow = style.overflow; style.overflow = "hidden"; } returnValue = win.getComputedStyle(element, null).getPropertyValue(property); if (needsOverflowReset) { style.overflow = originalOverflow || ""; } return returnValue; } } }; }; })(); ;wysihtml5.dom.getTextNodes = function(node, ingoreEmpty){ var all = []; for (node=node.firstChild;node;node=node.nextSibling){ if (node.nodeType == 3) { if (!ingoreEmpty || !(/^\s*$/).test(node.innerText || node.textContent)) { all.push(node); } } else { all = all.concat(wysihtml5.dom.getTextNodes(node, ingoreEmpty)); } } return all; };;/** * High performant way to check whether an element with a specific tag name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithTagName(document, "IMG"); */ wysihtml5.dom.hasElementWithTagName = (function() { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } return function(doc, tagName) { var key = _getDocumentIdentifier(doc) + ":" + tagName, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByTagName(tagName); } return cacheEntry.length > 0; }; })(); ;/** * High performant way to check whether an element with a specific class name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithClassName(document, "foobar"); */ (function(wysihtml5) { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } wysihtml5.dom.hasElementWithClassName = function(doc, className) { // getElementsByClassName is not supported by IE<9 // but is sometimes mocked via library code (which then doesn't return live node lists) if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) { return !!doc.querySelector("." + className); } var key = _getDocumentIdentifier(doc) + ":" + className, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className); } return cacheEntry.length > 0; }; })(wysihtml5); ;wysihtml5.dom.insert = function(elementToInsert) { return { after: function(element) { element.parentNode.insertBefore(elementToInsert, element.nextSibling); }, before: function(element) { element.parentNode.insertBefore(elementToInsert, element); }, into: function(element) { element.appendChild(elementToInsert); } }; }; ;wysihtml5.dom.insertCSS = function(rules) { rules = rules.join("\n"); return { into: function(doc) { var styleElement = doc.createElement("style"); styleElement.type = "text/css"; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = rules; } else { styleElement.appendChild(doc.createTextNode(rules)); } var link = doc.querySelector("head link"); if (link) { link.parentNode.insertBefore(styleElement, link); return; } else { var head = doc.querySelector("head"); if (head) { head.appendChild(styleElement); } } } }; }; ;// TODO: Refactor dom tree traversing here (function(wysihtml5) { wysihtml5.dom.lineBreaks = function(node) { function _isLineBreak(n) { return n.nodeName === "BR"; } /** * Checks whether the elment causes a visual line break * (<br> or block elements) */ function _isLineBreakOrBlockElement(element) { if (_isLineBreak(element)) { return true; } if (wysihtml5.dom.getStyle("display").from(element) === "block") { return true; } return false; } return { /* wysihtml5.dom.lineBreaks(element).add(); * * Adds line breaks before and after the given node if the previous and next siblings * aren't already causing a visual line break (block element or <br>) */ add: function(options) { var doc = node.ownerDocument, nextSibling = wysihtml5.dom.domNode(node).next({ignoreBlankTexts: true}), previousSibling = wysihtml5.dom.domNode(node).prev({ignoreBlankTexts: true}); if (nextSibling && !_isLineBreakOrBlockElement(nextSibling)) { wysihtml5.dom.insert(doc.createElement("br")).after(node); } if (previousSibling && !_isLineBreakOrBlockElement(previousSibling)) { wysihtml5.dom.insert(doc.createElement("br")).before(node); } }, /* wysihtml5.dom.lineBreaks(element).remove(); * * Removes line breaks before and after the given node */ remove: function(options) { var nextSibling = wysihtml5.dom.domNode(node).next({ignoreBlankTexts: true}), previousSibling = wysihtml5.dom.domNode(node).prev({ignoreBlankTexts: true}); if (nextSibling && _isLineBreak(nextSibling)) { nextSibling.parentNode.removeChild(nextSibling); } if (previousSibling && _isLineBreak(previousSibling)) { previousSibling.parentNode.removeChild(previousSibling); } } }; }; })(wysihtml5);;/** * Method to set dom events * * @example * wysihtml5.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... }); */ wysihtml5.dom.observe = function(element, eventNames, handler) { eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames; var handlerWrapper, eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else { handlerWrapper = function(event) { if (!("target" in event)) { event.target = event.srcElement; } event.preventDefault = event.preventDefault || function() { this.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { this.cancelBubble = true; }; handler.call(element, event); }; element.attachEvent("on" + eventName, handlerWrapper); } } return { stop: function() { var eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.removeEventListener) { element.removeEventListener(eventName, handler, false); } else { element.detachEvent("on" + eventName, handlerWrapper); } } } }; }; ;/** * HTML Sanitizer * Rewrites the HTML based on given rules * * @param {Element|String} elementOrHtml HTML String to be sanitized OR element whose content should be sanitized * @param {Object} [rules] List of rules for rewriting the HTML, if there's no rule for an element it will * be converted to a "span". Each rule is a key/value pair where key is the tag to convert, and value the * desired substitution. * @param {Object} context Document object in which to parse the html, needed to sandbox the parsing * * @return {Element|String} Depends on the elementOrHtml parameter. When html then the sanitized html as string elsewise the element. * * @example * var userHTML = '<div id="foo" onclick="alert(1);"><p><font color="red">foo</font><script>alert(1);</script></p></div>'; * wysihtml5.dom.parse(userHTML, { * tags { * p: "div", // Rename p tags to div tags * font: "span" // Rename font tags to span tags * div: true, // Keep them, also possible (same result when passing: "div" or true) * script: undefined // Remove script elements * } * }); * // => <div><div><span>foo bar</span></div></div> * * var userHTML = '<table><tbody><tr><td>I'm a table!</td></tr></tbody></table>'; * wysihtml5.dom.parse(userHTML); * // => '<span><span><span><span>I'm a table!</span></span></span></span>' * * var userHTML = '<div>foobar<br>foobar</div>'; * wysihtml5.dom.parse(userHTML, { * tags: { * div: undefined, * br: true * } * }); * // => '' * * var userHTML = '<div class="red">foo</div><div class="pink">bar</div>'; * wysihtml5.dom.parse(userHTML, { * classes: { * red: 1, * green: 1 * }, * tags: { * div: { * rename_tag: "p" * } * } * }); * // => '<p class="red">foo</p><p>bar</p>' */ wysihtml5.dom.parse = function(elementOrHtml_current, config_current) { /* TODO: Currently escaped module pattern as otherwise folloowing default swill be shared among multiple editors. * Refactor whole code as this method while workind is kind of awkward too */ /** * It's not possible to use a XMLParser/DOMParser as HTML5 is not always well-formed XML * new DOMParser().parseFromString('<img src="foo.gif">') will cause a parseError since the * node isn't closed * * Therefore we've to use the browser's ordinary HTML parser invoked by setting innerHTML. */ var NODE_TYPE_MAPPING = { "1": _handleElement, "3": _handleText, "8": _handleComment }, // Rename unknown tags to this DEFAULT_NODE_NAME = "span", WHITE_SPACE_REG_EXP = /\s+/, defaultRules = { tags: {}, classes: {} }, currentRules = {}; /** * Iterates over all childs of the element, recreates them, appends them into a document fragment * which later replaces the entire body content */ function parse(elementOrHtml, config) { wysihtml5.lang.object(currentRules).merge(defaultRules).merge(config.rules).get(); var context = config.context || elementOrHtml.ownerDocument || document, fragment = context.createDocumentFragment(), isString = typeof(elementOrHtml) === "string", clearInternals = false, element, newNode, firstChild; if (config.clearInternals === true) { clearInternals = true; } if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } if (currentRules.selectors) { _applySelectorRules(element, currentRules.selectors); } while (element.firstChild) { firstChild = element.firstChild; newNode = _convert(firstChild, config.cleanUp, clearInternals, config.uneditableClass); if (newNode) { fragment.appendChild(newNode); } if (firstChild !== newNode) { element.removeChild(firstChild); } } if (config.unjoinNbsps) { // replace joined non-breakable spaces with unjoined var txtnodes = wysihtml5.dom.getTextNodes(fragment); for (var n = txtnodes.length; n--;) { txtnodes[n].nodeValue = txtnodes[n].nodeValue.replace(/([\S\u00A0])\u00A0/gi, "$1 "); } } // Clear element contents element.innerHTML = ""; // Insert new DOM tree element.appendChild(fragment); return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element; } function _convert(oldNode, cleanUp, clearInternals, uneditableClass) { var oldNodeType = oldNode.nodeType, oldChilds = oldNode.childNodes, oldChildsLength = oldChilds.length, method = NODE_TYPE_MAPPING[oldNodeType], i = 0, fragment, newNode, newChild; // Passes directly elemets with uneditable class if (uneditableClass && oldNodeType === 1 && wysihtml5.dom.hasClass(oldNode, uneditableClass)) { return oldNode; } newNode = method && method(oldNode, clearInternals); // Remove or unwrap node in case of return value null or false if (!newNode) { if (newNode === false) { // false defines that tag should be removed but contents should remain (unwrap) fragment = oldNode.ownerDocument.createDocumentFragment(); for (i = oldChildsLength; i--;) { if (oldChilds[i]) { newChild = _convert(oldChilds[i], cleanUp, clearInternals, uneditableClass); if (newChild) { if (oldChilds[i] === newChild) { i--; } fragment.insertBefore(newChild, fragment.firstChild); } } } if (wysihtml5.dom.getStyle("display").from(oldNode) === "block") { fragment.appendChild(oldNode.ownerDocument.createElement("br")); } // TODO: try to minimize surplus spaces if (wysihtml5.lang.array([ "div", "pre", "p", "table", "td", "th", "ul", "ol", "li", "dd", "dl", "footer", "header", "section", "h1", "h2", "h3", "h4", "h5", "h6" ]).contains(oldNode.nodeName.toLowerCase()) && oldNode.parentNode.lastChild !== oldNode) { // add space at first when unwraping non-textflow elements if (!oldNode.nextSibling || oldNode.nextSibling.nodeType !== 3 || !(/^\s/).test(oldNode.nextSibling.nodeValue)) { fragment.appendChild(oldNode.ownerDocument.createTextNode(" ")); } } if (fragment.normalize) { fragment.normalize(); } return fragment; } else { // Remove return null; } } // Converts all childnodes for (i=0; i<oldChildsLength; i++) { if (oldChilds[i]) { newChild = _convert(oldChilds[i], cleanUp, clearInternals, uneditableClass); if (newChild) { if (oldChilds[i] === newChild) { i--; } newNode.appendChild(newChild); } } } // Cleanup senseless <span> elements if (cleanUp && newNode.nodeName.toLowerCase() === DEFAULT_NODE_NAME && (!newNode.childNodes.length || ((/^\s*$/gi).test(newNode.innerHTML) && (clearInternals || (oldNode.className !== "_wysihtml5-temp-placeholder" && oldNode.className !== "rangySelectionBoundary"))) || !newNode.attributes.length) ) { fragment = newNode.ownerDocument.createDocumentFragment(); while (newNode.firstChild) { fragment.appendChild(newNode.firstChild); } if (fragment.normalize) { fragment.normalize(); } return fragment; } if (newNode.normalize) { newNode.normalize(); } return newNode; } function _applySelectorRules (element, selectorRules) { var sel, method, els; for (sel in selectorRules) { if (selectorRules.hasOwnProperty(sel)) { if (wysihtml5.lang.object(selectorRules[sel]).isFunction()) { method = selectorRules[sel]; } else if (typeof(selectorRules[sel]) === "string" && elementHandlingMethods[selectorRules[sel]]) { method = elementHandlingMethods[selectorRules[sel]]; } els = element.querySelectorAll(sel); for (var i = els.length; i--;) { method(els[i]); } } } } function _handleElement(oldNode, clearInternals) { var rule, newNode, tagRules = currentRules.tags, nodeName = oldNode.nodeName.toLowerCase(), scopeName = oldNode.scopeName, renameTag; /** * We already parsed that element * ignore it! (yes, this sometimes happens in IE8 when the html is invalid) */ if (oldNode._wysihtml5) { return null; } oldNode._wysihtml5 = 1; if (oldNode.className === "wysihtml5-temp") { return null; } /** * IE is the only browser who doesn't include the namespace in the * nodeName, that's why we have to prepend it by ourselves * scopeName is a proprietary IE feature * read more here http://msdn.microsoft.com/en-us/library/ms534388(v=vs.85).aspx */ if (scopeName && scopeName != "HTML") { nodeName = scopeName + ":" + nodeName; } /** * Repair node * IE is a bit bitchy when it comes to invalid nested markup which includes unclosed tags * A <p> doesn't need to be closed according HTML4-5 spec, we simply replace it with a <div> to preserve its content and layout */ if ("outerHTML" in oldNode) { if (!wysihtml5.browser.autoClosesUnclosedTags() && oldNode.nodeName === "P" && oldNode.outerHTML.slice(-4).toLowerCase() !== "</p>") { nodeName = "div"; } } if (nodeName in tagRules) { rule = tagRules[nodeName]; if (!rule || rule.remove) { return null; } else if (rule.unwrap) { return false; } rule = typeof(rule) === "string" ? { rename_tag: rule } : rule; } else if (oldNode.firstChild) { rule = { rename_tag: DEFAULT_NODE_NAME }; } else { // Remove empty unknown elements return null; } // tests if type condition is met or node should be removed/unwrapped/renamed if (rule.one_of_type && !_testTypes(oldNode, currentRules, rule.one_of_type, clearInternals)) { if (rule.remove_action) { if (rule.remove_action === "unwrap") { return false; } else if (rule.remove_action === "rename") { renameTag = rule.remove_action_rename_to || DEFAULT_NODE_NAME; } else { return null; } } else { return null; } } newNode = oldNode.ownerDocument.createElement(renameTag || rule.rename_tag || nodeName); _handleAttributes(oldNode, newNode, rule, clearInternals); _handleStyles(oldNode, newNode, rule); oldNode = null; if (newNode.normalize) { newNode.normalize(); } return newNode; } function _testTypes(oldNode, rules, types, clearInternals) { var definition, type; // do not interfere with placeholder span or pasting caret position is not maintained if (oldNode.nodeName === "SPAN" && !clearInternals && (oldNode.className === "_wysihtml5-temp-placeholder" || oldNode.className === "rangySelectionBoundary")) { return true; } for (type in types) { if (types.hasOwnProperty(type) && rules.type_definitions && rules.type_definitions[type]) { definition = rules.type_definitions[type]; if (_testType(oldNode, definition)) { return true; } } } return false; } function array_contains(a, obj) { var i = a.length; while (i--) { if (a[i] === obj) { return true; } } return false; } function _testType(oldNode, definition) { var nodeClasses = oldNode.getAttribute("class"), nodeStyles = oldNode.getAttribute("style"), classesLength, s, s_corrected, a, attr, currentClass, styleProp; // test for methods if (definition.methods) { for (var m in definition.methods) { if (definition.methods.hasOwnProperty(m) && typeCeckMethods[m]) { if (typeCeckMethods[m](oldNode)) { return true; } } } } // test for classes, if one found return true if (nodeClasses && definition.classes) { nodeClasses = nodeClasses.replace(/^\s+/g, '').replace(/\s+$/g, '').split(WHITE_SPACE_REG_EXP); classesLength = nodeClasses.length; for (var i = 0; i < classesLength; i++) { if (definition.classes[nodeClasses[i]]) { return true; } } } // test for styles, if one found return true if (nodeStyles && definition.styles) { nodeStyles = nodeStyles.split(';'); for (s in definition.styles) { if (definition.styles.hasOwnProperty(s)) { for (var sp = nodeStyles.length; sp--;) { styleProp = nodeStyles[sp].split(':'); if (styleProp[0].replace(/\s/g, '').toLowerCase() === s) { if (definition.styles[s] === true || definition.styles[s] === 1 || wysihtml5.lang.array(definition.styles[s]).contains(styleProp[1].replace(/\s/g, '').toLowerCase()) ) { return true; } } } } } } // test for attributes in general against regex match if (definition.attrs) { for (a in definition.attrs) { if (definition.attrs.hasOwnProperty(a)) { attr = wysihtml5.dom.getAttribute(oldNode, a); if (typeof(attr) === "string") { if (attr.search(definition.attrs[a]) > -1) { return true; } } } } } return false; } function _handleStyles(oldNode, newNode, rule) { var s, v; if(rule && rule.keep_styles) { for (s in rule.keep_styles) { if (rule.keep_styles.hasOwnProperty(s)) { v = (s === "float") ? oldNode.style.styleFloat || oldNode.style.cssFloat : oldNode.style[s]; // value can be regex and if so should match or style skipped if (rule.keep_styles[s] instanceof RegExp && !(rule.keep_styles[s].test(v))) { continue; } if (s === "float") { // IE compability newNode.style[(oldNode.style.styleFloat) ? 'styleFloat': 'cssFloat'] = v; } else if (oldNode.style[s]) { newNode.style[s] = v; } } } } }; function _getAttributesBeginningWith(beginning, attributes) { var returnAttributes = []; for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr.indexOf(beginning) === 0) { returnAttributes.push(attr); } } return returnAttributes; } function _checkAttribute(attributeName, attributeValue, methodName, nodeName) { var method = attributeCheckMethods[methodName], newAttributeValue; if (method) { if (attributeValue || (attributeName === "alt" && nodeName == "IMG")) { newAttributeValue = method(attributeValue); if (typeof(newAttributeValue) === "string") { return newAttributeValue; } } } return false; } function _checkAttributes(oldNode, local_attributes) { var globalAttributes = wysihtml5.lang.object(currentRules.attributes || {}).clone(), // global values for check/convert values of attributes checkAttributes = wysihtml5.lang.object(globalAttributes).merge( wysihtml5.lang.object(local_attributes || {}).clone()).get(), attributes = {}, oldAttributes = wysihtml5.dom.getAttributes(oldNode), attributeName, newValue, matchingAttributes; for (attributeName in checkAttributes) { if ((/\*$/).test(attributeName)) { matchingAttributes = _getAttributesBeginningWith(attributeName.slice(0,-1), oldAttributes); for (var i = 0, imax = matchingAttributes.length; i < imax; i++) { newValue = _checkAttribute(matchingAttributes[i], oldAttributes[matchingAttributes[i]], checkAttributes[attributeName], oldNode.nodeName); if (newValue !== false) { attributes[matchingAttributes[i]] = newValue; } } } else { newValue = _checkAttribute(attributeName, oldAttributes[attributeName], checkAttributes[attributeName], oldNode.nodeName); if (newValue !== false) { attributes[attributeName] = newValue; } } } return attributes; } // TODO: refactor. Too long to read function _handleAttributes(oldNode, newNode, rule, clearInternals) { var attributes = {}, // fresh new set of attributes to set on newNode setClass = rule.set_class, // classes to set addClass = rule.add_class, // add classes based on existing attributes addStyle = rule.add_style, // add styles based on existing attributes setAttributes = rule.set_attributes, // attributes to set on the current node allowedClasses = currentRules.classes, i = 0, classes = [], styles = [], newClasses = [], oldClasses = [], classesLength, newClassesLength, currentClass, newClass, attributeName, method; if (setAttributes) { attributes = wysihtml5.lang.object(setAttributes).clone(); } // check/convert values of attributes attributes = wysihtml5.lang.object(attributes).merge(_checkAttributes(oldNode, rule.check_attributes)).get(); if (setClass) { classes.push(setClass); } if (addClass) { for (attributeName in addClass) { method = addClassMethods[addClass[attributeName]]; if (!method) { continue; } newClass = method(wysihtml5.dom.getAttribute(oldNode, attributeName)); if (typeof(newClass) === "string") { classes.push(newClass); } } } if (addStyle) { for (attributeName in addStyle) { method = addStyleMethods[addStyle[attributeName]]; if (!method) { continue; } newStyle = method(wysihtml5.dom.getAttribute(oldNode, attributeName)); if (typeof(newStyle) === "string") { styles.push(newStyle); } } } if (typeof(allowedClasses) === "string" && allowedClasses === "any" && oldNode.getAttribute("class")) { if (currentRules.classes_blacklist) { oldClasses = oldNode.getAttribute("class"); if (oldClasses) { classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP)); } classesLength = classes.length; for (; i<classesLength; i++) { currentClass = classes[i]; if (!currentRules.classes_blacklist[currentClass]) { newClasses.push(currentClass); } } if (newClasses.length) { attributes["class"] = wysihtml5.lang.array(newClasses).unique().join(" "); } } else { attributes["class"] = oldNode.getAttribute("class"); } } else { // make sure that wysihtml5 temp class doesn't get stripped out if (!clearInternals) { allowedClasses["_wysihtml5-temp-placeholder"] = 1; allowedClasses["_rangySelectionBoundary"] = 1; allowedClasses["wysiwyg-tmp-selected-cell"] = 1; } // add old classes last oldClasses = oldNode.getAttribute("class"); if (oldClasses) { classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP)); } classesLength = classes.length; for (; i<classesLength; i++) { currentClass = classes[i]; if (allowedClasses[currentClass]) { newClasses.push(currentClass); } } if (newClasses.length) { attributes["class"] = wysihtml5.lang.array(newClasses).unique().join(" "); } } // remove table selection class if present if (attributes["class"] && clearInternals) { attributes["class"] = attributes["class"].replace("wysiwyg-tmp-selected-cell", ""); if ((/^\s*$/g).test(attributes["class"])) { delete attributes["class"]; } } if (styles.length) { attributes["style"] = wysihtml5.lang.array(styles).unique().join(" "); } // set attributes on newNode for (attributeName in attributes) { // Setting attributes can cause a js error in IE under certain circumstances // eg. on a <img> under https when it's new attribute value is non-https // TODO: Investigate this further and check for smarter handling try { newNode.setAttribute(attributeName, attributes[attributeName]); } catch(e) {} } // IE8 sometimes loses the width/height attributes when those are set before the "src" // so we make sure to set them again if (attributes.src) { if (typeof(attributes.width) !== "undefined") { newNode.setAttribute("width", attributes.width); } if (typeof(attributes.height) !== "undefined") { newNode.setAttribute("height", attributes.height); } } } var INVISIBLE_SPACE_REG_EXP = /\uFEFF/g; function _handleText(oldNode) { var nextSibling = oldNode.nextSibling; if (nextSibling && nextSibling.nodeType === wysihtml5.TEXT_NODE) { // Concatenate text nodes nextSibling.data = oldNode.data.replace(INVISIBLE_SPACE_REG_EXP, "") + nextSibling.data.replace(INVISIBLE_SPACE_REG_EXP, ""); } else { // \uFEFF = wysihtml5.INVISIBLE_SPACE (used as a hack in certain rich text editing situations) var data = oldNode.data.replace(INVISIBLE_SPACE_REG_EXP, ""); return oldNode.ownerDocument.createTextNode(data); } } function _handleComment(oldNode) { if (currentRules.comments) { return oldNode.ownerDocument.createComment(oldNode.nodeValue); } } // ------------ attribute checks ------------ \\ var attributeCheckMethods = { url: (function() { var REG_EXP = /^https?:\/\//i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), src: (function() { var REG_EXP = /^(\/|https?:\/\/)/i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), href: (function() { var REG_EXP = /^(#|\/|https?:\/\/|mailto:)/i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), alt: (function() { var REG_EXP = /[^ a-z0-9_\-]/gi; return function(attributeValue) { if (!attributeValue) { return ""; } return attributeValue.replace(REG_EXP, ""); }; })(), numbers: (function() { var REG_EXP = /\D/g; return function(attributeValue) { attributeValue = (attributeValue || "").replace(REG_EXP, ""); return attributeValue || null; }; })(), any: (function() { return function(attributeValue) { return attributeValue; }; })() }; // ------------ style converter (converts an html attribute to a style) ------------ \\ var addStyleMethods = { align_text: (function() { var mapping = { left: "text-align: left;", right: "text-align: right;", center: "text-align: center;" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), }; // ------------ class converter (converts an html attribute to a class name) ------------ \\ var addClassMethods = { align_img: (function() { var mapping = { left: "wysiwyg-float-left", right: "wysiwyg-float-right" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), align_text: (function() { var mapping = { left: "wysiwyg-text-align-left", right: "wysiwyg-text-align-right", center: "wysiwyg-text-align-center", justify: "wysiwyg-text-align-justify" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), clear_br: (function() { var mapping = { left: "wysiwyg-clear-left", right: "wysiwyg-clear-right", both: "wysiwyg-clear-both", all: "wysiwyg-clear-both" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), size_font: (function() { var mapping = { "1": "wysiwyg-font-size-xx-small", "2": "wysiwyg-font-size-small", "3": "wysiwyg-font-size-medium", "4": "wysiwyg-font-size-large", "5": "wysiwyg-font-size-x-large", "6": "wysiwyg-font-size-xx-large", "7": "wysiwyg-font-size-xx-large", "-": "wysiwyg-font-size-smaller", "+": "wysiwyg-font-size-larger" }; return function(attributeValue) { return mapping[String(attributeValue).charAt(0)]; }; })() }; // checks if element is possibly visible var typeCeckMethods = { has_visible_contet: (function() { var txt, isVisible = false, visibleElements = ['img', 'video', 'picture', 'br', 'script', 'noscript', 'style', 'table', 'iframe', 'object', 'embed', 'audio', 'svg', 'input', 'button', 'select','textarea', 'canvas']; return function(el) { // has visible innertext. so is visible txt = (el.innerText || el.textContent).replace(/\s/g, ''); if (txt && txt.length > 0) { return true; } // matches list of visible dimensioned elements for (var i = visibleElements.length; i--;) { if (el.querySelector(visibleElements[i])) { return true; } } // try to measure dimesions in last resort. (can find only of elements in dom) if (el.offsetWidth && el.offsetWidth > 0 && el.offsetHeight && el.offsetHeight > 0) { return true; } return false; }; })() }; var elementHandlingMethods = { unwrap: function (element) { wysihtml5.dom.unwrap(element); }, remove: function (element) { element.parentNode.removeChild(element); } }; return parse(elementOrHtml_current, config_current); }; ;/** * Checks for empty text node childs and removes them * * @param {Element} node The element in which to cleanup * @example * wysihtml5.dom.removeEmptyTextNodes(element); */ wysihtml5.dom.removeEmptyTextNodes = function(node) { var childNode, childNodes = wysihtml5.lang.array(node.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { childNode = childNodes[i]; if (childNode.nodeType === wysihtml5.TEXT_NODE && childNode.data === "") { childNode.parentNode.removeChild(childNode); } } }; ;/** * Renames an element (eg. a <div> to a <p>) and keeps its childs * * @param {Element} element The list element which should be renamed * @param {Element} newNodeName The desired tag name * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.renameElement(document.getElementById("list"), "ol"); * </script> * * <!-- Will result in: --> * <ol> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ol> */ wysihtml5.dom.renameElement = function(element, newNodeName) { var newElement = element.ownerDocument.createElement(newNodeName), firstChild; while (firstChild = element.firstChild) { newElement.appendChild(firstChild); } wysihtml5.dom.copyAttributes(["align", "className"]).from(element).to(newElement); element.parentNode.replaceChild(newElement, element); return newElement; }; ;/** * Takes an element, removes it and replaces it with it's childs * * @param {Object} node The node which to replace with it's child nodes * @example * <div id="foo"> * <span>hello</span> * </div> * <script> * // Remove #foo and replace with it's children * wysihtml5.dom.replaceWithChildNodes(document.getElementById("foo")); * </script> */ wysihtml5.dom.replaceWithChildNodes = function(node) { if (!node.parentNode) { return; } if (!node.firstChild) { node.parentNode.removeChild(node); return; } var fragment = node.ownerDocument.createDocumentFragment(); while (node.firstChild) { fragment.appendChild(node.firstChild); } node.parentNode.replaceChild(fragment, node); node = fragment = null; }; ;/** * Unwraps an unordered/ordered list * * @param {Element} element The list element which should be unwrapped * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.resolveList(document.getElementById("list")); * </script> * * <!-- Will result in: --> * eminem<br> * dr. dre<br> * 50 Cent<br> */ (function(dom) { function _isBlockElement(node) { return dom.getStyle("display").from(node) === "block"; } function _isLineBreak(node) { return node.nodeName === "BR"; } function _appendLineBreak(element) { var lineBreak = element.ownerDocument.createElement("br"); element.appendChild(lineBreak); } function resolveList(list, useLineBreaks) { if (!list.nodeName.match(/^(MENU|UL|OL)$/)) { return; } var doc = list.ownerDocument, fragment = doc.createDocumentFragment(), previousSibling = wysihtml5.dom.domNode(list).prev({ignoreBlankTexts: true}), firstChild, lastChild, isLastChild, shouldAppendLineBreak, paragraph, listItem; if (useLineBreaks) { // Insert line break if list is after a non-block element if (previousSibling && !_isBlockElement(previousSibling) && !_isLineBreak(previousSibling)) { _appendLineBreak(fragment); } while (listItem = (list.firstElementChild || list.firstChild)) { lastChild = listItem.lastChild; while (firstChild = listItem.firstChild) { isLastChild = firstChild === lastChild; // This needs to be done before appending it to the fragment, as it otherwise will lose style information shouldAppendLineBreak = isLastChild && !_isBlockElement(firstChild) && !_isLineBreak(firstChild); fragment.appendChild(firstChild); if (shouldAppendLineBreak) { _appendLineBreak(fragment); } } listItem.parentNode.removeChild(listItem); } } else { while (listItem = (list.firstElementChild || list.firstChild)) { if (listItem.querySelector && listItem.querySelector("div, p, ul, ol, menu, blockquote, h1, h2, h3, h4, h5, h6")) { while (firstChild = listItem.firstChild) { fragment.appendChild(firstChild); } } else { paragraph = doc.createElement("p"); while (firstChild = listItem.firstChild) { paragraph.appendChild(firstChild); } fragment.appendChild(paragraph); } listItem.parentNode.removeChild(listItem); } } list.parentNode.replaceChild(fragment, list); } dom.resolveList = resolveList; })(wysihtml5.dom); ;/** * Sandbox for executing javascript, parsing css styles and doing dom operations in a secure way * * Browser Compatibility: * - Secure in MSIE 6+, but only when the user hasn't made changes to his security level "restricted" * - Partially secure in other browsers (Firefox, Opera, Safari, Chrome, ...) * * Please note that this class can't benefit from the HTML5 sandbox attribute for the following reasons: * - sandboxing doesn't work correctly with inlined content (src="javascript:'<html>...</html>'") * - sandboxing of physical documents causes that the dom isn't accessible anymore from the outside (iframe.contentWindow, ...) * - setting the "allow-same-origin" flag would fix that, but then still javascript and dom events refuse to fire * - therefore the "allow-scripts" flag is needed, which then would deactivate any security, as the js executed inside the iframe * can do anything as if the sandbox attribute wasn't set * * @param {Function} [readyCallback] Method that gets invoked when the sandbox is ready * @param {Object} [config] Optional parameters * * @example * new wysihtml5.dom.Sandbox(function(sandbox) { * sandbox.getWindow().document.body.innerHTML = '<img src=foo.gif onerror="alert(document.cookie)">'; * }); */ (function(wysihtml5) { var /** * Default configuration */ doc = document, /** * Properties to unset/protect on the window object */ windowProperties = [ "parent", "top", "opener", "frameElement", "frames", "localStorage", "globalStorage", "sessionStorage", "indexedDB" ], /** * Properties on the window object which are set to an empty function */ windowProperties2 = [ "open", "close", "openDialog", "showModalDialog", "alert", "confirm", "prompt", "openDatabase", "postMessage", "XMLHttpRequest", "XDomainRequest" ], /** * Properties to unset/protect on the document object */ documentProperties = [ "referrer", "write", "open", "close" ]; wysihtml5.dom.Sandbox = Base.extend( /** @scope wysihtml5.dom.Sandbox.prototype */ { constructor: function(readyCallback, config) { this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION; this.config = wysihtml5.lang.object({}).merge(config).get(); this.editableArea = this._createIframe(); }, insertInto: function(element) { if (typeof(element) === "string") { element = doc.getElementById(element); } element.appendChild(this.editableArea); }, getIframe: function() { return this.editableArea; }, getWindow: function() { this._readyError(); }, getDocument: function() { this._readyError(); }, destroy: function() { var iframe = this.getIframe(); iframe.parentNode.removeChild(iframe); }, _readyError: function() { throw new Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet"); }, /** * Creates the sandbox iframe * * Some important notes: * - We can't use HTML5 sandbox for now: * setting it causes that the iframe's dom can't be accessed from the outside * Therefore we need to set the "allow-same-origin" flag which enables accessing the iframe's dom * But then there's another problem, DOM events (focus, blur, change, keypress, ...) aren't fired. * In order to make this happen we need to set the "allow-scripts" flag. * A combination of allow-scripts and allow-same-origin is almost the same as setting no sandbox attribute at all. * - Chrome & Safari, doesn't seem to support sandboxing correctly when the iframe's html is inlined (no physical document) * - IE needs to have the security="restricted" attribute set before the iframe is * inserted into the dom tree * - Believe it or not but in IE "security" in document.createElement("iframe") is false, even * though it supports it * - When an iframe has security="restricted", in IE eval() & execScript() don't work anymore * - IE doesn't fire the onload event when the content is inlined in the src attribute, therefore we rely * on the onreadystatechange event */ _createIframe: function() { var that = this, iframe = doc.createElement("iframe"); iframe.className = "wysihtml5-sandbox"; wysihtml5.dom.setAttributes({ "security": "restricted", "allowtransparency": "true", "frameborder": 0, "width": 0, "height": 0, "marginwidth": 0, "marginheight": 0 }).on(iframe); // Setting the src like this prevents ssl warnings in IE6 if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) { iframe.src = "javascript:'<html></html>'"; } iframe.onload = function() { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); }; iframe.onreadystatechange = function() { if (/loaded|complete/.test(iframe.readyState)) { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); } }; return iframe; }, /** * Callback for when the iframe has finished loading */ _onLoadIframe: function(iframe) { // don't resume when the iframe got unloaded (eg. by removing it from the dom) if (!wysihtml5.dom.contains(doc.documentElement, iframe)) { return; } var that = this, iframeWindow = iframe.contentWindow, iframeDocument = iframe.contentWindow.document, charset = doc.characterSet || doc.charset || "utf-8", sandboxHtml = this._getHtml({ charset: charset, stylesheets: this.config.stylesheets }); // Create the basic dom tree including proper DOCTYPE and charset iframeDocument.open("text/html", "replace"); iframeDocument.write(sandboxHtml); iframeDocument.close(); this.getWindow = function() { return iframe.contentWindow; }; this.getDocument = function() { return iframe.contentWindow.document; }; // Catch js errors and pass them to the parent's onerror event // addEventListener("error") doesn't work properly in some browsers // TODO: apparently this doesn't work in IE9! iframeWindow.onerror = function(errorMessage, fileName, lineNumber) { throw new Error("wysihtml5.Sandbox: " + errorMessage, fileName, lineNumber); }; if (!wysihtml5.browser.supportsSandboxedIframes()) { // Unset a bunch of sensitive variables // Please note: This isn't hack safe! // It more or less just takes care of basic attacks and prevents accidental theft of sensitive information // IE is secure though, which is the most important thing, since IE is the only browser, who // takes over scripts & styles into contentEditable elements when copied from external websites // or applications (Microsoft Word, ...) var i, length; for (i=0, length=windowProperties.length; i<length; i++) { this._unset(iframeWindow, windowProperties[i]); } for (i=0, length=windowProperties2.length; i<length; i++) { this._unset(iframeWindow, windowProperties2[i], wysihtml5.EMPTY_FUNCTION); } for (i=0, length=documentProperties.length; i<length; i++) { this._unset(iframeDocument, documentProperties[i]); } // This doesn't work in Safari 5 // See http://stackoverflow.com/questions/992461/is-it-possible-to-override-document-cookie-in-webkit this._unset(iframeDocument, "cookie", "", true); } this.loaded = true; // Trigger the callback setTimeout(function() { that.callback(that); }, 0); }, _getHtml: function(templateVars) { var stylesheets = templateVars.stylesheets, html = "", i = 0, length; stylesheets = typeof(stylesheets) === "string" ? [stylesheets] : stylesheets; if (stylesheets) { length = stylesheets.length; for (; i<length; i++) { html += '<link rel="stylesheet" href="' + stylesheets[i] + '">'; } } templateVars.stylesheets = html; return wysihtml5.lang.string( '<!DOCTYPE html><html><head>' + '<meta charset="#{charset}">#{stylesheets}</head>' + '<body></body></html>' ).interpolate(templateVars); }, /** * Method to unset/override existing variables * @example * // Make cookie unreadable and unwritable * this._unset(document, "cookie", "", true); */ _unset: function(object, property, value, setter) { try { object[property] = value; } catch(e) {} try { object.__defineGetter__(property, function() { return value; }); } catch(e) {} if (setter) { try { object.__defineSetter__(property, function() {}); } catch(e) {} } if (!wysihtml5.browser.crashesWhenDefineProperty(property)) { try { var config = { get: function() { return value; } }; if (setter) { config.set = function() {}; } Object.defineProperty(object, property, config); } catch(e) {} } } }); })(wysihtml5); ;(function(wysihtml5) { var doc = document; wysihtml5.dom.ContentEditableArea = Base.extend({ getContentEditable: function() { return this.element; }, getWindow: function() { return this.element.ownerDocument.defaultView; }, getDocument: function() { return this.element.ownerDocument; }, constructor: function(readyCallback, config, contentEditable) { this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION; this.config = wysihtml5.lang.object({}).merge(config).get(); if (contentEditable) { this.element = this._bindElement(contentEditable); } else { this.element = this._createElement(); } }, // creates a new contenteditable and initiates it _createElement: function() { var element = doc.createElement("div"); element.className = "wysihtml5-sandbox"; this._loadElement(element); return element; }, // initiates an allready existent contenteditable _bindElement: function(contentEditable) { contentEditable.className = (contentEditable.className && contentEditable.className != '') ? contentEditable.className + " wysihtml5-sandbox" : "wysihtml5-sandbox"; this._loadElement(contentEditable, true); return contentEditable; }, _loadElement: function(element, contentExists) { var that = this; if (!contentExists) { var sandboxHtml = this._getHtml(); element.innerHTML = sandboxHtml; } this.getWindow = function() { return element.ownerDocument.defaultView; }; this.getDocument = function() { return element.ownerDocument; }; // Catch js errors and pass them to the parent's onerror event // addEventListener("error") doesn't work properly in some browsers // TODO: apparently this doesn't work in IE9! // TODO: figure out and bind the errors logic for contenteditble mode /*iframeWindow.onerror = function(errorMessage, fileName, lineNumber) { throw new Error("wysihtml5.Sandbox: " + errorMessage, fileName, lineNumber); } */ this.loaded = true; // Trigger the callback setTimeout(function() { that.callback(that); }, 0); }, _getHtml: function(templateVars) { return ''; } }); })(wysihtml5); ;(function() { var mapping = { "className": "class" }; wysihtml5.dom.setAttributes = function(attributes) { return { on: function(element) { for (var i in attributes) { element.setAttribute(mapping[i] || i, attributes[i]); } } }; }; })(); ;wysihtml5.dom.setStyles = function(styles) { return { on: function(element) { var style = element.style; if (typeof(styles) === "string") { style.cssText += ";" + styles; return; } for (var i in styles) { if (i === "float") { style.cssFloat = styles[i]; style.styleFloat = styles[i]; } else { style[i] = styles[i]; } } } }; }; ;/** * Simulate HTML5 placeholder attribute * * Needed since * - div[contentEditable] elements don't support it * - older browsers (such as IE8 and Firefox 3.6) don't support it at all * * @param {Object} parent Instance of main wysihtml5.Editor class * @param {Element} view Instance of wysihtml5.views.* class * @param {String} placeholderText * * @example * wysihtml.dom.simulatePlaceholder(this, composer, "Foobar"); */ (function(dom) { dom.simulatePlaceholder = function(editor, view, placeholderText) { var CLASS_NAME = "placeholder", unset = function() { var composerIsVisible = view.element.offsetWidth > 0 && view.element.offsetHeight > 0; if (view.hasPlaceholderSet()) { view.clear(); view.element.focus(); if (composerIsVisible ) { setTimeout(function() { var sel = view.selection.getSelection(); if (!sel.focusNode || !sel.anchorNode) { view.selection.selectNode(view.element.firstChild || view.element); } }, 0); } } view.placeholderSet = false; dom.removeClass(view.element, CLASS_NAME); }, set = function() { if (view.isEmpty()) { view.placeholderSet = true; view.setValue(placeholderText); dom.addClass(view.element, CLASS_NAME); } }; editor .on("set_placeholder", set) .on("unset_placeholder", unset) .on("focus:composer", unset) .on("paste:composer", unset) .on("blur:composer", set); set(); }; })(wysihtml5.dom); ;(function(dom) { var documentElement = document.documentElement; if ("textContent" in documentElement) { dom.setTextContent = function(element, text) { element.textContent = text; }; dom.getTextContent = function(element) { return element.textContent; }; } else if ("innerText" in documentElement) { dom.setTextContent = function(element, text) { element.innerText = text; }; dom.getTextContent = function(element) { return element.innerText; }; } else { dom.setTextContent = function(element, text) { element.nodeValue = text; }; dom.getTextContent = function(element) { return element.nodeValue; }; } })(wysihtml5.dom); ;/** * Get a set of attribute from one element * * IE gives wrong results for hasAttribute/getAttribute, for example: * var td = document.createElement("td"); * td.getAttribute("rowspan"); // => "1" in IE * * Therefore we have to check the element's outerHTML for the attribute */ wysihtml5.dom.getAttribute = function(node, attributeName) { var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly(); attributeName = attributeName.toLowerCase(); var nodeName = node.nodeName; if (nodeName == "IMG" && attributeName == "src" && wysihtml5.dom.isLoadedImage(node) === true) { // Get 'src' attribute value via object property since this will always contain the // full absolute url (http://...) // this fixes a very annoying bug in firefox (ver 3.6 & 4) and IE 8 where images copied from the same host // will have relative paths, which the sanitizer strips out (see attributeCheckMethods.url) return node.src; } else if (HAS_GET_ATTRIBUTE_BUG && "outerHTML" in node) { // Don't trust getAttribute/hasAttribute in IE 6-8, instead check the element's outerHTML var outerHTML = node.outerHTML.toLowerCase(), // TODO: This might not work for attributes without value: <input disabled> hasAttribute = outerHTML.indexOf(" " + attributeName + "=") != -1; return hasAttribute ? node.getAttribute(attributeName) : null; } else{ return node.getAttribute(attributeName); } }; ;/** * Get all attributes of an element * * IE gives wrong results for hasAttribute/getAttribute, for example: * var td = document.createElement("td"); * td.getAttribute("rowspan"); // => "1" in IE * * Therefore we have to check the element's outerHTML for the attribute */ wysihtml5.dom.getAttributes = function(node) { var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly(), nodeName = node.nodeName, attributes = [], attr; for (attr in node.attributes) { if ((node.attributes.hasOwnProperty && node.attributes.hasOwnProperty(attr)) || (!node.attributes.hasOwnProperty && Object.prototype.hasOwnProperty.call(node.attributes, attr))) { if (node.attributes[attr].specified) { if (nodeName == "IMG" && node.attributes[attr].name.toLowerCase() == "src" && wysihtml5.dom.isLoadedImage(node) === true) { attributes['src'] = node.src; } else if (wysihtml5.lang.array(['rowspan', 'colspan']).contains(node.attributes[attr].name.toLowerCase()) && HAS_GET_ATTRIBUTE_BUG) { if (node.attributes[attr].value !== 1) { attributes[node.attributes[attr].name] = node.attributes[attr].value; } } else { attributes[node.attributes[attr].name] = node.attributes[attr].value; } } } } return attributes; };;/** * Check whether the given node is a proper loaded image * FIXME: Returns undefined when unknown (Chrome, Safari) */ wysihtml5.dom.isLoadedImage = function (node) { try { return node.complete && !node.mozMatchesSelector(":-moz-broken"); } catch(e) { if (node.complete && node.readyState === "complete") { return true; } } }; ;(function(wysihtml5) { var api = wysihtml5.dom; var MapCell = function(cell) { this.el = cell; this.isColspan= false; this.isRowspan= false; this.firstCol= true; this.lastCol= true; this.firstRow= true; this.lastRow= true; this.isReal= true; this.spanCollection= []; this.modified = false; }; var TableModifyerByCell = function (cell, table) { if (cell) { this.cell = cell; this.table = api.getParentElement(cell, { nodeName: ["TABLE"] }); } else if (table) { this.table = table; this.cell = this.table.querySelectorAll('th, td')[0]; } }; function queryInList(list, query) { var ret = [], q; for (var e = 0, len = list.length; e < len; e++) { q = list[e].querySelectorAll(query); if (q) { for(var i = q.length; i--; ret.unshift(q[i])); } } return ret; } function removeElement(el) { el.parentNode.removeChild(el); } function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } function nextNode(node, tag) { var element = node.nextSibling; while (element.nodeType !=1) { element = element.nextSibling; if (!tag || tag == element.tagName.toLowerCase()) { return element; } } return null; } TableModifyerByCell.prototype = { addSpannedCellToMap: function(cell, map, r, c, cspan, rspan) { var spanCollect = [], rmax = r + ((rspan) ? parseInt(rspan, 10) - 1 : 0), cmax = c + ((cspan) ? parseInt(cspan, 10) - 1 : 0); for (var rr = r; rr <= rmax; rr++) { if (typeof map[rr] == "undefined") { map[rr] = []; } for (var cc = c; cc <= cmax; cc++) { map[rr][cc] = new MapCell(cell); map[rr][cc].isColspan = (cspan && parseInt(cspan, 10) > 1); map[rr][cc].isRowspan = (rspan && parseInt(rspan, 10) > 1); map[rr][cc].firstCol = cc == c; map[rr][cc].lastCol = cc == cmax; map[rr][cc].firstRow = rr == r; map[rr][cc].lastRow = rr == rmax; map[rr][cc].isReal = cc == c && rr == r; map[rr][cc].spanCollection = spanCollect; spanCollect.push(map[rr][cc]); } } }, setCellAsModified: function(cell) { cell.modified = true; if (cell.spanCollection.length > 0) { for (var s = 0, smax = cell.spanCollection.length; s < smax; s++) { cell.spanCollection[s].modified = true; } } }, setTableMap: function() { var map = []; var tableRows = this.getTableRows(), ridx, row, cells, cidx, cell, c, cspan, rspan; for (ridx = 0; ridx < tableRows.length; ridx++) { row = tableRows[ridx]; cells = this.getRowCells(row); c = 0; if (typeof map[ridx] == "undefined") { map[ridx] = []; } for (cidx = 0; cidx < cells.length; cidx++) { cell = cells[cidx]; // If cell allready set means it is set by col or rowspan, // so increase cols index until free col is found while (typeof map[ridx][c] != "undefined") { c++; } cspan = api.getAttribute(cell, 'colspan'); rspan = api.getAttribute(cell, 'rowspan'); if (cspan || rspan) { this.addSpannedCellToMap(cell, map, ridx, c, cspan, rspan); c = c + ((cspan) ? parseInt(cspan, 10) : 1); } else { map[ridx][c] = new MapCell(cell); c++; } } } this.map = map; return map; }, getRowCells: function(row) { var inlineTables = this.table.querySelectorAll('table'), inlineCells = (inlineTables) ? queryInList(inlineTables, 'th, td') : [], allCells = row.querySelectorAll('th, td'), tableCells = (inlineCells.length > 0) ? wysihtml5.lang.array(allCells).without(inlineCells) : allCells; return tableCells; }, getTableRows: function() { var inlineTables = this.table.querySelectorAll('table'), inlineRows = (inlineTables) ? queryInList(inlineTables, 'tr') : [], allRows = this.table.querySelectorAll('tr'), tableRows = (inlineRows.length > 0) ? wysihtml5.lang.array(allRows).without(inlineRows) : allRows; return tableRows; }, getMapIndex: function(cell) { var r_length = this.map.length, c_length = (this.map && this.map[0]) ? this.map[0].length : 0; for (var r_idx = 0;r_idx < r_length; r_idx++) { for (var c_idx = 0;c_idx < c_length; c_idx++) { if (this.map[r_idx][c_idx].el === cell) { return {'row': r_idx, 'col': c_idx}; } } } return false; }, getElementAtIndex: function(idx) { this.setTableMap(); if (this.map[idx.row] && this.map[idx.row][idx.col] && this.map[idx.row][idx.col].el) { return this.map[idx.row][idx.col].el; } return null; }, getMapElsTo: function(to_cell) { var els = []; this.setTableMap(); this.idx_start = this.getMapIndex(this.cell); this.idx_end = this.getMapIndex(to_cell); // switch indexes if start is bigger than end if (this.idx_start.row > this.idx_end.row || (this.idx_start.row == this.idx_end.row && this.idx_start.col > this.idx_end.col)) { var temp_idx = this.idx_start; this.idx_start = this.idx_end; this.idx_end = temp_idx; } if (this.idx_start.col > this.idx_end.col) { var temp_cidx = this.idx_start.col; this.idx_start.col = this.idx_end.col; this.idx_end.col = temp_cidx; } if (this.idx_start != null && this.idx_end != null) { for (var row = this.idx_start.row, maxr = this.idx_end.row; row <= maxr; row++) { for (var col = this.idx_start.col, maxc = this.idx_end.col; col <= maxc; col++) { els.push(this.map[row][col].el); } } } return els; }, orderSelectionEnds: function(secondcell) { this.setTableMap(); this.idx_start = this.getMapIndex(this.cell); this.idx_end = this.getMapIndex(secondcell); // switch indexes if start is bigger than end if (this.idx_start.row > this.idx_end.row || (this.idx_start.row == this.idx_end.row && this.idx_start.col > this.idx_end.col)) { var temp_idx = this.idx_start; this.idx_start = this.idx_end; this.idx_end = temp_idx; } if (this.idx_start.col > this.idx_end.col) { var temp_cidx = this.idx_start.col; this.idx_start.col = this.idx_end.col; this.idx_end.col = temp_cidx; } return { "start": this.map[this.idx_start.row][this.idx_start.col].el, "end": this.map[this.idx_end.row][this.idx_end.col].el }; }, createCells: function(tag, nr, attrs) { var doc = this.table.ownerDocument, frag = doc.createDocumentFragment(), cell; for (var i = 0; i < nr; i++) { cell = doc.createElement(tag); if (attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { cell.setAttribute(attr, attrs[attr]); } } } // add non breaking space cell.appendChild(document.createTextNode("\u00a0")); frag.appendChild(cell); } return frag; }, // Returns next real cell (not part of spanned cell unless first) on row if selected index is not real. I no real cells -1 will be returned correctColIndexForUnreals: function(col, row) { var r = this.map[row], corrIdx = -1; for (var i = 0, max = col; i < col; i++) { if (r[i].isReal){ corrIdx++; } } return corrIdx; }, getLastNewCellOnRow: function(row, rowLimit) { var cells = this.getRowCells(row), cell, idx; for (var cidx = 0, cmax = cells.length; cidx < cmax; cidx++) { cell = cells[cidx]; idx = this.getMapIndex(cell); if (idx === false || (typeof rowLimit != "undefined" && idx.row != rowLimit)) { return cell; } } return null; }, removeEmptyTable: function() { var cells = this.table.querySelectorAll('td, th'); if (!cells || cells.length == 0) { removeElement(this.table); return true; } else { return false; } }, // Splits merged cell on row to unique cells splitRowToCells: function(cell) { if (cell.isColspan) { var colspan = parseInt(api.getAttribute(cell.el, 'colspan') || 1, 10), cType = cell.el.tagName.toLowerCase(); if (colspan > 1) { var newCells = this.createCells(cType, colspan -1); insertAfter(cell.el, newCells); } cell.el.removeAttribute('colspan'); } }, getRealRowEl: function(force, idx) { var r = null, c = null; idx = idx || this.idx; for (var cidx = 0, cmax = this.map[idx.row].length; cidx < cmax; cidx++) { c = this.map[idx.row][cidx]; if (c.isReal) { r = api.getParentElement(c.el, { nodeName: ["TR"] }); if (r) { return r; } } } if (r === null && force) { r = api.getParentElement(this.map[idx.row][idx.col].el, { nodeName: ["TR"] }) || null; } return r; }, injectRowAt: function(row, col, colspan, cType, c) { var r = this.getRealRowEl(false, {'row': row, 'col': col}), new_cells = this.createCells(cType, colspan); if (r) { var n_cidx = this.correctColIndexForUnreals(col, row); if (n_cidx >= 0) { insertAfter(this.getRowCells(r)[n_cidx], new_cells); } else { r.insertBefore(new_cells, r.firstChild); } } else { var rr = this.table.ownerDocument.createElement('tr'); rr.appendChild(new_cells); insertAfter(api.getParentElement(c.el, { nodeName: ["TR"] }), rr); } }, canMerge: function(to) { this.to = to; this.setTableMap(); this.idx_start = this.getMapIndex(this.cell); this.idx_end = this.getMapIndex(this.to); // switch indexes if start is bigger than end if (this.idx_start.row > this.idx_end.row || (this.idx_start.row == this.idx_end.row && this.idx_start.col > this.idx_end.col)) { var temp_idx = this.idx_start; this.idx_start = this.idx_end; this.idx_end = temp_idx; } if (this.idx_start.col > this.idx_end.col) { var temp_cidx = this.idx_start.col; this.idx_start.col = this.idx_end.col; this.idx_end.col = temp_cidx; } for (var row = this.idx_start.row, maxr = this.idx_end.row; row <= maxr; row++) { for (var col = this.idx_start.col, maxc = this.idx_end.col; col <= maxc; col++) { if (this.map[row][col].isColspan || this.map[row][col].isRowspan) { return false; } } } return true; }, decreaseCellSpan: function(cell, span) { var nr = parseInt(api.getAttribute(cell.el, span), 10) - 1; if (nr >= 1) { cell.el.setAttribute(span, nr); } else { cell.el.removeAttribute(span); if (span == 'colspan') { cell.isColspan = false; } if (span == 'rowspan') { cell.isRowspan = false; } cell.firstCol = true; cell.lastCol = true; cell.firstRow = true; cell.lastRow = true; cell.isReal = true; } }, removeSurplusLines: function() { var row, cell, ridx, rmax, cidx, cmax, allRowspan; this.setTableMap(); if (this.map) { ridx = 0; rmax = this.map.length; for (;ridx < rmax; ridx++) { row = this.map[ridx]; allRowspan = true; cidx = 0; cmax = row.length; for (; cidx < cmax; cidx++) { cell = row[cidx]; if (!(api.getAttribute(cell.el, "rowspan") && parseInt(api.getAttribute(cell.el, "rowspan"), 10) > 1 && cell.firstRow !== true)) { allRowspan = false; break; } } if (allRowspan) { cidx = 0; for (; cidx < cmax; cidx++) { this.decreaseCellSpan(row[cidx], 'rowspan'); } } } // remove rows without cells var tableRows = this.getTableRows(); ridx = 0; rmax = tableRows.length; for (;ridx < rmax; ridx++) { row = tableRows[ridx]; if (row.childNodes.length == 0 && (/^\s*$/.test(row.textContent || row.innerText))) { removeElement(row); } } } }, fillMissingCells: function() { var r_max = 0, c_max = 0, prevcell = null; this.setTableMap(); if (this.map) { // find maximal dimensions of broken table r_max = this.map.length; for (var ridx = 0; ridx < r_max; ridx++) { if (this.map[ridx].length > c_max) { c_max = this.map[ridx].length; } } for (var row = 0; row < r_max; row++) { for (var col = 0; col < c_max; col++) { if (this.map[row] && !this.map[row][col]) { if (col > 0) { this.map[row][col] = new MapCell(this.createCells('td', 1)); prevcell = this.map[row][col-1]; if (prevcell && prevcell.el && prevcell.el.parent) { // if parent does not exist element is removed from dom insertAfter(this.map[row][col-1].el, this.map[row][col].el); } } } } } } }, rectify: function() { if (!this.removeEmptyTable()) { this.removeSurplusLines(); this.fillMissingCells(); return true; } else { return false; } }, unmerge: function() { if (this.rectify()) { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx) { var thisCell = this.map[this.idx.row][this.idx.col], colspan = (api.getAttribute(thisCell.el, "colspan")) ? parseInt(api.getAttribute(thisCell.el, "colspan"), 10) : 1, cType = thisCell.el.tagName.toLowerCase(); if (thisCell.isRowspan) { var rowspan = parseInt(api.getAttribute(thisCell.el, "rowspan"), 10); if (rowspan > 1) { for (var nr = 1, maxr = rowspan - 1; nr <= maxr; nr++){ this.injectRowAt(this.idx.row + nr, this.idx.col, colspan, cType, thisCell); } } thisCell.el.removeAttribute('rowspan'); } this.splitRowToCells(thisCell); } } }, // merges cells from start cell (defined in creating obj) to "to" cell merge: function(to) { if (this.rectify()) { if (this.canMerge(to)) { var rowspan = this.idx_end.row - this.idx_start.row + 1, colspan = this.idx_end.col - this.idx_start.col + 1; for (var row = this.idx_start.row, maxr = this.idx_end.row; row <= maxr; row++) { for (var col = this.idx_start.col, maxc = this.idx_end.col; col <= maxc; col++) { if (row == this.idx_start.row && col == this.idx_start.col) { if (rowspan > 1) { this.map[row][col].el.setAttribute('rowspan', rowspan); } if (colspan > 1) { this.map[row][col].el.setAttribute('colspan', colspan); } } else { // transfer content if (!(/^\s*<br\/?>\s*$/.test(this.map[row][col].el.innerHTML.toLowerCase()))) { this.map[this.idx_start.row][this.idx_start.col].el.innerHTML += ' ' + this.map[row][col].el.innerHTML; } removeElement(this.map[row][col].el); } } } this.rectify(); } else { if (window.console) { console.log('Do not know how to merge allready merged cells.'); } } } }, // Decreases rowspan of a cell if it is done on first cell of rowspan row (real cell) // Cell is moved to next row (if it is real) collapseCellToNextRow: function(cell) { var cellIdx = this.getMapIndex(cell.el), newRowIdx = cellIdx.row + 1, newIdx = {'row': newRowIdx, 'col': cellIdx.col}; if (newRowIdx < this.map.length) { var row = this.getRealRowEl(false, newIdx); if (row !== null) { var n_cidx = this.correctColIndexForUnreals(newIdx.col, newIdx.row); if (n_cidx >= 0) { insertAfter(this.getRowCells(row)[n_cidx], cell.el); } else { var lastCell = this.getLastNewCellOnRow(row, newRowIdx); if (lastCell !== null) { insertAfter(lastCell, cell.el); } else { row.insertBefore(cell.el, row.firstChild); } } if (parseInt(api.getAttribute(cell.el, 'rowspan'), 10) > 2) { cell.el.setAttribute('rowspan', parseInt(api.getAttribute(cell.el, 'rowspan'), 10) - 1); } else { cell.el.removeAttribute('rowspan'); } } } }, // Removes a cell when removing a row // If is rowspan cell then decreases the rowspan // and moves cell to next row if needed (is first cell of rowspan) removeRowCell: function(cell) { if (cell.isReal) { if (cell.isRowspan) { this.collapseCellToNextRow(cell); } else { removeElement(cell.el); } } else { if (parseInt(api.getAttribute(cell.el, 'rowspan'), 10) > 2) { cell.el.setAttribute('rowspan', parseInt(api.getAttribute(cell.el, 'rowspan'), 10) - 1); } else { cell.el.removeAttribute('rowspan'); } } }, getRowElementsByCell: function() { var cells = []; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { var modRow = this.map[this.idx.row]; for (var cidx = 0, cmax = modRow.length; cidx < cmax; cidx++) { if (modRow[cidx].isReal) { cells.push(modRow[cidx].el); } } } return cells; }, getColumnElementsByCell: function() { var cells = []; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { for (var ridx = 0, rmax = this.map.length; ridx < rmax; ridx++) { if (this.map[ridx][this.idx.col] && this.map[ridx][this.idx.col].isReal) { cells.push(this.map[ridx][this.idx.col].el); } } } return cells; }, // Removes the row of selected cell removeRow: function() { var oldRow = api.getParentElement(this.cell, { nodeName: ["TR"] }); if (oldRow) { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { var modRow = this.map[this.idx.row]; for (var cidx = 0, cmax = modRow.length; cidx < cmax; cidx++) { if (!modRow[cidx].modified) { this.setCellAsModified(modRow[cidx]); this.removeRowCell(modRow[cidx]); } } } removeElement(oldRow); } }, removeColCell: function(cell) { if (cell.isColspan) { if (parseInt(api.getAttribute(cell.el, 'colspan'), 10) > 2) { cell.el.setAttribute('colspan', parseInt(api.getAttribute(cell.el, 'colspan'), 10) - 1); } else { cell.el.removeAttribute('colspan'); } } else if (cell.isReal) { removeElement(cell.el); } }, removeColumn: function() { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { for (var ridx = 0, rmax = this.map.length; ridx < rmax; ridx++) { if (!this.map[ridx][this.idx.col].modified) { this.setCellAsModified(this.map[ridx][this.idx.col]); this.removeColCell(this.map[ridx][this.idx.col]); } } } }, // removes row or column by selected cell element remove: function(what) { if (this.rectify()) { switch (what) { case 'row': this.removeRow(); break; case 'column': this.removeColumn(); break; } this.rectify(); } }, addRow: function(where) { var doc = this.table.ownerDocument; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (where == "below" && api.getAttribute(this.cell, 'rowspan')) { this.idx.row = this.idx.row + parseInt(api.getAttribute(this.cell, 'rowspan'), 10) - 1; } if (this.idx !== false) { var modRow = this.map[this.idx.row], newRow = doc.createElement('tr'); for (var ridx = 0, rmax = modRow.length; ridx < rmax; ridx++) { if (!modRow[ridx].modified) { this.setCellAsModified(modRow[ridx]); this.addRowCell(modRow[ridx], newRow, where); } } switch (where) { case 'below': insertAfter(this.getRealRowEl(true), newRow); break; case 'above': var cr = api.getParentElement(this.map[this.idx.row][this.idx.col].el, { nodeName: ["TR"] }); if (cr) { cr.parentNode.insertBefore(newRow, cr); } break; } } }, addRowCell: function(cell, row, where) { var colSpanAttr = (cell.isColspan) ? {"colspan" : api.getAttribute(cell.el, 'colspan')} : null; if (cell.isReal) { if (where != 'above' && cell.isRowspan) { cell.el.setAttribute('rowspan', parseInt(api.getAttribute(cell.el,'rowspan'), 10) + 1); } else { row.appendChild(this.createCells('td', 1, colSpanAttr)); } } else { if (where != 'above' && cell.isRowspan && cell.lastRow) { row.appendChild(this.createCells('td', 1, colSpanAttr)); } else if (c.isRowspan) { cell.el.attr('rowspan', parseInt(api.getAttribute(cell.el, 'rowspan'), 10) + 1); } } }, add: function(where) { if (this.rectify()) { if (where == 'below' || where == 'above') { this.addRow(where); } if (where == 'before' || where == 'after') { this.addColumn(where); } } }, addColCell: function (cell, ridx, where) { var doAdd, cType = cell.el.tagName.toLowerCase(); // defines add cell vs expand cell conditions // true means add switch (where) { case "before": doAdd = (!cell.isColspan || cell.firstCol); break; case "after": doAdd = (!cell.isColspan || cell.lastCol || (cell.isColspan && c.el == this.cell)); break; } if (doAdd){ // adds a cell before or after current cell element switch (where) { case "before": cell.el.parentNode.insertBefore(this.createCells(cType, 1), cell.el); break; case "after": insertAfter(cell.el, this.createCells(cType, 1)); break; } // handles if cell has rowspan if (cell.isRowspan) { this.handleCellAddWithRowspan(cell, ridx+1, where); } } else { // expands cell cell.el.setAttribute('colspan', parseInt(api.getAttribute(cell.el, 'colspan'), 10) + 1); } }, addColumn: function(where) { var row, modCell; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (where == "after" && api.getAttribute(this.cell, 'colspan')) { this.idx.col = this.idx.col + parseInt(api.getAttribute(this.cell, 'colspan'), 10) - 1; } if (this.idx !== false) { for (var ridx = 0, rmax = this.map.length; ridx < rmax; ridx++ ) { row = this.map[ridx]; if (row[this.idx.col]) { modCell = row[this.idx.col]; if (!modCell.modified) { this.setCellAsModified(modCell); this.addColCell(modCell, ridx , where); } } } } }, handleCellAddWithRowspan: function (cell, ridx, where) { var addRowsNr = parseInt(api.getAttribute(this.cell, 'rowspan'), 10) - 1, crow = api.getParentElement(cell.el, { nodeName: ["TR"] }), cType = cell.el.tagName.toLowerCase(), cidx, temp_r_cells, doc = this.table.ownerDocument, nrow; for (var i = 0; i < addRowsNr; i++) { cidx = this.correctColIndexForUnreals(this.idx.col, (ridx + i)); crow = nextNode(crow, 'tr'); if (crow) { if (cidx > 0) { switch (where) { case "before": temp_r_cells = this.getRowCells(crow); if (cidx > 0 && this.map[ridx + i][this.idx.col].el != temp_r_cells[cidx] && cidx == temp_r_cells.length - 1) { insertAfter(temp_r_cells[cidx], this.createCells(cType, 1)); } else { temp_r_cells[cidx].parentNode.insertBefore(this.createCells(cType, 1), temp_r_cells[cidx]); } break; case "after": insertAfter(this.getRowCells(crow)[cidx], this.createCells(cType, 1)); break; } } else { crow.insertBefore(this.createCells(cType, 1), crow.firstChild); } } else { nrow = doc.createElement('tr'); nrow.appendChild(this.createCells(cType, 1)); this.table.appendChild(nrow); } } } }; api.table = { getCellsBetween: function(cell1, cell2) { var c1 = new TableModifyerByCell(cell1); return c1.getMapElsTo(cell2); }, addCells: function(cell, where) { var c = new TableModifyerByCell(cell); c.add(where); }, removeCells: function(cell, what) { var c = new TableModifyerByCell(cell); c.remove(what); }, mergeCellsBetween: function(cell1, cell2) { var c1 = new TableModifyerByCell(cell1); c1.merge(cell2); }, unmergeCell: function(cell) { var c = new TableModifyerByCell(cell); c.unmerge(); }, orderSelectionEnds: function(cell, cell2) { var c = new TableModifyerByCell(cell); return c.orderSelectionEnds(cell2); }, indexOf: function(cell) { var c = new TableModifyerByCell(cell); c.setTableMap(); return c.getMapIndex(cell); }, findCell: function(table, idx) { var c = new TableModifyerByCell(null, table); return c.getElementAtIndex(idx); }, findRowByCell: function(cell) { var c = new TableModifyerByCell(cell); return c.getRowElementsByCell(); }, findColumnByCell: function(cell) { var c = new TableModifyerByCell(cell); return c.getColumnElementsByCell(); }, canMerge: function(cell1, cell2) { var c = new TableModifyerByCell(cell1); return c.canMerge(cell2); } }; })(wysihtml5); ;// does a selector query on element or array of elements wysihtml5.dom.query = function(elements, query) { var ret = [], q; if (elements.nodeType) { elements = [elements]; } for (var e = 0, len = elements.length; e < len; e++) { q = elements[e].querySelectorAll(query); if (q) { for(var i = q.length; i--; ret.unshift(q[i])); } } return ret; }; ;wysihtml5.dom.compareDocumentPosition = (function() { var documentElement = document.documentElement; if (documentElement.compareDocumentPosition) { return function(container, element) { return container.compareDocumentPosition(element); }; } else { return function( container, element ) { // implementation borrowed from https://github.com/tmpvar/jsdom/blob/681a8524b663281a0f58348c6129c8c184efc62c/lib/jsdom/level3/core.js // MIT license var thisOwner, otherOwner; if( container.nodeType === 9) // Node.DOCUMENT_NODE thisOwner = container; else thisOwner = container.ownerDocument; if( element.nodeType === 9) // Node.DOCUMENT_NODE otherOwner = element; else otherOwner = element.ownerDocument; if( container === element ) return 0; if( container === element.ownerDocument ) return 4 + 16; //Node.DOCUMENT_POSITION_FOLLOWING + Node.DOCUMENT_POSITION_CONTAINED_BY; if( container.ownerDocument === element ) return 2 + 8; //Node.DOCUMENT_POSITION_PRECEDING + Node.DOCUMENT_POSITION_CONTAINS; if( thisOwner !== otherOwner ) return 1; // Node.DOCUMENT_POSITION_DISCONNECTED; // Text nodes for attributes does not have a _parentNode. So we need to find them as attribute child. if( container.nodeType === 2 /*Node.ATTRIBUTE_NODE*/ && container.childNodes && wysihtml5.lang.array(container.childNodes).indexOf( element ) !== -1) return 4 + 16; //Node.DOCUMENT_POSITION_FOLLOWING + Node.DOCUMENT_POSITION_CONTAINED_BY; if( element.nodeType === 2 /*Node.ATTRIBUTE_NODE*/ && element.childNodes && wysihtml5.lang.array(element.childNodes).indexOf( container ) !== -1) return 2 + 8; //Node.DOCUMENT_POSITION_PRECEDING + Node.DOCUMENT_POSITION_CONTAINS; var point = container; var parents = [ ]; var previous = null; while( point ) { if( point == element ) return 2 + 8; //Node.DOCUMENT_POSITION_PRECEDING + Node.DOCUMENT_POSITION_CONTAINS; parents.push( point ); point = point.parentNode; } point = element; previous = null; while( point ) { if( point == container ) return 4 + 16; //Node.DOCUMENT_POSITION_FOLLOWING + Node.DOCUMENT_POSITION_CONTAINED_BY; var location_index = wysihtml5.lang.array(parents).indexOf( point ); if( location_index !== -1) { var smallest_common_ancestor = parents[ location_index ]; var this_index = wysihtml5.lang.array(smallest_common_ancestor.childNodes).indexOf( parents[location_index - 1]);//smallest_common_ancestor.childNodes.toArray().indexOf( parents[location_index - 1] ); var other_index = wysihtml5.lang.array(smallest_common_ancestor.childNodes).indexOf( previous ); //smallest_common_ancestor.childNodes.toArray().indexOf( previous ); if( this_index > other_index ) { return 2; //Node.DOCUMENT_POSITION_PRECEDING; } else { return 4; //Node.DOCUMENT_POSITION_FOLLOWING; } } previous = point; point = point.parentNode; } return 1; //Node.DOCUMENT_POSITION_DISCONNECTED; }; } })(); ;wysihtml5.dom.unwrap = function(node) { if (node.parentNode) { while (node.lastChild) { wysihtml5.dom.insert(node.lastChild).after(node); } node.parentNode.removeChild(node); } };;/* * Methods for fetching pasted html before it gets inserted into content **/ /* Modern event.clipboardData driven approach. * Advantage is that it does not have to loose selection or modify dom to catch the data. * IE does not support though. **/ wysihtml5.dom.getPastedHtml = function(event) { var html; if (event.clipboardData) { if (wysihtml5.lang.array(event.clipboardData.types).contains('text/html')) { html = event.clipboardData.getData('text/html'); } else if (wysihtml5.lang.array(event.clipboardData.types).contains('text/plain')) { html = wysihtml5.lang.string(event.clipboardData.getData('text/plain')).escapeHTML(true, true); } } return html; }; /* Older temprorary contenteditable as paste source catcher method for fallbacks */ wysihtml5.dom.getPastedHtmlWithDiv = function (composer, f) { var selBookmark = composer.selection.getBookmark(), doc = composer.element.ownerDocument, cleanerDiv = doc.createElement('DIV'); doc.body.appendChild(cleanerDiv); cleanerDiv.style.width = "1px"; cleanerDiv.style.height = "1px"; cleanerDiv.style.overflow = "hidden"; cleanerDiv.setAttribute('contenteditable', 'true'); cleanerDiv.focus(); setTimeout(function () { composer.selection.setBookmark(selBookmark); f(cleanerDiv.innerHTML); cleanerDiv.parentNode.removeChild(cleanerDiv); }, 0); };;/** * Fix most common html formatting misbehaviors of browsers implementation when inserting * content via copy & paste contentEditable * * @author Christopher Blum */ wysihtml5.quirks.cleanPastedHTML = (function() { var styleToRegex = function (styleStr) { var trimmedStr = wysihtml5.lang.string(styleStr).trim(), escapedStr = trimmedStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); return new RegExp("^((?!^" + escapedStr + "$).)*$", "i"); }; var extendRulesWithStyleExceptions = function (rules, exceptStyles) { var newRules = wysihtml5.lang.object(rules).clone(true), tag, style; for (tag in newRules.tags) { if (newRules.tags.hasOwnProperty(tag)) { if (newRules.tags[tag].keep_styles) { for (style in newRules.tags[tag].keep_styles) { if (newRules.tags[tag].keep_styles.hasOwnProperty(style)) { if (exceptStyles[style]) { newRules.tags[tag].keep_styles[style] = styleToRegex(exceptStyles[style]); } } } } } } return newRules; }; var pickRuleset = function(ruleset, html) { var pickedSet, defaultSet; if (!ruleset) { return null; } for (var i = 0, max = ruleset.length; i < max; i++) { if (!ruleset[i].condition) { defaultSet = ruleset[i].set; } if (ruleset[i].condition && ruleset[i].condition.test(html)) { return ruleset[i].set; } } return defaultSet; }; return function(html, options) { var exceptStyles = { 'color': wysihtml5.dom.getStyle("color").from(options.referenceNode), 'fontSize': wysihtml5.dom.getStyle("font-size").from(options.referenceNode) }, rules = extendRulesWithStyleExceptions(pickRuleset(options.rules, html) || {}, exceptStyles), newHtml; newHtml = wysihtml5.dom.parse(html, { "rules": rules, "cleanUp": true, // <span> elements, empty or without attributes, should be removed/replaced with their content "context": options.referenceNode.ownerDocument, "uneditableClass": options.uneditableClass, "clearInternals" : true, // don't paste temprorary selection and other markings "unjoinNbsps" : true }); return newHtml; }; })();;/** * IE and Opera leave an empty paragraph in the contentEditable element after clearing it * * @param {Object} contentEditableElement The contentEditable element to observe for clearing events * @exaple * wysihtml5.quirks.ensureProperClearing(myContentEditableElement); */ wysihtml5.quirks.ensureProperClearing = (function() { var clearIfNecessary = function() { var element = this; setTimeout(function() { var innerHTML = element.innerHTML.toLowerCase(); if (innerHTML == "<p>&nbsp;</p>" || innerHTML == "<p>&nbsp;</p><p>&nbsp;</p>") { element.innerHTML = ""; } }, 0); }; return function(composer) { wysihtml5.dom.observe(composer.element, ["cut", "keydown"], clearIfNecessary); }; })(); ;// See https://bugzilla.mozilla.org/show_bug.cgi?id=664398 // // In Firefox this: // var d = document.createElement("div"); // d.innerHTML ='<a href="~"></a>'; // d.innerHTML; // will result in: // <a href="%7E"></a> // which is wrong (function(wysihtml5) { var TILDE_ESCAPED = "%7E"; wysihtml5.quirks.getCorrectInnerHTML = function(element) { var innerHTML = element.innerHTML; if (innerHTML.indexOf(TILDE_ESCAPED) === -1) { return innerHTML; } var elementsWithTilde = element.querySelectorAll("[href*='~'], [src*='~']"), url, urlToSearch, length, i; for (i=0, length=elementsWithTilde.length; i<length; i++) { url = elementsWithTilde[i].href || elementsWithTilde[i].src; urlToSearch = wysihtml5.lang.string(url).replace("~").by(TILDE_ESCAPED); innerHTML = wysihtml5.lang.string(innerHTML).replace(urlToSearch).by(url); } return innerHTML; }; })(wysihtml5); ;/** * Force rerendering of a given element * Needed to fix display misbehaviors of IE * * @param {Element} element The element object which needs to be rerendered * @example * wysihtml5.quirks.redraw(document.body); */ (function(wysihtml5) { var CLASS_NAME = "wysihtml5-quirks-redraw"; wysihtml5.quirks.redraw = function(element) { wysihtml5.dom.addClass(element, CLASS_NAME); wysihtml5.dom.removeClass(element, CLASS_NAME); // Following hack is needed for firefox to make sure that image resize handles are properly removed try { var doc = element.ownerDocument; doc.execCommand("italic", false, null); doc.execCommand("italic", false, null); } catch(e) {} }; })(wysihtml5); ;wysihtml5.quirks.tableCellsSelection = function(editable, editor) { var dom = wysihtml5.dom, select = { table: null, start: null, end: null, cells: null, select: selectCells }, selection_class = "wysiwyg-tmp-selected-cell", moveHandler = null, upHandler = null; function init () { dom.observe(editable, "mousedown", function(event) { var target = wysihtml5.dom.getParentElement(event.target, { nodeName: ["TD", "TH"] }); if (target) { handleSelectionMousedown(target); } }); return select; } function handleSelectionMousedown (target) { select.start = target; select.end = target; select.cells = [target]; select.table = dom.getParentElement(select.start, { nodeName: ["TABLE"] }); if (select.table) { removeCellSelections(); dom.addClass(target, selection_class); moveHandler = dom.observe(editable, "mousemove", handleMouseMove); upHandler = dom.observe(editable, "mouseup", handleMouseUp); editor.fire("tableselectstart").fire("tableselectstart:composer"); } } // remove all selection classes function removeCellSelections () { if (editable) { var selectedCells = editable.querySelectorAll('.' + selection_class); if (selectedCells.length > 0) { for (var i = 0; i < selectedCells.length; i++) { dom.removeClass(selectedCells[i], selection_class); } } } } function addSelections (cells) { for (var i = 0; i < cells.length; i++) { dom.addClass(cells[i], selection_class); } } function handleMouseMove (event) { var curTable = null, cell = dom.getParentElement(event.target, { nodeName: ["TD","TH"] }), oldEnd; if (cell && select.table && select.start) { curTable = dom.getParentElement(cell, { nodeName: ["TABLE"] }); if (curTable && curTable === select.table) { removeCellSelections(); oldEnd = select.end; select.end = cell; select.cells = dom.table.getCellsBetween(select.start, cell); if (select.cells.length > 1) { editor.composer.selection.deselect(); } addSelections(select.cells); if (select.end !== oldEnd) { editor.fire("tableselectchange").fire("tableselectchange:composer"); } } } } function handleMouseUp (event) { moveHandler.stop(); upHandler.stop(); editor.fire("tableselect").fire("tableselect:composer"); setTimeout(function() { bindSideclick(); },0); } function bindSideclick () { var sideClickHandler = dom.observe(editable.ownerDocument, "click", function(event) { sideClickHandler.stop(); if (dom.getParentElement(event.target, { nodeName: ["TABLE"] }) != select.table) { removeCellSelections(); select.table = null; select.start = null; select.end = null; editor.fire("tableunselect").fire("tableunselect:composer"); } }); } function selectCells (start, end) { select.start = start; select.end = end; select.table = dom.getParentElement(select.start, { nodeName: ["TABLE"] }); selectedCells = dom.table.getCellsBetween(select.start, select.end); addSelections(selectedCells); bindSideclick(); editor.fire("tableselect").fire("tableselect:composer"); } return init(); }; ;(function(wysihtml5) { var RGBA_REGEX = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([\d\.]+)\s*\)/i, RGB_REGEX = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/i, HEX6_REGEX = /^#([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])/i, HEX3_REGEX = /^#([0-9a-f])([0-9a-f])([0-9a-f])/i; var param_REGX = function (p) { return new RegExp("(^|\\s|;)" + p + "\\s*:\\s*[^;$]+" , "gi"); }; wysihtml5.quirks.styleParser = { parseColor: function(stylesStr, paramName) { var paramRegex = param_REGX(paramName), params = stylesStr.match(paramRegex), radix = 10, str, colorMatch; if (params) { for (var i = params.length; i--;) { params[i] = wysihtml5.lang.string(params[i].split(':')[1]).trim(); } str = params[params.length-1]; if (RGBA_REGEX.test(str)) { colorMatch = str.match(RGBA_REGEX); } else if (RGB_REGEX.test(str)) { colorMatch = str.match(RGB_REGEX); } else if (HEX6_REGEX.test(str)) { colorMatch = str.match(HEX6_REGEX); radix = 16; } else if (HEX3_REGEX.test(str)) { colorMatch = str.match(HEX3_REGEX); colorMatch.shift(); colorMatch.push(1); return wysihtml5.lang.array(colorMatch).map(function(d, idx) { return (idx < 3) ? (parseInt(d, 16) * 16) + parseInt(d, 16): parseFloat(d); }); } if (colorMatch) { colorMatch.shift(); if (!colorMatch[3]) { colorMatch.push(1); } return wysihtml5.lang.array(colorMatch).map(function(d, idx) { return (idx < 3) ? parseInt(d, radix): parseFloat(d); }); } } return false; }, unparseColor: function(val, props) { if (props) { if (props == "hex") { return (val[0].toString(16).toUpperCase()) + (val[1].toString(16).toUpperCase()) + (val[2].toString(16).toUpperCase()); } else if (props == "hash") { return "#" + (val[0].toString(16).toUpperCase()) + (val[1].toString(16).toUpperCase()) + (val[2].toString(16).toUpperCase()); } else if (props == "rgb") { return "rgb(" + val[0] + "," + val[1] + "," + val[2] + ")"; } else if (props == "rgba") { return "rgba(" + val[0] + "," + val[1] + "," + val[2] + "," + val[3] + ")"; } else if (props == "csv") { return val[0] + "," + val[1] + "," + val[2] + "," + val[3]; } } if (val[3] && val[3] !== 1) { return "rgba(" + val[0] + "," + val[1] + "," + val[2] + "," + val[3] + ")"; } else { return "rgb(" + val[0] + "," + val[1] + "," + val[2] + ")"; } }, parseFontSize: function(stylesStr) { var params = stylesStr.match(param_REGX('font-size')); if (params) { return wysihtml5.lang.string(params[params.length - 1].split(':')[1]).trim(); } return false; } }; })(wysihtml5); ;/** * Selection API * * @example * var selection = new wysihtml5.Selection(editor); */ (function(wysihtml5) { var dom = wysihtml5.dom; function _getCumulativeOffsetTop(element) { var top = 0; if (element.parentNode) { do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); } return top; } // Provides the depth of ``descendant`` relative to ``ancestor`` function getDepth(ancestor, descendant) { var ret = 0; while (descendant !== ancestor) { ret++; descendant = descendant.parentNode; if (!descendant) throw new Error("not a descendant of ancestor!"); } return ret; } // Should fix the obtained ranges that cannot surrond contents normally to apply changes upon // Being considerate to firefox that sets range start start out of span and end inside on doubleclick initiated selection function expandRangeToSurround(range) { if (range.canSurroundContents()) return; var common = range.commonAncestorContainer, start_depth = getDepth(common, range.startContainer), end_depth = getDepth(common, range.endContainer); while(!range.canSurroundContents()) { // In the following branches, we cannot just decrement the depth variables because the setStartBefore/setEndAfter may move the start or end of the range more than one level relative to ``common``. So we need to recompute the depth. if (start_depth > end_depth) { range.setStartBefore(range.startContainer); start_depth = getDepth(common, range.startContainer); } else { range.setEndAfter(range.endContainer); end_depth = getDepth(common, range.endContainer); } } } wysihtml5.Selection = Base.extend( /** @scope wysihtml5.Selection.prototype */ { constructor: function(editor, contain, unselectableClass) { // Make sure that our external range library is initialized window.rangy.init(); this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; this.contain = contain; this.unselectableClass = unselectableClass || false; }, /** * Get the current selection as a bookmark to be able to later restore it * * @return {Object} An object that represents the current selection */ getBookmark: function() { var range = this.getRange(); if (range) expandRangeToSurround(range); return range && range.cloneRange(); }, /** * Restore a selection retrieved via wysihtml5.Selection.prototype.getBookmark * * @param {Object} bookmark An object that represents the current selection */ setBookmark: function(bookmark) { if (!bookmark) { return; } this.setSelection(bookmark); }, /** * Set the caret in front of the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); */ setBefore: function(node) { var range = rangy.createRange(this.doc); range.setStartBefore(node); range.setEndBefore(node); return this.setSelection(range); }, /** * Set the caret after the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); */ setAfter: function(node) { var range = rangy.createRange(this.doc); range.setStartAfter(node); range.setEndAfter(node); return this.setSelection(range); }, /** * Ability to select/mark nodes * * @param {Element} node The node/element to select * @example * selection.selectNode(document.getElementById("my-image")); */ selectNode: function(node, avoidInvisibleSpace) { var range = rangy.createRange(this.doc), isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : (node.nodeName !== "IMG"), content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE), displayStyle = dom.getStyle("display").from(node), isBlockElement = (displayStyle === "block" || displayStyle === "list-item"); if (isEmpty && isElement && canHaveHTML && !avoidInvisibleSpace) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } if (canHaveHTML) { range.selectNodeContents(node); } else { range.selectNode(node); } if (canHaveHTML && isEmpty && isElement) { range.collapse(isBlockElement); } else if (canHaveHTML && isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } this.setSelection(range); }, /** * Get the node which contains the selection * * @param {Boolean} [controlRange] (only IE) Whether it should return the selected ControlRange element when the selection type is a "ControlRange" * @return {Object} The node that contains the caret * @example * var nodeThatContainsCaret = selection.getSelectedNode(); */ getSelectedNode: function(controlRange) { var selection, range; if (controlRange && this.doc.selection && this.doc.selection.type === "Control") { range = this.doc.selection.createRange(); if (range && range.length) { return range.item(0); } } selection = this.getSelection(this.doc); if (selection.focusNode === selection.anchorNode) { return selection.focusNode; } else { range = this.getRange(this.doc); return range ? range.commonAncestorContainer : this.doc.body; } }, fixSelBorders: function() { var range = this.getRange(); expandRangeToSurround(range); this.setSelection(range); }, getSelectedOwnNodes: function(controlRange) { var selection, ranges = this.getOwnRanges(), ownNodes = []; for (var i = 0, maxi = ranges.length; i < maxi; i++) { ownNodes.push(ranges[i].commonAncestorContainer || this.doc.body); } return ownNodes; }, findNodesInSelection: function(nodeTypes) { var ranges = this.getOwnRanges(), nodes = [], curNodes; for (var i = 0, maxi = ranges.length; i < maxi; i++) { curNodes = ranges[i].getNodes([1], function(node) { return wysihtml5.lang.array(nodeTypes).contains(node.nodeName); }); nodes = nodes.concat(curNodes); } return nodes; }, containsUneditable: function() { var uneditables = this.getOwnUneditables(), selection = this.getSelection(); for (var i = 0, maxi = uneditables.length; i < maxi; i++) { if (selection.containsNode(uneditables[i])) { return true; } } return false; }, deleteContents: function() { var ranges = this.getOwnRanges(); for (var i = ranges.length; i--;) { ranges[i].deleteContents(); } this.setSelection(ranges[0]); }, getPreviousNode: function(node, ignoreEmpty) { if (!node) { var selection = this.getSelection(); node = selection.anchorNode; } if (node === this.contain) { return false; } var ret = node.previousSibling, parent; if (ret === this.contain) { return false; } if (ret && ret.nodeType !== 3 && ret.nodeType !== 1) { // do not count comments and other node types ret = this.getPreviousNode(ret, ignoreEmpty); } else if (ret && ret.nodeType === 3 && (/^\s*$/).test(ret.textContent)) { // do not count empty textnodes as previus nodes ret = this.getPreviousNode(ret, ignoreEmpty); } else if (ignoreEmpty && ret && ret.nodeType === 1 && !wysihtml5.lang.array(["BR", "HR", "IMG"]).contains(ret.nodeName) && (/^[\s]*$/).test(ret.innerHTML)) { // Do not count empty nodes if param set. // Contenteditable tends to bypass and delete these silently when deleting with caret ret = this.getPreviousNode(ret, ignoreEmpty); } else if (!ret && node !== this.contain) { parent = node.parentNode; if (parent !== this.contain) { ret = this.getPreviousNode(parent, ignoreEmpty); } } return (ret !== this.contain) ? ret : false; }, getSelectionParentsByTag: function(tagName) { var nodes = this.getSelectedOwnNodes(), curEl, parents = []; for (var i = 0, maxi = nodes.length; i < maxi; i++) { curEl = (nodes[i].nodeName && nodes[i].nodeName === 'LI') ? nodes[i] : wysihtml5.dom.getParentElement(nodes[i], { nodeName: ['LI']}, false, this.contain); if (curEl) { parents.push(curEl); } } return (parents.length) ? parents : null; }, getRangeToNodeEnd: function() { if (this.isCollapsed()) { var range = this.getRange(), sNode = range.startContainer, pos = range.startOffset, lastR = rangy.createRange(this.doc); lastR.selectNodeContents(sNode); lastR.setStart(sNode, pos); return lastR; } }, caretIsLastInSelection: function() { var r = rangy.createRange(this.doc), s = this.getSelection(), endc = this.getRangeToNodeEnd().cloneContents(), endtxt = endc.textContent; return (/^\s*$/).test(endtxt); }, caretIsFirstInSelection: function() { var r = rangy.createRange(this.doc), s = this.getSelection(), range = this.getRange(), startNode = range.startContainer; if (startNode.nodeType === wysihtml5.TEXT_NODE) { return this.isCollapsed() && (startNode.nodeType === wysihtml5.TEXT_NODE && (/^\s*$/).test(startNode.data.substr(0,range.startOffset))); } else { r.selectNodeContents(this.getRange().commonAncestorContainer); r.collapse(true); return (this.isCollapsed() && (r.startContainer === s.anchorNode || r.endContainer === s.anchorNode) && r.startOffset === s.anchorOffset); } }, caretIsInTheBeginnig: function(ofNode) { var selection = this.getSelection(), node = selection.anchorNode, offset = selection.anchorOffset; if (ofNode) { return (offset === 0 && (node.nodeName && node.nodeName === ofNode.toUpperCase() || wysihtml5.dom.getParentElement(node.parentNode, { nodeName: ofNode }, 1))); } else { return (offset === 0 && !this.getPreviousNode(node, true)); } }, caretIsBeforeUneditable: function() { var selection = this.getSelection(), node = selection.anchorNode, offset = selection.anchorOffset; if (offset === 0) { var prevNode = this.getPreviousNode(node, true); if (prevNode) { var uneditables = this.getOwnUneditables(); for (var i = 0, maxi = uneditables.length; i < maxi; i++) { if (prevNode === uneditables[i]) { return uneditables[i]; } } } } return false; }, // TODO: Figure out a method from following 2 that would work universally executeAndRestoreRangy: function(method, restoreScrollPosition) { var win = this.doc.defaultView || this.doc.parentWindow, sel = rangy.saveSelection(win); if (!sel) { method(); } else { try { method(); } catch(e) { setTimeout(function() { throw e; }, 0); } } rangy.restoreSelection(sel); }, // TODO: has problems in chrome 12. investigate block level and uneditable area inbetween executeAndRestore: function(method, restoreScrollPosition) { var body = this.doc.body, oldScrollTop = restoreScrollPosition && body.scrollTop, oldScrollLeft = restoreScrollPosition && body.scrollLeft, className = "_wysihtml5-temp-placeholder", placeholderHtml = '<span class="' + className + '">' + wysihtml5.INVISIBLE_SPACE + '</span>', range = this.getRange(true), caretPlaceholder, newCaretPlaceholder, nextSibling, prevSibling, node, node2, range2, newRange; // Nothing selected, execute and say goodbye if (!range) { method(body, body); return; } if (!range.collapsed) { range2 = range.cloneRange(); node2 = range2.createContextualFragment(placeholderHtml); range2.collapse(false); range2.insertNode(node2); range2.detach(); } node = range.createContextualFragment(placeholderHtml); range.insertNode(node); if (node2) { caretPlaceholder = this.contain.querySelectorAll("." + className); range.setStartBefore(caretPlaceholder[0]); range.setEndAfter(caretPlaceholder[caretPlaceholder.length -1]); } this.setSelection(range); // Make sure that a potential error doesn't cause our placeholder element to be left as a placeholder try { method(range.startContainer, range.endContainer); } catch(e) { setTimeout(function() { throw e; }, 0); } caretPlaceholder = this.contain.querySelectorAll("." + className); if (caretPlaceholder && caretPlaceholder.length) { newRange = rangy.createRange(this.doc); nextSibling = caretPlaceholder[0].nextSibling; if (caretPlaceholder.length > 1) { prevSibling = caretPlaceholder[caretPlaceholder.length -1].previousSibling; } if (prevSibling && nextSibling) { newRange.setStartBefore(nextSibling); newRange.setEndAfter(prevSibling); } else { newCaretPlaceholder = this.doc.createTextNode(wysihtml5.INVISIBLE_SPACE); dom.insert(newCaretPlaceholder).after(caretPlaceholder[0]); newRange.setStartBefore(newCaretPlaceholder); newRange.setEndAfter(newCaretPlaceholder); } this.setSelection(newRange); for (var i = caretPlaceholder.length; i--;) { caretPlaceholder[i].parentNode.removeChild(caretPlaceholder[i]); } } else { // fallback for when all hell breaks loose this.contain.focus(); } if (restoreScrollPosition) { body.scrollTop = oldScrollTop; body.scrollLeft = oldScrollLeft; } // Remove it again, just to make sure that the placeholder is definitely out of the dom tree try { caretPlaceholder.parentNode.removeChild(caretPlaceholder); } catch(e2) {} }, set: function(node, offset) { var newRange = rangy.createRange(this.doc); newRange.setStart(node, offset || 0); this.setSelection(newRange); }, /** * Insert html at the caret position and move the cursor after the inserted html * * @param {String} html HTML string to insert * @example * selection.insertHTML("<p>foobar</p>"); */ insertHTML: function(html) { var range = rangy.createRange(this.doc), node = this.doc.createElement('DIV'), fragment = this.doc.createDocumentFragment(), lastChild; node.innerHTML = html; lastChild = node.lastChild; while (node.firstChild) { fragment.appendChild(node.firstChild); } this.insertNode(fragment); if (lastChild) { this.setAfter(lastChild); } }, /** * Insert a node at the caret position and move the cursor behind it * * @param {Object} node HTML string to insert * @example * selection.insertNode(document.createTextNode("foobar")); */ insertNode: function(node) { var range = this.getRange(); if (range) { range.insertNode(node); } }, /** * Wraps current selection with the given node * * @param {Object} node The node to surround the selected elements with */ surround: function(nodeOptions) { var ranges = this.getOwnRanges(), node, nodes = []; if (ranges.length == 0) { return nodes; } for (var i = ranges.length; i--;) { node = this.doc.createElement(nodeOptions.nodeName); nodes.push(node); if (nodeOptions.className) { node.className = nodeOptions.className; } if (nodeOptions.cssStyle) { node.setAttribute('style', nodeOptions.cssStyle); } try { // This only works when the range boundaries are not overlapping other elements ranges[i].surroundContents(node); this.selectNode(node); } catch(e) { // fallback node.appendChild(ranges[i].extractContents()); ranges[i].insertNode(node); } } return nodes; }, deblockAndSurround: function(nodeOptions) { var tempElement = this.doc.createElement('div'), range = rangy.createRange(this.doc), tempDivElements, tempElements, firstChild; tempElement.className = nodeOptions.className; this.composer.commands.exec("formatBlock", nodeOptions.nodeName, nodeOptions.className); tempDivElements = this.contain.querySelectorAll("." + nodeOptions.className); if (tempDivElements[0]) { tempDivElements[0].parentNode.insertBefore(tempElement, tempDivElements[0]); range.setStartBefore(tempDivElements[0]); range.setEndAfter(tempDivElements[tempDivElements.length - 1]); tempElements = range.extractContents(); while (tempElements.firstChild) { firstChild = tempElements.firstChild; if (firstChild.nodeType == 1 && wysihtml5.dom.hasClass(firstChild, nodeOptions.className)) { while (firstChild.firstChild) { tempElement.appendChild(firstChild.firstChild); } if (firstChild.nodeName !== "BR") { tempElement.appendChild(this.doc.createElement('br')); } tempElements.removeChild(firstChild); } else { tempElement.appendChild(firstChild); } } } else { tempElement = null; } return tempElement; }, /** * Scroll the current caret position into the view * FIXME: This is a bit hacky, there might be a smarter way of doing this * * @example * selection.scrollIntoView(); */ scrollIntoView: function() { var doc = this.doc, tolerance = 5, // px hasScrollBars = doc.documentElement.scrollHeight > doc.documentElement.offsetHeight, tempElement = doc._wysihtml5ScrollIntoViewElement = doc._wysihtml5ScrollIntoViewElement || (function() { var element = doc.createElement("span"); // The element needs content in order to be able to calculate it's position properly element.innerHTML = wysihtml5.INVISIBLE_SPACE; return element; })(), offsetTop; if (hasScrollBars) { this.insertNode(tempElement); offsetTop = _getCumulativeOffsetTop(tempElement); tempElement.parentNode.removeChild(tempElement); if (offsetTop >= (doc.body.scrollTop + doc.documentElement.offsetHeight - tolerance)) { doc.body.scrollTop = offsetTop; } } }, /** * Select line where the caret is in */ selectLine: function() { if (wysihtml5.browser.supportsSelectionModify()) { this._selectLine_W3C(); } else if (this.doc.selection) { this._selectLine_MSIE(); } }, /** * See https://developer.mozilla.org/en/DOM/Selection/modify */ _selectLine_W3C: function() { var win = this.doc.defaultView, selection = win.getSelection(); selection.modify("move", "left", "lineboundary"); selection.modify("extend", "right", "lineboundary"); }, _selectLine_MSIE: function() { var range = this.doc.selection.createRange(), rangeTop = range.boundingTop, scrollWidth = this.doc.body.scrollWidth, rangeBottom, rangeEnd, measureNode, i, j; if (!range.moveToPoint) { return; } if (rangeTop === 0) { // Don't know why, but when the selection ends at the end of a line // range.boundingTop is 0 measureNode = this.doc.createElement("span"); this.insertNode(measureNode); rangeTop = measureNode.offsetTop; measureNode.parentNode.removeChild(measureNode); } rangeTop += 1; for (i=-10; i<scrollWidth; i+=2) { try { range.moveToPoint(i, rangeTop); break; } catch(e1) {} } // Investigate the following in order to handle multi line selections // rangeBottom = rangeTop + (rangeHeight ? (rangeHeight - 1) : 0); rangeBottom = rangeTop; rangeEnd = this.doc.selection.createRange(); for (j=scrollWidth; j>=0; j--) { try { rangeEnd.moveToPoint(j, rangeBottom); break; } catch(e2) {} } range.setEndPoint("EndToEnd", rangeEnd); range.select(); }, getText: function() { var selection = this.getSelection(); return selection ? selection.toString() : ""; }, getNodes: function(nodeType, filter) { var range = this.getRange(); if (range) { return range.getNodes([nodeType], filter); } else { return []; } }, fixRangeOverflow: function(range) { if (this.contain && this.contain.firstChild && range) { var containment = range.compareNode(this.contain); if (containment !== 2) { if (containment === 1) { range.setStartBefore(this.contain.firstChild); } if (containment === 0) { range.setEndAfter(this.contain.lastChild); } if (containment === 3) { range.setStartBefore(this.contain.firstChild); range.setEndAfter(this.contain.lastChild); } } else if (this._detectInlineRangeProblems(range)) { var previousElementSibling = range.endContainer.previousElementSibling; if (previousElementSibling) { range.setEnd(previousElementSibling, this._endOffsetForNode(previousElementSibling)); } } } }, _endOffsetForNode: function(node) { var range = document.createRange(); range.selectNodeContents(node); return range.endOffset; }, _detectInlineRangeProblems: function(range) { var position = dom.compareDocumentPosition(range.startContainer, range.endContainer); return ( range.endOffset == 0 && position & 4 //Node.DOCUMENT_POSITION_FOLLOWING ); }, getRange: function(dontFix) { var selection = this.getSelection(), range = selection && selection.rangeCount && selection.getRangeAt(0); if (dontFix !== true) { this.fixRangeOverflow(range); } return range; }, getOwnUneditables: function() { var allUneditables = dom.query(this.contain, '.' + this.unselectableClass), deepUneditables = dom.query(allUneditables, '.' + this.unselectableClass); return wysihtml5.lang.array(allUneditables).without(deepUneditables); }, // Returns an array of ranges that belong only to this editable // Needed as uneditable block in contenteditabel can split range into pieces // If manipulating content reverse loop is usually needed as manipulation can shift subsequent ranges getOwnRanges: function() { var ranges = [], r = this.getRange(), tmpRanges; if (r) { ranges.push(r); } if (this.unselectableClass && this.contain && r) { var uneditables = this.getOwnUneditables(), tmpRange; if (uneditables.length > 0) { for (var i = 0, imax = uneditables.length; i < imax; i++) { tmpRanges = []; for (var j = 0, jmax = ranges.length; j < jmax; j++) { if (ranges[j]) { switch (ranges[j].compareNode(uneditables[i])) { case 2: // all selection inside uneditable. remove break; case 3: //section begins before and ends after uneditable. spilt tmpRange = ranges[j].cloneRange(); tmpRange.setEndBefore(uneditables[i]); tmpRanges.push(tmpRange); tmpRange = ranges[j].cloneRange(); tmpRange.setStartAfter(uneditables[i]); tmpRanges.push(tmpRange); break; default: // in all other cases uneditable does not touch selection. dont modify tmpRanges.push(ranges[j]); } } ranges = tmpRanges; } } } } return ranges; }, getSelection: function() { return rangy.getSelection(this.doc.defaultView || this.doc.parentWindow); }, setSelection: function(range) { var win = this.doc.defaultView || this.doc.parentWindow, selection = rangy.getSelection(win); return selection.setSingleRange(range); }, createRange: function() { return rangy.createRange(this.doc); }, isCollapsed: function() { return this.getSelection().isCollapsed; }, getHtml: function() { return this.getSelection().toHtml(); }, isEndToEndInNode: function(nodeNames) { var range = this.getRange(), parentElement = range.commonAncestorContainer, startNode = range.startContainer, endNode = range.endContainer; if (parentElement.nodeType === wysihtml5.TEXT_NODE) { parentElement = parentElement.parentNode; } if (startNode.nodeType === wysihtml5.TEXT_NODE && !(/^\s*$/).test(startNode.data.substr(range.startOffset))) { return false; } if (endNode.nodeType === wysihtml5.TEXT_NODE && !(/^\s*$/).test(endNode.data.substr(range.endOffset))) { return false; } while (startNode && startNode !== parentElement) { if (startNode.nodeType !== wysihtml5.TEXT_NODE && !wysihtml5.dom.contains(parentElement, startNode)) { return false; } if (wysihtml5.dom.domNode(startNode).prev({ignoreBlankTexts: true})) { return false; } startNode = startNode.parentNode; } while (endNode && endNode !== parentElement) { if (endNode.nodeType !== wysihtml5.TEXT_NODE && !wysihtml5.dom.contains(parentElement, endNode)) { return false; } if (wysihtml5.dom.domNode(endNode).next({ignoreBlankTexts: true})) { return false; } endNode = endNode.parentNode; } return (wysihtml5.lang.array(nodeNames).contains(parentElement.nodeName)) ? parentElement : false; }, deselect: function() { var sel = this.getSelection(); sel && sel.removeAllRanges(); } }); })(wysihtml5); ;/** * Inspired by the rangy CSS Applier module written by Tim Down and licensed under the MIT license. * http://code.google.com/p/rangy/ * * changed in order to be able ... * - to use custom tags * - to detect and replace similar css classes via reg exp */ (function(wysihtml5, rangy) { var defaultTagName = "span"; var REG_EXP_WHITE_SPACE = /\s+/g; function hasClass(el, cssClass, regExp) { if (!el.className) { return false; } var matchingClassNames = el.className.match(regExp) || []; return matchingClassNames[matchingClassNames.length - 1] === cssClass; } function hasStyleAttr(el, regExp) { if (!el.getAttribute || !el.getAttribute('style')) { return false; } var matchingStyles = el.getAttribute('style').match(regExp); return (el.getAttribute('style').match(regExp)) ? true : false; } function addStyle(el, cssStyle, regExp) { if (el.getAttribute('style')) { removeStyle(el, regExp); if (el.getAttribute('style') && !(/^\s*$/).test(el.getAttribute('style'))) { el.setAttribute('style', cssStyle + ";" + el.getAttribute('style')); } else { el.setAttribute('style', cssStyle); } } else { el.setAttribute('style', cssStyle); } } function addClass(el, cssClass, regExp) { if (el.className) { removeClass(el, regExp); el.className += " " + cssClass; } else { el.className = cssClass; } } function removeClass(el, regExp) { if (el.className) { el.className = el.className.replace(regExp, ""); } } function removeStyle(el, regExp) { var s, s2 = []; if (el.getAttribute('style')) { s = el.getAttribute('style').split(';'); for (var i = s.length; i--;) { if (!s[i].match(regExp) && !(/^\s*$/).test(s[i])) { s2.push(s[i]); } } if (s2.length) { el.setAttribute('style', s2.join(';')); } else { el.removeAttribute('style'); } } } function getMatchingStyleRegexp(el, style) { var regexes = [], sSplit = style.split(';'), elStyle = el.getAttribute('style'); if (elStyle) { elStyle = elStyle.replace(/\s/gi, '').toLowerCase(); regexes.push(new RegExp("(^|\\s|;)" + style.replace(/\s/gi, '').replace(/([\(\)])/gi, "\\$1").toLowerCase().replace(";", ";?").replace(/rgb\\\((\d+),(\d+),(\d+)\\\)/gi, "\\s?rgb\\($1,\\s?$2,\\s?$3\\)"), "gi")); for (var i = sSplit.length; i-- > 0;) { if (!(/^\s*$/).test(sSplit[i])) { regexes.push(new RegExp("(^|\\s|;)" + sSplit[i].replace(/\s/gi, '').replace(/([\(\)])/gi, "\\$1").toLowerCase().replace(";", ";?").replace(/rgb\\\((\d+),(\d+),(\d+)\\\)/gi, "\\s?rgb\\($1,\\s?$2,\\s?$3\\)"), "gi")); } } for (var j = 0, jmax = regexes.length; j < jmax; j++) { if (elStyle.match(regexes[j])) { return regexes[j]; } } } return false; } function isMatchingAllready(node, tags, style, className) { if (style) { return getMatchingStyleRegexp(node, style); } else if (className) { return wysihtml5.dom.hasClass(node, className); } else { return rangy.dom.arrayContains(tags, node.tagName.toLowerCase()); } } function areMatchingAllready(nodes, tags, style, className) { for (var i = nodes.length; i--;) { if (!isMatchingAllready(nodes[i], tags, style, className)) { return false; } } return nodes.length ? true : false; } function removeOrChangeStyle(el, style, regExp) { var exactRegex = getMatchingStyleRegexp(el, style); if (exactRegex) { // adding same style value on property again removes style removeStyle(el, exactRegex); return "remove"; } else { // adding new style value changes value addStyle(el, style, regExp); return "change"; } } function hasSameClasses(el1, el2) { return el1.className.replace(REG_EXP_WHITE_SPACE, " ") == el2.className.replace(REG_EXP_WHITE_SPACE, " "); } function replaceWithOwnChildren(el) { var parent = el.parentNode; while (el.firstChild) { parent.insertBefore(el.firstChild, el); } parent.removeChild(el); } function elementsHaveSameNonClassAttributes(el1, el2) { if (el1.attributes.length != el2.attributes.length) { return false; } for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) { attr1 = el1.attributes[i]; name = attr1.name; if (name != "class") { attr2 = el2.attributes.getNamedItem(name); if (attr1.specified != attr2.specified) { return false; } if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) { return false; } } } return true; } function isSplitPoint(node, offset) { if (rangy.dom.isCharacterDataNode(node)) { if (offset == 0) { return !!node.previousSibling; } else if (offset == node.length) { return !!node.nextSibling; } else { return true; } } return offset > 0 && offset < node.childNodes.length; } function splitNodeAt(node, descendantNode, descendantOffset, container) { var newNode; if (rangy.dom.isCharacterDataNode(descendantNode)) { if (descendantOffset == 0) { descendantOffset = rangy.dom.getNodeIndex(descendantNode); descendantNode = descendantNode.parentNode; } else if (descendantOffset == descendantNode.length) { descendantOffset = rangy.dom.getNodeIndex(descendantNode) + 1; descendantNode = descendantNode.parentNode; } else { newNode = rangy.dom.splitDataNode(descendantNode, descendantOffset); } } if (!newNode) { if (!container || descendantNode !== container) { newNode = descendantNode.cloneNode(false); if (newNode.id) { newNode.removeAttribute("id"); } var child; while ((child = descendantNode.childNodes[descendantOffset])) { newNode.appendChild(child); } rangy.dom.insertAfter(newNode, descendantNode); } } return (descendantNode == node) ? newNode : splitNodeAt(node, newNode.parentNode, rangy.dom.getNodeIndex(newNode), container); } function Merge(firstNode) { this.isElementMerge = (firstNode.nodeType == wysihtml5.ELEMENT_NODE); this.firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode; this.textNodes = [this.firstTextNode]; } Merge.prototype = { doMerge: function() { var textBits = [], textNode, parent, text; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textNode = this.textNodes[i]; parent = textNode.parentNode; textBits[i] = textNode.data; if (i) { parent.removeChild(textNode); if (!parent.hasChildNodes()) { parent.parentNode.removeChild(parent); } } } this.firstTextNode.data = text = textBits.join(""); return text; }, getLength: function() { var i = this.textNodes.length, len = 0; while (i--) { len += this.textNodes[i].length; } return len; }, toString: function() { var textBits = []; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textBits[i] = "'" + this.textNodes[i].data + "'"; } return "[Merge(" + textBits.join(",") + ")]"; } }; function HTMLApplier(tagNames, cssClass, similarClassRegExp, normalize, cssStyle, similarStyleRegExp, container) { this.tagNames = tagNames || [defaultTagName]; this.cssClass = cssClass || ((cssClass === false) ? false : ""); this.similarClassRegExp = similarClassRegExp; this.cssStyle = cssStyle || ""; this.similarStyleRegExp = similarStyleRegExp; this.normalize = normalize; this.applyToAnyTagName = false; this.container = container; } HTMLApplier.prototype = { getAncestorWithClass: function(node) { var cssClassMatch; while (node) { cssClassMatch = this.cssClass ? hasClass(node, this.cssClass, this.similarClassRegExp) : (this.cssStyle !== "") ? false : true; if (node.nodeType == wysihtml5.ELEMENT_NODE && node.getAttribute("contenteditable") != "false" && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssClassMatch) { return node; } node = node.parentNode; } return false; }, // returns parents of node with given style attribute getAncestorWithStyle: function(node) { var cssStyleMatch; while (node) { cssStyleMatch = this.cssStyle ? hasStyleAttr(node, this.similarStyleRegExp) : false; if (node.nodeType == wysihtml5.ELEMENT_NODE && node.getAttribute("contenteditable") != "false" && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssStyleMatch) { return node; } node = node.parentNode; } return false; }, getMatchingAncestor: function(node) { var ancestor = this.getAncestorWithClass(node), matchType = false; if (!ancestor) { ancestor = this.getAncestorWithStyle(node); if (ancestor) { matchType = "style"; } } else { if (this.cssStyle) { matchType = "class"; } } return { "element": ancestor, "type": matchType }; }, // Normalizes nodes after applying a CSS class to a Range. postApply: function(textNodes, range) { var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1]; var merges = [], currentMerge; var rangeStartNode = firstNode, rangeEndNode = lastNode; var rangeStartOffset = 0, rangeEndOffset = lastNode.length; var textNode, precedingTextNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; precedingTextNode = null; if (textNode && textNode.parentNode) { precedingTextNode = this.getAdjacentMergeableTextNode(textNode.parentNode, false); } if (precedingTextNode) { if (!currentMerge) { currentMerge = new Merge(precedingTextNode); merges.push(currentMerge); } currentMerge.textNodes.push(textNode); if (textNode === firstNode) { rangeStartNode = currentMerge.firstTextNode; rangeStartOffset = rangeStartNode.length; } if (textNode === lastNode) { rangeEndNode = currentMerge.firstTextNode; rangeEndOffset = currentMerge.getLength(); } } else { currentMerge = null; } } // Test whether the first node after the range needs merging if(lastNode && lastNode.parentNode) { var nextTextNode = this.getAdjacentMergeableTextNode(lastNode.parentNode, true); if (nextTextNode) { if (!currentMerge) { currentMerge = new Merge(lastNode); merges.push(currentMerge); } currentMerge.textNodes.push(nextTextNode); } } // Do the merges if (merges.length) { for (i = 0, len = merges.length; i < len; ++i) { merges[i].doMerge(); } // Set the range boundaries range.setStart(rangeStartNode, rangeStartOffset); range.setEnd(rangeEndNode, rangeEndOffset); } }, getAdjacentMergeableTextNode: function(node, forward) { var isTextNode = (node.nodeType == wysihtml5.TEXT_NODE); var el = isTextNode ? node.parentNode : node; var adjacentNode; var propName = forward ? "nextSibling" : "previousSibling"; if (isTextNode) { // Can merge if the node's previous/next sibling is a text node adjacentNode = node[propName]; if (adjacentNode && adjacentNode.nodeType == wysihtml5.TEXT_NODE) { return adjacentNode; } } else { // Compare element with its sibling adjacentNode = el[propName]; if (adjacentNode && this.areElementsMergeable(node, adjacentNode)) { return adjacentNode[forward ? "firstChild" : "lastChild"]; } } return null; }, areElementsMergeable: function(el1, el2) { return rangy.dom.arrayContains(this.tagNames, (el1.tagName || "").toLowerCase()) && rangy.dom.arrayContains(this.tagNames, (el2.tagName || "").toLowerCase()) && hasSameClasses(el1, el2) && elementsHaveSameNonClassAttributes(el1, el2); }, createContainer: function(doc) { var el = doc.createElement(this.tagNames[0]); if (this.cssClass) { el.className = this.cssClass; } if (this.cssStyle) { el.setAttribute('style', this.cssStyle); } return el; }, applyToTextNode: function(textNode) { var parent = textNode.parentNode; if (parent.childNodes.length == 1 && rangy.dom.arrayContains(this.tagNames, parent.tagName.toLowerCase())) { if (this.cssClass) { addClass(parent, this.cssClass, this.similarClassRegExp); } if (this.cssStyle) { addStyle(parent, this.cssStyle, this.similarStyleRegExp); } } else { var el = this.createContainer(rangy.dom.getDocument(textNode)); textNode.parentNode.insertBefore(el, textNode); el.appendChild(textNode); } }, isRemovable: function(el) { return rangy.dom.arrayContains(this.tagNames, el.tagName.toLowerCase()) && wysihtml5.lang.string(el.className).trim() === "" && ( !el.getAttribute('style') || wysihtml5.lang.string(el.getAttribute('style')).trim() === "" ); }, undoToTextNode: function(textNode, range, ancestorWithClass, ancestorWithStyle) { var styleMode = (ancestorWithClass) ? false : true, ancestor = ancestorWithClass || ancestorWithStyle, styleChanged = false; if (!range.containsNode(ancestor)) { // Split out the portion of the ancestor from which we can remove the CSS class var ancestorRange = range.cloneRange(); ancestorRange.selectNode(ancestor); if (ancestorRange.isPointInRange(range.endContainer, range.endOffset) && isSplitPoint(range.endContainer, range.endOffset)) { splitNodeAt(ancestor, range.endContainer, range.endOffset, this.container); range.setEndAfter(ancestor); } if (ancestorRange.isPointInRange(range.startContainer, range.startOffset) && isSplitPoint(range.startContainer, range.startOffset)) { ancestor = splitNodeAt(ancestor, range.startContainer, range.startOffset, this.container); } } if (!styleMode && this.similarClassRegExp) { removeClass(ancestor, this.similarClassRegExp); } if (styleMode && this.similarStyleRegExp) { styleChanged = (removeOrChangeStyle(ancestor, this.cssStyle, this.similarStyleRegExp) === "change"); } if (this.isRemovable(ancestor) && !styleChanged) { replaceWithOwnChildren(ancestor); } }, applyToRange: function(range) { var textNodes; for (var ri = range.length; ri--;) { textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { try { var node = this.createContainer(range[ri].endContainer.ownerDocument); range[ri].surroundContents(node); this.selectNode(range[ri], node); return; } catch(e) {} } range[ri].splitBoundaries(); textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (textNodes.length) { var textNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; if (!this.getMatchingAncestor(textNode).element) { this.applyToTextNode(textNode); } } range[ri].setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range[ri].setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range[ri]); } } } }, undoToRange: function(range) { var textNodes, textNode, ancestorWithClass, ancestorWithStyle, ancestor; for (var ri = range.length; ri--;) { textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (textNodes.length) { range[ri].splitBoundaries(); textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); } else { var doc = range[ri].endContainer.ownerDocument, node = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); range[ri].insertNode(node); range[ri].selectNode(node); textNodes = [node]; } for (var i = 0, len = textNodes.length; i < len; ++i) { if (range[ri].isValid()) { textNode = textNodes[i]; ancestor = this.getMatchingAncestor(textNode); if (ancestor.type === "style") { this.undoToTextNode(textNode, range[ri], false, ancestor.element); } else if (ancestor.element) { this.undoToTextNode(textNode, range[ri], ancestor.element); } } } if (len == 1) { this.selectNode(range[ri], textNodes[0]); } else { range[ri].setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range[ri].setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range[ri]); } } } }, selectNode: function(range, node) { var isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : true, content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE); if (isEmpty && isElement && canHaveHTML) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } range.selectNodeContents(node); if (isEmpty && isElement) { range.collapse(false); } else if (isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } }, getTextSelectedByRange: function(textNode, range) { var textRange = range.cloneRange(); textRange.selectNodeContents(textNode); var intersectionRange = textRange.intersection(range); var text = intersectionRange ? intersectionRange.toString() : ""; textRange.detach(); return text; }, isAppliedToRange: function(range) { var ancestors = [], appliedType = "full", ancestor, styleAncestor, textNodes; for (var ri = range.length; ri--;) { textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { ancestor = this.getMatchingAncestor(range[ri].startContainer).element; return (ancestor) ? { "elements": [ancestor], "coverage": appliedType } : false; } for (var i = 0, len = textNodes.length, selectedText; i < len; ++i) { selectedText = this.getTextSelectedByRange(textNodes[i], range[ri]); ancestor = this.getMatchingAncestor(textNodes[i]).element; if (ancestor && selectedText != "") { ancestors.push(ancestor); if (wysihtml5.dom.getTextNodes(ancestor, true).length === 1) { appliedType = "full"; } else if (appliedType === "full") { appliedType = "inline"; } } else if (!ancestor) { appliedType = "partial"; } } } return (ancestors.length) ? { "elements": ancestors, "coverage": appliedType } : false; }, toggleRange: function(range) { var isApplied = this.isAppliedToRange(range), parentsExactMatch; if (isApplied) { if (isApplied.coverage === "full") { this.undoToRange(range); } else if (isApplied.coverage === "inline") { parentsExactMatch = areMatchingAllready(isApplied.elements, this.tagNames, this.cssStyle, this.cssClass); this.undoToRange(range); if (!parentsExactMatch) { this.applyToRange(range); } } else { // partial if (!areMatchingAllready(isApplied.elements, this.tagNames, this.cssStyle, this.cssClass)) { this.undoToRange(range); } this.applyToRange(range); } } else { this.applyToRange(range); } } }; wysihtml5.selection.HTMLApplier = HTMLApplier; })(wysihtml5, rangy); ;/** * Rich Text Query/Formatting Commands * * @example * var commands = new wysihtml5.Commands(editor); */ wysihtml5.Commands = Base.extend( /** @scope wysihtml5.Commands.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @example * commands.supports("createLink"); */ support: function(command) { return wysihtml5.browser.supportsCommand(this.doc, command); }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to execute (eg. "bold", "italic", "insertUnorderedList") * @param {String} [value] The command value parameter, needed for some commands ("createLink", "insertImage", ...), optional for commands that don't require one ("bold", "underline", ...) * @example * commands.exec("insertImage", "http://a1.twimg.com/profile_images/113868655/schrei_twitter_reasonably_small.jpg"); */ exec: function(command, value) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.exec, result = null; this.editor.fire("beforecommand:composer"); if (method) { args.unshift(this.composer); result = method.apply(obj, args); } else { try { // try/catch for buggy firefox result = this.doc.execCommand(command, false, value); } catch(e) {} } this.editor.fire("aftercommand:composer"); return result; }, /** * Check whether the current command is active * If the caret is within a bold text, then calling this with command "bold" should return true * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @param {String} [commandValue] The command value parameter (eg. for "insertImage" the image src) * @return {Boolean} Whether the command is active * @example * var isCurrentSelectionBold = commands.state("bold"); */ state: function(command, commandValue) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.state; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { try { // try/catch for buggy firefox return this.doc.queryCommandState(command); } catch(e) { return false; } } }, /* Get command state parsed value if command has stateValue parsing function */ stateValue: function(command) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.stateValue; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { return false; } } }); ;wysihtml5.commands.bold = { exec: function(composer, command) { wysihtml5.commands.formatInline.execWithToggle(composer, command, "b"); }, state: function(composer, command) { // element.ownerDocument.queryCommandState("bold") results: // firefox: only <b> // chrome: <b>, <strong>, <h1>, <h2>, ... // ie: <b>, <strong> // opera: <b>, <strong> return wysihtml5.commands.formatInline.state(composer, command, "b"); } }; ;(function(wysihtml5) { var undef, NODE_NAME = "A", dom = wysihtml5.dom; function _format(composer, attributes) { var doc = composer.doc, tempClass = "_wysihtml5-temp-" + (+new Date()), tempClassRegExp = /non-matching-class/g, i = 0, length, anchors, anchor, hasElementChild, isEmpty, elementToSetCaretAfter, textContent, whiteSpace, j; wysihtml5.commands.formatInline.exec(composer, undef, NODE_NAME, tempClass, tempClassRegExp, undef, undef, true, true); anchors = doc.querySelectorAll(NODE_NAME + "." + tempClass); length = anchors.length; for (; i<length; i++) { anchor = anchors[i]; anchor.removeAttribute("class"); for (j in attributes) { // Do not set attribute "text" as it is meant for setting string value if created link has no textual data if (j !== "text") { anchor.setAttribute(j, attributes[j]); } } } elementToSetCaretAfter = anchor; if (length === 1) { textContent = dom.getTextContent(anchor); hasElementChild = !!anchor.querySelector("*"); isEmpty = textContent === "" || textContent === wysihtml5.INVISIBLE_SPACE; if (!hasElementChild && isEmpty) { dom.setTextContent(anchor, attributes.text || anchor.href); whiteSpace = doc.createTextNode(" "); composer.selection.setAfter(anchor); dom.insert(whiteSpace).after(anchor); elementToSetCaretAfter = whiteSpace; } } composer.selection.setAfter(elementToSetCaretAfter); } // Changes attributes of links function _changeLinks(composer, anchors, attributes) { var oldAttrs; for (var a = anchors.length; a--;) { // Remove all old attributes oldAttrs = anchors[a].attributes; for (var oa = oldAttrs.length; oa--;) { anchors[a].removeAttribute(oldAttrs.item(oa).name); } // Set new attributes for (var j in attributes) { if (attributes.hasOwnProperty(j)) { anchors[a].setAttribute(j, attributes[j]); } } } } wysihtml5.commands.createLink = { /** * TODO: Use HTMLApplier or formatInline here * * Turns selection into a link * If selection is already a link, it just changes the attributes * * @example * // either ... * wysihtml5.commands.createLink.exec(composer, "createLink", "http://www.google.de"); * // ... or ... * wysihtml5.commands.createLink.exec(composer, "createLink", { href: "http://www.google.de", target: "_blank" }); */ exec: function(composer, command, value) { var anchors = this.state(composer, command); if (anchors) { // Selection contains links then change attributes of these links composer.selection.executeAndRestore(function() { _changeLinks(composer, anchors, value); }); } else { // Create links value = typeof(value) === "object" ? value : { href: value }; _format(composer, value); } }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "A"); } }; })(wysihtml5); ;(function(wysihtml5) { var dom = wysihtml5.dom; function _removeFormat(composer, anchors) { var length = anchors.length, i = 0, anchor, codeElement, textContent; for (; i<length; i++) { anchor = anchors[i]; codeElement = dom.getParentElement(anchor, { nodeName: "code" }); textContent = dom.getTextContent(anchor); // if <a> contains url-like text content, rename it to <code> to prevent re-autolinking // else replace <a> with its childNodes if (textContent.match(dom.autoLink.URL_REG_EXP) && !codeElement) { // <code> element is used to prevent later auto-linking of the content codeElement = dom.renameElement(anchor, "code"); } else { dom.replaceWithChildNodes(anchor); } } } wysihtml5.commands.removeLink = { /* * If selection is a link, it removes the link and wraps it with a <code> element * The <code> element is needed to avoid auto linking * * @example * wysihtml5.commands.createLink.exec(composer, "removeLink"); */ exec: function(composer, command) { var anchors = this.state(composer, command); if (anchors) { composer.selection.executeAndRestore(function() { _removeFormat(composer, anchors); }); } }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "A"); } }; })(wysihtml5); ;/** * document.execCommand("fontSize") will create either inline styles (firefox, chrome) or use font tags * which we don't want * Instead we set a css class */ (function(wysihtml5) { var REG_EXP = /wysiwyg-font-size-[0-9a-z\-]+/g; wysihtml5.commands.fontSize = { exec: function(composer, command, size) { wysihtml5.commands.formatInline.execWithToggle(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP); }, state: function(composer, command, size) { return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-font-size-" + size, REG_EXP); } }; })(wysihtml5); ;/* In case font size adjustment to any number defined by user is preferred, we cannot use classes and must use inline styles. */ (function(wysihtml5) { var REG_EXP = /(\s|^)font-size\s*:\s*[^;\s]+;?/gi; wysihtml5.commands.fontSizeStyle = { exec: function(composer, command, size) { size = (typeof(size) == "object") ? size.size : size; if (!(/^\s*$/).test(size)) { wysihtml5.commands.formatInline.execWithToggle(composer, command, "span", false, false, "font-size:" + size, REG_EXP); } }, state: function(composer, command, size) { return wysihtml5.commands.formatInline.state(composer, command, "span", false, false, "font-size", REG_EXP); }, stateValue: function(composer, command) { var st = this.state(composer, command), styleStr, fontsizeMatches, val = false; if (st && wysihtml5.lang.object(st).isArray()) { st = st[0]; } if (st) { styleStr = st.getAttribute('style'); if (styleStr) { return wysihtml5.quirks.styleParser.parseFontSize(styleStr); } } return false; } }; })(wysihtml5); ;/** * document.execCommand("foreColor") will create either inline styles (firefox, chrome) or use font tags * which we don't want * Instead we set a css class */ (function(wysihtml5) { var REG_EXP = /wysiwyg-color-[0-9a-z]+/g; wysihtml5.commands.foreColor = { exec: function(composer, command, color) { wysihtml5.commands.formatInline.execWithToggle(composer, command, "span", "wysiwyg-color-" + color, REG_EXP); }, state: function(composer, command, color) { return wysihtml5.commands.formatInline.state(composer, command, "span", "wysiwyg-color-" + color, REG_EXP); } }; })(wysihtml5); ;/** * document.execCommand("foreColor") will create either inline styles (firefox, chrome) or use font tags * which we don't want * Instead we set a css class */ (function(wysihtml5) { var REG_EXP = /(\s|^)color\s*:\s*[^;\s]+;?/gi; wysihtml5.commands.foreColorStyle = { exec: function(composer, command, color) { var colorVals = wysihtml5.quirks.styleParser.parseColor((typeof(color) == "object") ? "color:" + color.color : "color:" + color, "color"), colString; if (colorVals) { colString = "color: rgb(" + colorVals[0] + ',' + colorVals[1] + ',' + colorVals[2] + ');'; if (colorVals[3] !== 1) { colString += "color: rgba(" + colorVals[0] + ',' + colorVals[1] + ',' + colorVals[2] + ',' + colorVals[3] + ');'; } wysihtml5.commands.formatInline.execWithToggle(composer, command, "span", false, false, colString, REG_EXP); } }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "span", false, false, "color", REG_EXP); }, stateValue: function(composer, command, props) { var st = this.state(composer, command), colorStr; if (st && wysihtml5.lang.object(st).isArray()) { st = st[0]; } if (st) { colorStr = st.getAttribute('style'); if (colorStr) { if (colorStr) { val = wysihtml5.quirks.styleParser.parseColor(colorStr, "color"); return wysihtml5.quirks.styleParser.unparseColor(val, props); } } } return false; } }; })(wysihtml5); ;/* In case background adjustment to any color defined by user is preferred, we cannot use classes and must use inline styles. */ (function(wysihtml5) { var REG_EXP = /(\s|^)background-color\s*:\s*[^;\s]+;?/gi; wysihtml5.commands.bgColorStyle = { exec: function(composer, command, color) { var colorVals = wysihtml5.quirks.styleParser.parseColor((typeof(color) == "object") ? "background-color:" + color.color : "background-color:" + color, "background-color"), colString; if (colorVals) { colString = "background-color: rgb(" + colorVals[0] + ',' + colorVals[1] + ',' + colorVals[2] + ');'; if (colorVals[3] !== 1) { colString += "background-color: rgba(" + colorVals[0] + ',' + colorVals[1] + ',' + colorVals[2] + ',' + colorVals[3] + ');'; } wysihtml5.commands.formatInline.execWithToggle(composer, command, "span", false, false, colString, REG_EXP); } }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "span", false, false, "background-color", REG_EXP); }, stateValue: function(composer, command, props) { var st = this.state(composer, command), colorStr, val = false; if (st && wysihtml5.lang.object(st).isArray()) { st = st[0]; } if (st) { colorStr = st.getAttribute('style'); if (colorStr) { val = wysihtml5.quirks.styleParser.parseColor(colorStr, "background-color"); return wysihtml5.quirks.styleParser.unparseColor(val, props); } } return false; } }; })(wysihtml5); ;(function(wysihtml5) { var dom = wysihtml5.dom, // Following elements are grouped // when the caret is within a H1 and the H4 is invoked, the H1 should turn into H4 // instead of creating a H4 within a H1 which would result in semantically invalid html BLOCK_ELEMENTS_GROUP = ["H1", "H2", "H3", "H4", "H5", "H6", "P", "PRE", "DIV"]; /** * Remove similiar classes (based on classRegExp) * and add the desired class name */ function _addClass(element, className, classRegExp) { if (element.className) { _removeClass(element, classRegExp); element.className = wysihtml5.lang.string(element.className + " " + className).trim(); } else { element.className = className; } } function _addStyle(element, cssStyle, styleRegExp) { _removeStyle(element, styleRegExp); if (element.getAttribute('style')) { element.setAttribute('style', wysihtml5.lang.string(element.getAttribute('style') + " " + cssStyle).trim()); } else { element.setAttribute('style', cssStyle); } } function _removeClass(element, classRegExp) { var ret = classRegExp.test(element.className); element.className = element.className.replace(classRegExp, ""); if (wysihtml5.lang.string(element.className).trim() == '') { element.removeAttribute('class'); } return ret; } function _removeStyle(element, styleRegExp) { var ret = styleRegExp.test(element.getAttribute('style')); element.setAttribute('style', (element.getAttribute('style') || "").replace(styleRegExp, "")); if (wysihtml5.lang.string(element.getAttribute('style') || "").trim() == '') { element.removeAttribute('style'); } return ret; } function _removeLastChildIfLineBreak(node) { var lastChild = node.lastChild; if (lastChild && _isLineBreak(lastChild)) { lastChild.parentNode.removeChild(lastChild); } } function _isLineBreak(node) { return node.nodeName === "BR"; } /** * Execute native query command * and if necessary modify the inserted node's className */ function _execCommand(doc, composer, command, nodeName, className) { var ranges = composer.selection.getOwnRanges(); for (var i = ranges.length; i--;){ composer.selection.getSelection().removeAllRanges(); composer.selection.setSelection(ranges[i]); if (className) { var eventListener = dom.observe(doc, "DOMNodeInserted", function(event) { var target = event.target, displayStyle; if (target.nodeType !== wysihtml5.ELEMENT_NODE) { return; } displayStyle = dom.getStyle("display").from(target); if (displayStyle.substr(0, 6) !== "inline") { // Make sure that only block elements receive the given class target.className += " " + className; } }); } doc.execCommand(command, false, nodeName); if (eventListener) { eventListener.stop(); } } } function _selectionWrap(composer, options) { if (composer.selection.isCollapsed()) { composer.selection.selectLine(); } var surroundedNodes = composer.selection.surround(options); for (var i = 0, imax = surroundedNodes.length; i < imax; i++) { wysihtml5.dom.lineBreaks(surroundedNodes[i]).remove(); _removeLastChildIfLineBreak(surroundedNodes[i]); } // rethink restoring selection // composer.selection.selectNode(element, wysihtml5.browser.displaysCaretInEmptyContentEditableCorrectly()); } function _hasClasses(element) { return !!wysihtml5.lang.string(element.className).trim(); } function _hasStyles(element) { return !!wysihtml5.lang.string(element.getAttribute('style') || '').trim(); } wysihtml5.commands.formatBlock = { exec: function(composer, command, nodeName, className, classRegExp, cssStyle, styleRegExp) { var doc = composer.doc, blockElements = this.state(composer, command, nodeName, className, classRegExp, cssStyle, styleRegExp), useLineBreaks = composer.config.useLineBreaks, defaultNodeName = useLineBreaks ? "DIV" : "P", selectedNodes, classRemoveAction, blockRenameFound, styleRemoveAction, blockElement; nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName; if (blockElements.length) { composer.selection.executeAndRestoreRangy(function() { for (var b = blockElements.length; b--;) { if (classRegExp) { classRemoveAction = _removeClass(blockElements[b], classRegExp); } if (styleRegExp) { styleRemoveAction = _removeStyle(blockElements[b], styleRegExp); } if ((styleRemoveAction || classRemoveAction) && nodeName === null && blockElements[b].nodeName != defaultNodeName) { // dont rename or remove element when just setting block formating class or style return; } var hasClasses = _hasClasses(blockElements[b]), hasStyles = _hasStyles(blockElements[b]); if (!hasClasses && !hasStyles && (useLineBreaks || nodeName === "P")) { // Insert a line break afterwards and beforewards when there are siblings // that are not of type line break or block element wysihtml5.dom.lineBreaks(blockElements[b]).add(); dom.replaceWithChildNodes(blockElements[b]); } else { // Make sure that styling is kept by renaming the element to a <div> or <p> and copying over the class name dom.renameElement(blockElements[b], nodeName === "P" ? "DIV" : defaultNodeName); } } }); return; } // Find similiar block element and rename it (<h2 class="foo"></h2> => <h1 class="foo"></h1>) if (nodeName === null || wysihtml5.lang.array(BLOCK_ELEMENTS_GROUP).contains(nodeName)) { selectedNodes = composer.selection.findNodesInSelection(BLOCK_ELEMENTS_GROUP).concat(composer.selection.getSelectedOwnNodes()); composer.selection.executeAndRestoreRangy(function() { for (var n = selectedNodes.length; n--;) { blockElement = dom.getParentElement(selectedNodes[n], { nodeName: BLOCK_ELEMENTS_GROUP }); if (blockElement == composer.element) { blockElement = null; } if (blockElement) { // Rename current block element to new block element and add class if (nodeName) { blockElement = dom.renameElement(blockElement, nodeName); } if (className) { _addClass(blockElement, className, classRegExp); } if (cssStyle) { _addStyle(blockElement, cssStyle, styleRegExp); } blockRenameFound = true; } } }); if (blockRenameFound) { return; } } _selectionWrap(composer, { "nodeName": (nodeName || defaultNodeName), "className": className || null, "cssStyle": cssStyle || null }); }, state: function(composer, command, nodeName, className, classRegExp, cssStyle, styleRegExp) { var nodes = composer.selection.getSelectedOwnNodes(), parents = [], parent; nodeName = typeof(nodeName) === "string" ? nodeName.toUpperCase() : nodeName; //var selectedNode = composer.selection.getSelectedNode(); for (var i = 0, maxi = nodes.length; i < maxi; i++) { parent = dom.getParentElement(nodes[i], { nodeName: nodeName, className: className, classRegExp: classRegExp, cssStyle: cssStyle, styleRegExp: styleRegExp }); if (parent && wysihtml5.lang.array(parents).indexOf(parent) == -1) { parents.push(parent); } } if (parents.length == 0) { return false; } return parents; } }; })(wysihtml5); ;/* Formats block for as a <pre><code class="classname"></code></pre> block * Useful in conjuction for sytax highlight utility: highlight.js * * Usage: * * editorInstance.composer.commands.exec("formatCode", "language-html"); */ wysihtml5.commands.formatCode = { exec: function(composer, command, classname) { var pre = this.state(composer), code, range, selectedNodes; if (pre) { // caret is already within a <pre><code>...</code></pre> composer.selection.executeAndRestore(function() { code = pre.querySelector("code"); wysihtml5.dom.replaceWithChildNodes(pre); if (code) { wysihtml5.dom.replaceWithChildNodes(code); } }); } else { // Wrap in <pre><code>...</code></pre> range = composer.selection.getRange(); selectedNodes = range.extractContents(); pre = composer.doc.createElement("pre"); code = composer.doc.createElement("code"); if (classname) { code.className = classname; } pre.appendChild(code); code.appendChild(selectedNodes); range.insertNode(pre); composer.selection.selectNode(pre); } }, state: function(composer) { var selectedNode = composer.selection.getSelectedNode(); if (selectedNode && selectedNode.nodeName && selectedNode.nodeName == "PRE"&& selectedNode.firstChild && selectedNode.firstChild.nodeName && selectedNode.firstChild.nodeName == "CODE") { return selectedNode; } else { return wysihtml5.dom.getParentElement(selectedNode, { nodeName: "CODE" }) && wysihtml5.dom.getParentElement(selectedNode, { nodeName: "PRE" }); } } };;/** * formatInline scenarios for tag "B" (| = caret, |foo| = selected text) * * #1 caret in unformatted text: * abcdefg| * output: * abcdefg<b>|</b> * * #2 unformatted text selected: * abc|deg|h * output: * abc<b>|deg|</b>h * * #3 unformatted text selected across boundaries: * ab|c <span>defg|h</span> * output: * ab<b>|c </b><span><b>defg</b>|h</span> * * #4 formatted text entirely selected * <b>|abc|</b> * output: * |abc| * * #5 formatted text partially selected * <b>ab|c|</b> * output: * <b>ab</b>|c| * * #6 formatted text selected across boundaries * <span>ab|c</span> <b>de|fgh</b> * output: * <span>ab|c</span> de|<b>fgh</b> */ (function(wysihtml5) { var // Treat <b> as <strong> and vice versa ALIAS_MAPPING = { "strong": "b", "em": "i", "b": "strong", "i": "em" }, htmlApplier = {}; function _getTagNames(tagName) { var alias = ALIAS_MAPPING[tagName]; return alias ? [tagName.toLowerCase(), alias.toLowerCase()] : [tagName.toLowerCase()]; } function _getApplier(tagName, className, classRegExp, cssStyle, styleRegExp, container) { var identifier = tagName; if (className) { identifier += ":" + className; } if (cssStyle) { identifier += ":" + cssStyle; } if (!htmlApplier[identifier]) { htmlApplier[identifier] = new wysihtml5.selection.HTMLApplier(_getTagNames(tagName), className, classRegExp, true, cssStyle, styleRegExp, container); } return htmlApplier[identifier]; } wysihtml5.commands.formatInline = { exec: function(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp, dontRestoreSelect, noCleanup) { var range = composer.selection.createRange(), ownRanges = composer.selection.getOwnRanges(); if (!ownRanges || ownRanges.length == 0) { return false; } composer.selection.getSelection().removeAllRanges(); _getApplier(tagName, className, classRegExp, cssStyle, styleRegExp, composer.element).toggleRange(ownRanges); if (!dontRestoreSelect) { range.setStart(ownRanges[0].startContainer, ownRanges[0].startOffset); range.setEnd( ownRanges[ownRanges.length - 1].endContainer, ownRanges[ownRanges.length - 1].endOffset ); composer.selection.setSelection(range); composer.selection.executeAndRestore(function() { if (!noCleanup) { composer.cleanUp(); } }, true, true); } else if (!noCleanup) { composer.cleanUp(); } }, // Executes so that if collapsed caret is in a state and executing that state it should unformat that state // It is achieved by selecting the entire state element before executing. // This works on built in contenteditable inline format commands execWithToggle: function(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) { var that = this; if (this.state(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) && composer.selection.isCollapsed() && !composer.selection.caretIsLastInSelection() && !composer.selection.caretIsFirstInSelection() ) { var state_element = that.state(composer, command, tagName, className, classRegExp)[0]; composer.selection.executeAndRestoreRangy(function() { var parent = state_element.parentNode; composer.selection.selectNode(state_element, true); wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp, true, true); }); } else { if (this.state(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) && !composer.selection.isCollapsed()) { composer.selection.executeAndRestoreRangy(function() { wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp, true, true); }); } else { wysihtml5.commands.formatInline.exec(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp); } } }, state: function(composer, command, tagName, className, classRegExp, cssStyle, styleRegExp) { var doc = composer.doc, aliasTagName = ALIAS_MAPPING[tagName] || tagName, ownRanges, isApplied; // Check whether the document contains a node with the desired tagName if (!wysihtml5.dom.hasElementWithTagName(doc, tagName) && !wysihtml5.dom.hasElementWithTagName(doc, aliasTagName)) { return false; } // Check whether the document contains a node with the desired className if (className && !wysihtml5.dom.hasElementWithClassName(doc, className)) { return false; } ownRanges = composer.selection.getOwnRanges(); if (!ownRanges || ownRanges.length === 0) { return false; } isApplied = _getApplier(tagName, className, classRegExp, cssStyle, styleRegExp, composer.element).isAppliedToRange(ownRanges); return (isApplied && isApplied.elements) ? isApplied.elements : false; } }; })(wysihtml5); ;(function(wysihtml5) { wysihtml5.commands.insertBlockQuote = { exec: function(composer, command) { var state = this.state(composer, command), endToEndParent = composer.selection.isEndToEndInNode(['H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'P']), prevNode, nextNode; composer.selection.executeAndRestore(function() { if (state) { if (composer.config.useLineBreaks) { wysihtml5.dom.lineBreaks(state).add(); } wysihtml5.dom.unwrap(state); } else { if (composer.selection.isCollapsed()) { composer.selection.selectLine(); } if (endToEndParent) { var qouteEl = endToEndParent.ownerDocument.createElement('blockquote'); wysihtml5.dom.insert(qouteEl).after(endToEndParent); qouteEl.appendChild(endToEndParent); } else { composer.selection.surround({nodeName: "blockquote"}); } } }); }, state: function(composer, command) { var selectedNode = composer.selection.getSelectedNode(), node = wysihtml5.dom.getParentElement(selectedNode, { nodeName: "BLOCKQUOTE" }, false, composer.element); return (node) ? node : false; } }; })(wysihtml5);;wysihtml5.commands.insertHTML = { exec: function(composer, command, html) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, html); } else { composer.selection.insertHTML(html); } }, state: function() { return false; } }; ;(function(wysihtml5) { var NODE_NAME = "IMG"; wysihtml5.commands.insertImage = { /** * Inserts an <img> * If selection is already an image link, it removes it * * @example * // either ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", "http://www.google.de/logo.jpg"); * // ... or ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", { src: "http://www.google.de/logo.jpg", title: "foo" }); */ exec: function(composer, command, value) { value = typeof(value) === "object" ? value : { src: value }; var doc = composer.doc, image = this.state(composer), textNode, parent; if (image) { // Image already selected, set the caret before it and delete it composer.selection.setBefore(image); parent = image.parentNode; parent.removeChild(image); // and it's parent <a> too if it hasn't got any other relevant child nodes wysihtml5.dom.removeEmptyTextNodes(parent); if (parent.nodeName === "A" && !parent.firstChild) { composer.selection.setAfter(parent); parent.parentNode.removeChild(parent); } // firefox and ie sometimes don't remove the image handles, even though the image got removed wysihtml5.quirks.redraw(composer.element); return; } image = doc.createElement(NODE_NAME); for (var i in value) { image.setAttribute(i === "className" ? "class" : i, value[i]); } composer.selection.insertNode(image); if (wysihtml5.browser.hasProblemsSettingCaretAfterImg()) { textNode = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); composer.selection.insertNode(textNode); composer.selection.setAfter(textNode); } else { composer.selection.setAfter(image); } }, state: function(composer) { var doc = composer.doc, selectedNode, text, imagesInSelection; if (!wysihtml5.dom.hasElementWithTagName(doc, NODE_NAME)) { return false; } selectedNode = composer.selection.getSelectedNode(); if (!selectedNode) { return false; } if (selectedNode.nodeName === NODE_NAME) { // This works perfectly in IE return selectedNode; } if (selectedNode.nodeType !== wysihtml5.ELEMENT_NODE) { return false; } text = composer.selection.getText(); text = wysihtml5.lang.string(text).trim(); if (text) { return false; } imagesInSelection = composer.selection.getNodes(wysihtml5.ELEMENT_NODE, function(node) { return node.nodeName === "IMG"; }); if (imagesInSelection.length !== 1) { return false; } return imagesInSelection[0]; } }; })(wysihtml5); ;(function(wysihtml5) { var LINE_BREAK = "<br>" + (wysihtml5.browser.needsSpaceAfterLineBreak() ? " " : ""); wysihtml5.commands.insertLineBreak = { exec: function(composer, command) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, null); if (!wysihtml5.browser.autoScrollsToCaret()) { composer.selection.scrollIntoView(); } } else { composer.commands.exec("insertHTML", LINE_BREAK); } }, state: function() { return false; } }; })(wysihtml5); ;wysihtml5.commands.insertOrderedList = { exec: function(composer, command) { wysihtml5.commands.insertList.exec(composer, command, "OL"); }, state: function(composer, command) { return wysihtml5.commands.insertList.state(composer, command, "OL"); } }; ;wysihtml5.commands.insertUnorderedList = { exec: function(composer, command) { wysihtml5.commands.insertList.exec(composer, command, "UL"); }, state: function(composer, command) { return wysihtml5.commands.insertList.state(composer, command, "UL"); } }; ;wysihtml5.commands.insertList = (function(wysihtml5) { var isNode = function(node, name) { if (node && node.nodeName) { if (typeof name === 'string') { name = [name]; } for (var n = name.length; n--;) { if (node.nodeName === name[n]) { return true; } } } return false; }; var findListEl = function(node, nodeName, composer) { var ret = { el: null, other: false }; if (node) { var parentLi = wysihtml5.dom.getParentElement(node, { nodeName: "LI" }), otherNodeName = (nodeName === "UL") ? "OL" : "UL"; if (isNode(node, nodeName)) { ret.el = node; } else if (isNode(node, otherNodeName)) { ret = { el: node, other: true }; } else if (parentLi) { if (isNode(parentLi.parentNode, nodeName)) { ret.el = parentLi.parentNode; } else if (isNode(parentLi.parentNode, otherNodeName)) { ret = { el : parentLi.parentNode, other: true }; } } } // do not count list elements outside of composer if (ret.el && !composer.element.contains(ret.el)) { ret.el = null; } return ret; }; var handleSameTypeList = function(el, nodeName, composer) { var otherNodeName = (nodeName === "UL") ? "OL" : "UL", otherLists, innerLists; // Unwrap list // <ul><li>foo</li><li>bar</li></ul> // becomes: // foo<br>bar<br> composer.selection.executeAndRestore(function() { var otherLists = getListsInSelection(otherNodeName, composer); if (otherLists.length) { for (var l = otherLists.length; l--;) { wysihtml5.dom.renameElement(otherLists[l], nodeName.toLowerCase()); } } else { innerLists = getListsInSelection(['OL', 'UL'], composer); for (var i = innerLists.length; i--;) { wysihtml5.dom.resolveList(innerLists[i], composer.config.useLineBreaks); } wysihtml5.dom.resolveList(el, composer.config.useLineBreaks); } }); }; var handleOtherTypeList = function(el, nodeName, composer) { var otherNodeName = (nodeName === "UL") ? "OL" : "UL"; // Turn an ordered list into an unordered list // <ol><li>foo</li><li>bar</li></ol> // becomes: // <ul><li>foo</li><li>bar</li></ul> // Also rename other lists in selection composer.selection.executeAndRestore(function() { var renameLists = [el].concat(getListsInSelection(otherNodeName, composer)); // All selection inner lists get renamed too for (var l = renameLists.length; l--;) { wysihtml5.dom.renameElement(renameLists[l], nodeName.toLowerCase()); } }); }; var getListsInSelection = function(nodeName, composer) { var ranges = composer.selection.getOwnRanges(), renameLists = []; for (var r = ranges.length; r--;) { renameLists = renameLists.concat(ranges[r].getNodes([1], function(node) { return isNode(node, nodeName); })); } return renameLists; }; var createListFallback = function(nodeName, composer) { // Fallback for Create list composer.selection.executeAndRestoreRangy(function() { var tempClassName = "_wysihtml5-temp-" + new Date().getTime(), tempElement = composer.selection.deblockAndSurround({ "nodeName": "div", "className": tempClassName }), isEmpty, list; // This space causes new lists to never break on enter var INVISIBLE_SPACE_REG_EXP = /\uFEFF/g; tempElement.innerHTML = tempElement.innerHTML.replace(INVISIBLE_SPACE_REG_EXP, ""); if (tempElement) { isEmpty = wysihtml5.lang.array(["", "<br>", wysihtml5.INVISIBLE_SPACE]).contains(tempElement.innerHTML); list = wysihtml5.dom.convertToList(tempElement, nodeName.toLowerCase(), composer.parent.config.uneditableContainerClassname); if (isEmpty) { composer.selection.selectNode(list.querySelector("li"), true); } } }); }; return { exec: function(composer, command, nodeName) { var doc = composer.doc, cmd = (nodeName === "OL") ? "insertOrderedList" : "insertUnorderedList", selectedNode = composer.selection.getSelectedNode(), list = findListEl(selectedNode, nodeName, composer); if (!list.el) { if (composer.commands.support(cmd)) { doc.execCommand(cmd, false, null); } else { createListFallback(nodeName, composer); } } else if (list.other) { handleOtherTypeList(list.el, nodeName, composer); } else { handleSameTypeList(list.el, nodeName, composer); } }, state: function(composer, command, nodeName) { var selectedNode = composer.selection.getSelectedNode(), list = findListEl(selectedNode, nodeName, composer); return (list.el && !list.other) ? list.el : false; } }; })(wysihtml5);;wysihtml5.commands.italic = { exec: function(composer, command) { wysihtml5.commands.formatInline.execWithToggle(composer, command, "i"); }, state: function(composer, command) { // element.ownerDocument.queryCommandState("italic") results: // firefox: only <i> // chrome: <i>, <em>, <blockquote>, ... // ie: <i>, <em> // opera: only <i> return wysihtml5.commands.formatInline.state(composer, command, "i"); } }; ;(function(wysihtml5) { var CLASS_NAME = "wysiwyg-text-align-center", REG_EXP = /wysiwyg-text-align-[0-9a-z]+/g; wysihtml5.commands.justifyCenter = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); } }; })(wysihtml5); ;(function(wysihtml5) { var CLASS_NAME = "wysiwyg-text-align-left", REG_EXP = /wysiwyg-text-align-[0-9a-z]+/g; wysihtml5.commands.justifyLeft = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); } }; })(wysihtml5); ;(function(wysihtml5) { var CLASS_NAME = "wysiwyg-text-align-right", REG_EXP = /wysiwyg-text-align-[0-9a-z]+/g; wysihtml5.commands.justifyRight = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); } }; })(wysihtml5); ;(function(wysihtml5) { var CLASS_NAME = "wysiwyg-text-align-justify", REG_EXP = /wysiwyg-text-align-[0-9a-z]+/g; wysihtml5.commands.justifyFull = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, CLASS_NAME, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, CLASS_NAME, REG_EXP); } }; })(wysihtml5); ;(function(wysihtml5) { var STYLE_STR = "text-align: right;", REG_EXP = /(\s|^)text-align\s*:\s*[^;\s]+;?/gi; wysihtml5.commands.alignRightStyle = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP); } }; })(wysihtml5); ;(function(wysihtml5) { var STYLE_STR = "text-align: left;", REG_EXP = /(\s|^)text-align\s*:\s*[^;\s]+;?/gi; wysihtml5.commands.alignLeftStyle = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP); } }; })(wysihtml5); ;(function(wysihtml5) { var STYLE_STR = "text-align: center;", REG_EXP = /(\s|^)text-align\s*:\s*[^;\s]+;?/gi; wysihtml5.commands.alignCenterStyle = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", null, null, null, STYLE_STR, REG_EXP); } }; })(wysihtml5); ;wysihtml5.commands.redo = { exec: function(composer) { return composer.undoManager.redo(); }, state: function(composer) { return false; } }; ;wysihtml5.commands.underline = { exec: function(composer, command) { wysihtml5.commands.formatInline.execWithToggle(composer, command, "u"); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "u"); } }; ;wysihtml5.commands.undo = { exec: function(composer) { return composer.undoManager.undo(); }, state: function(composer) { return false; } }; ;wysihtml5.commands.createTable = { exec: function(composer, command, value) { var col, row, html; if (value && value.cols && value.rows && parseInt(value.cols, 10) > 0 && parseInt(value.rows, 10) > 0) { if (value.tableStyle) { html = "<table style=\"" + value.tableStyle + "\">"; } else { html = "<table>"; } html += "<tbody>"; for (row = 0; row < value.rows; row ++) { html += '<tr>'; for (col = 0; col < value.cols; col ++) { html += "<td>&nbsp;</td>"; } html += '</tr>'; } html += "</tbody></table>"; composer.commands.exec("insertHTML", html); //composer.selection.insertHTML(html); } }, state: function(composer, command) { return false; } }; ;wysihtml5.commands.mergeTableCells = { exec: function(composer, command) { if (composer.tableSelection && composer.tableSelection.start && composer.tableSelection.end) { if (this.state(composer, command)) { wysihtml5.dom.table.unmergeCell(composer.tableSelection.start); } else { wysihtml5.dom.table.mergeCellsBetween(composer.tableSelection.start, composer.tableSelection.end); } } }, state: function(composer, command) { if (composer.tableSelection) { var start = composer.tableSelection.start, end = composer.tableSelection.end; if (start && end && start == end && (( wysihtml5.dom.getAttribute(start, "colspan") && parseInt(wysihtml5.dom.getAttribute(start, "colspan"), 10) > 1 ) || ( wysihtml5.dom.getAttribute(start, "rowspan") && parseInt(wysihtml5.dom.getAttribute(start, "rowspan"), 10) > 1 )) ) { return [start]; } } return false; } }; ;wysihtml5.commands.addTableCells = { exec: function(composer, command, value) { if (composer.tableSelection && composer.tableSelection.start && composer.tableSelection.end) { // switches start and end if start is bigger than end (reverse selection) var tableSelect = wysihtml5.dom.table.orderSelectionEnds(composer.tableSelection.start, composer.tableSelection.end); if (value == "before" || value == "above") { wysihtml5.dom.table.addCells(tableSelect.start, value); } else if (value == "after" || value == "below") { wysihtml5.dom.table.addCells(tableSelect.end, value); } setTimeout(function() { composer.tableSelection.select(tableSelect.start, tableSelect.end); },0); } }, state: function(composer, command) { return false; } }; ;wysihtml5.commands.deleteTableCells = { exec: function(composer, command, value) { if (composer.tableSelection && composer.tableSelection.start && composer.tableSelection.end) { var tableSelect = wysihtml5.dom.table.orderSelectionEnds(composer.tableSelection.start, composer.tableSelection.end), idx = wysihtml5.dom.table.indexOf(tableSelect.start), selCell, table = composer.tableSelection.table; wysihtml5.dom.table.removeCells(tableSelect.start, value); setTimeout(function() { // move selection to next or previous if not present selCell = wysihtml5.dom.table.findCell(table, idx); if (!selCell){ if (value == "row") { selCell = wysihtml5.dom.table.findCell(table, { "row": idx.row - 1, "col": idx.col }); } if (value == "column") { selCell = wysihtml5.dom.table.findCell(table, { "row": idx.row, "col": idx.col - 1 }); } } if (selCell) { composer.tableSelection.select(selCell, selCell); } }, 0); } }, state: function(composer, command) { return false; } }; ;wysihtml5.commands.indentList = { exec: function(composer, command, value) { var listEls = composer.selection.getSelectionParentsByTag('LI'); if (listEls) { return this.tryToPushLiLevel(listEls, composer.selection); } return false; }, state: function(composer, command) { return false; }, tryToPushLiLevel: function(liNodes, selection) { var listTag, list, prevLi, liNode, prevLiList, found = false; selection.executeAndRestoreRangy(function() { for (var i = liNodes.length; i--;) { liNode = liNodes[i]; listTag = (liNode.parentNode.nodeName === 'OL') ? 'OL' : 'UL'; list = liNode.ownerDocument.createElement(listTag); prevLi = wysihtml5.dom.domNode(liNode).prev({nodeTypes: [wysihtml5.ELEMENT_NODE]}); prevLiList = (prevLi) ? prevLi.querySelector('ul, ol') : null; if (prevLi) { if (prevLiList) { prevLiList.appendChild(liNode); } else { list.appendChild(liNode); prevLi.appendChild(list); } found = true; } } }); return found; } }; ;wysihtml5.commands.outdentList = { exec: function(composer, command, value) { var listEls = composer.selection.getSelectionParentsByTag('LI'); if (listEls) { return this.tryToPullLiLevel(listEls, composer); } return false; }, state: function(composer, command) { return false; }, tryToPullLiLevel: function(liNodes, composer) { var listNode, outerListNode, outerLiNode, list, prevLi, liNode, afterList, found = false, that = this; composer.selection.executeAndRestoreRangy(function() { for (var i = liNodes.length; i--;) { liNode = liNodes[i]; if (liNode.parentNode) { listNode = liNode.parentNode; if (listNode.tagName === 'OL' || listNode.tagName === 'UL') { found = true; outerListNode = wysihtml5.dom.getParentElement(listNode.parentNode, { nodeName: ['OL', 'UL']}, false, composer.element); outerLiNode = wysihtml5.dom.getParentElement(listNode.parentNode, { nodeName: ['LI']}, false, composer.element); if (outerListNode && outerLiNode) { if (liNode.nextSibling) { afterList = that.getAfterList(listNode, liNode); liNode.appendChild(afterList); } outerListNode.insertBefore(liNode, outerLiNode.nextSibling); } else { if (liNode.nextSibling) { afterList = that.getAfterList(listNode, liNode); liNode.appendChild(afterList); } for (var j = liNode.childNodes.length; j--;) { listNode.parentNode.insertBefore(liNode.childNodes[j], listNode.nextSibling); } listNode.parentNode.insertBefore(document.createElement('br'), listNode.nextSibling); liNode.parentNode.removeChild(liNode); } // cleanup if (listNode.childNodes.length === 0) { listNode.parentNode.removeChild(listNode); } } } } }); return found; }, getAfterList: function(listNode, liNode) { var nodeName = listNode.nodeName, newList = document.createElement(nodeName); while (liNode.nextSibling) { newList.appendChild(liNode.nextSibling); } return newList; } };;/** * Undo Manager for wysihtml5 * slightly inspired by http://rniwa.com/editing/undomanager.html#the-undomanager-interface */ (function(wysihtml5) { var Z_KEY = 90, Y_KEY = 89, BACKSPACE_KEY = 8, DELETE_KEY = 46, MAX_HISTORY_ENTRIES = 25, DATA_ATTR_NODE = "data-wysihtml5-selection-node", DATA_ATTR_OFFSET = "data-wysihtml5-selection-offset", UNDO_HTML = '<span id="_wysihtml5-undo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', REDO_HTML = '<span id="_wysihtml5-redo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', dom = wysihtml5.dom; function cleanTempElements(doc) { var tempElement; while (tempElement = doc.querySelector("._wysihtml5-temp")) { tempElement.parentNode.removeChild(tempElement); } } wysihtml5.UndoManager = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.UndoManager.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.element = this.composer.element; this.position = 0; this.historyStr = []; this.historyDom = []; this.transact(); this._observe(); }, _observe: function() { var that = this, doc = this.composer.sandbox.getDocument(), lastKey; // Catch CTRL+Z and CTRL+Y dom.observe(this.element, "keydown", function(event) { if (event.altKey || (!event.ctrlKey && !event.metaKey)) { return; } var keyCode = event.keyCode, isUndo = keyCode === Z_KEY && !event.shiftKey, isRedo = (keyCode === Z_KEY && event.shiftKey) || (keyCode === Y_KEY); if (isUndo) { that.undo(); event.preventDefault(); } else if (isRedo) { that.redo(); event.preventDefault(); } }); // Catch delete and backspace dom.observe(this.element, "keydown", function(event) { var keyCode = event.keyCode; if (keyCode === lastKey) { return; } lastKey = keyCode; if (keyCode === BACKSPACE_KEY || keyCode === DELETE_KEY) { that.transact(); } }); this.editor .on("newword:composer", function() { that.transact(); }) .on("beforecommand:composer", function() { that.transact(); }); }, transact: function() { var previousHtml = this.historyStr[this.position - 1], currentHtml = this.composer.getValue(false, false), composerIsVisible = this.element.offsetWidth > 0 && this.element.offsetHeight > 0, range, node, offset, element, position; if (currentHtml === previousHtml) { return; } var length = this.historyStr.length = this.historyDom.length = this.position; if (length > MAX_HISTORY_ENTRIES) { this.historyStr.shift(); this.historyDom.shift(); this.position--; } this.position++; if (composerIsVisible) { // Do not start saving selection if composer is not visible range = this.composer.selection.getRange(); node = (range && range.startContainer) ? range.startContainer : this.element; offset = (range && range.startOffset) ? range.startOffset : 0; if (node.nodeType === wysihtml5.ELEMENT_NODE) { element = node; } else { element = node.parentNode; position = this.getChildNodeIndex(element, node); } element.setAttribute(DATA_ATTR_OFFSET, offset); if (typeof(position) !== "undefined") { element.setAttribute(DATA_ATTR_NODE, position); } } var clone = this.element.cloneNode(!!currentHtml); this.historyDom.push(clone); this.historyStr.push(currentHtml); if (element) { element.removeAttribute(DATA_ATTR_OFFSET); element.removeAttribute(DATA_ATTR_NODE); } }, undo: function() { this.transact(); if (!this.undoPossible()) { return; } this.set(this.historyDom[--this.position - 1]); this.editor.fire("undo:composer"); }, redo: function() { if (!this.redoPossible()) { return; } this.set(this.historyDom[++this.position - 1]); this.editor.fire("redo:composer"); }, undoPossible: function() { return this.position > 1; }, redoPossible: function() { return this.position < this.historyStr.length; }, set: function(historyEntry) { this.element.innerHTML = ""; var i = 0, childNodes = historyEntry.childNodes, length = historyEntry.childNodes.length; for (; i<length; i++) { this.element.appendChild(childNodes[i].cloneNode(true)); } // Restore selection var offset, node, position; if (historyEntry.hasAttribute(DATA_ATTR_OFFSET)) { offset = historyEntry.getAttribute(DATA_ATTR_OFFSET); position = historyEntry.getAttribute(DATA_ATTR_NODE); node = this.element; } else { node = this.element.querySelector("[" + DATA_ATTR_OFFSET + "]") || this.element; offset = node.getAttribute(DATA_ATTR_OFFSET); position = node.getAttribute(DATA_ATTR_NODE); node.removeAttribute(DATA_ATTR_OFFSET); node.removeAttribute(DATA_ATTR_NODE); } if (position !== null) { node = this.getChildNodeByIndex(node, +position); } this.composer.selection.set(node, offset); }, getChildNodeIndex: function(parent, child) { var i = 0, childNodes = parent.childNodes, length = childNodes.length; for (; i<length; i++) { if (childNodes[i] === child) { return i; } } }, getChildNodeByIndex: function(parent, index) { return parent.childNodes[index]; } }); })(wysihtml5); ;/** * TODO: the following methods still need unit test coverage */ wysihtml5.views.View = Base.extend( /** @scope wysihtml5.views.View.prototype */ { constructor: function(parent, textareaElement, config) { this.parent = parent; this.element = textareaElement; this.config = config; if (!this.config.noTextarea) { this._observeViewChange(); } }, _observeViewChange: function() { var that = this; this.parent.on("beforeload", function() { that.parent.on("change_view", function(view) { if (view === that.name) { that.parent.currentView = that; that.show(); // Using tiny delay here to make sure that the placeholder is set before focusing setTimeout(function() { that.focus(); }, 0); } else { that.hide(); } }); }); }, focus: function() { if (this.element.ownerDocument.querySelector(":focus") === this.element) { return; } try { this.element.focus(); } catch(e) {} }, hide: function() { this.element.style.display = "none"; }, show: function() { this.element.style.display = ""; }, disable: function() { this.element.setAttribute("disabled", "disabled"); }, enable: function() { this.element.removeAttribute("disabled"); } }); ;(function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser; wysihtml5.views.Composer = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Composer.prototype */ { name: "composer", // Needed for firefox in order to display a proper caret in an empty contentEditable CARET_HACK: "<br>", constructor: function(parent, editableElement, config) { this.base(parent, editableElement, config); if (!this.config.noTextarea) { this.textarea = this.parent.textarea; } else { this.editableArea = editableElement; } if (this.config.contentEditableMode) { this._initContentEditableArea(); } else { this._initSandbox(); } }, clear: function() { this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK; }, getValue: function(parse, clearInternals) { var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element); if (parse !== false) { value = this.parent.parse(value, (clearInternals === false) ? false : true); } return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } try { this.element.innerHTML = html; } catch (e) { this.element.innerText = html; } }, cleanUp: function() { this.parent.parse(this.element); }, show: function() { this.editableArea.style.display = this._displayStyle || ""; if (!this.config.noTextarea && !this.textarea.element.disabled) { // Firefox needs this, otherwise contentEditable becomes uneditable this.disable(); this.enable(); } }, hide: function() { this._displayStyle = dom.getStyle("display").from(this.editableArea); if (this._displayStyle === "none") { this._displayStyle = null; } this.editableArea.style.display = "none"; }, disable: function() { this.parent.fire("disable:composer"); this.element.removeAttribute("contentEditable"); }, enable: function() { this.parent.fire("enable:composer"); this.element.setAttribute("contentEditable", "true"); }, focus: function(setToEnd) { // IE 8 fires the focus event after .focus() // This is needed by our simulate_placeholder.js to work // therefore we clear it ourselves this time if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) { this.clear(); } this.base(); var lastChild = this.element.lastChild; if (setToEnd && lastChild && this.selection) { if (lastChild.nodeName === "BR") { this.selection.setBefore(this.element.lastChild); } else { this.selection.setAfter(this.element.lastChild); } } }, getTextContent: function() { return dom.getTextContent(this.element); }, hasPlaceholderSet: function() { return this.getTextContent() == ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder")) && this.placeholderSet; }, isEmpty: function() { var innerHTML = this.element.innerHTML.toLowerCase(); return (/^(\s|<br>|<\/br>|<p>|<\/p>)*$/i).test(innerHTML) || innerHTML === "" || innerHTML === "<br>" || innerHTML === "<p></p>" || innerHTML === "<p><br></p>" || this.hasPlaceholderSet(); }, _initContentEditableArea: function() { var that = this; if (this.config.noTextarea) { this.sandbox = new dom.ContentEditableArea(function() { that._create(); }, {}, this.editableArea); } else { this.sandbox = new dom.ContentEditableArea(function() { that._create(); }); this.editableArea = this.sandbox.getContentEditable(); dom.insert(this.editableArea).after(this.textarea.element); this._createWysiwygFormField(); } }, _initSandbox: function() { var that = this; this.sandbox = new dom.Sandbox(function() { that._create(); }, { stylesheets: this.config.stylesheets }); this.editableArea = this.sandbox.getIframe(); var textareaElement = this.textarea.element; dom.insert(this.editableArea).after(textareaElement); this._createWysiwygFormField(); }, // Creates hidden field which tells the server after submit, that the user used an wysiwyg editor _createWysiwygFormField: function() { if (this.textarea.element.form) { var hiddenField = document.createElement("input"); hiddenField.type = "hidden"; hiddenField.name = "_wysihtml5_mode"; hiddenField.value = 1; dom.insert(hiddenField).after(this.textarea.element); } }, _create: function() { var that = this; this.doc = this.sandbox.getDocument(); this.element = (this.config.contentEditableMode) ? this.sandbox.getContentEditable() : this.doc.body; if (!this.config.noTextarea) { this.textarea = this.parent.textarea; this.element.innerHTML = this.textarea.getValue(true, false); } else { this.cleanUp(); // cleans contenteditable on initiation as it may contain html } // Make sure our selection handler is ready this.selection = new wysihtml5.Selection(this.parent, this.element, this.config.uneditableContainerClassname); // Make sure commands dispatcher is ready this.commands = new wysihtml5.Commands(this.parent); if (!this.config.noTextarea) { dom.copyAttributes([ "className", "spellcheck", "title", "lang", "dir", "accessKey" ]).from(this.textarea.element).to(this.element); } dom.addClass(this.element, this.config.composerClassName); // // Make the editor look like the original textarea, by syncing styles if (this.config.style && !this.config.contentEditableMode) { this.style(); } this.observe(); var name = this.config.name; if (name) { dom.addClass(this.element, name); if (!this.config.contentEditableMode) { dom.addClass(this.editableArea, name); } } this.enable(); if (!this.config.noTextarea && this.textarea.element.disabled) { this.disable(); } // Simulate html5 placeholder attribute on contentEditable element var placeholderText = typeof(this.config.placeholder) === "string" ? this.config.placeholder : ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder")); if (placeholderText) { dom.simulatePlaceholder(this.parent, this, placeholderText); } // Make sure that the browser avoids using inline styles whenever possible this.commands.exec("styleWithCSS", false); this._initAutoLinking(); this._initObjectResizing(); this._initUndoManager(); this._initLineBreaking(); // Simulate html5 autofocus on contentEditable element // This doesn't work on IOS (5.1.1) if (!this.config.noTextarea && (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) && !browser.isIos()) { setTimeout(function() { that.focus(true); }, 100); } // IE sometimes leaves a single paragraph, which can't be removed by the user if (!browser.clearsContentEditableCorrectly()) { wysihtml5.quirks.ensureProperClearing(this); } // Set up a sync that makes sure that textarea and editor have the same content if (this.initSync && this.config.sync) { this.initSync(); } // Okay hide the textarea, we are ready to go if (!this.config.noTextarea) { this.textarea.hide(); } // Fire global (before-)load event this.parent.fire("beforeload").fire("load"); }, _initAutoLinking: function() { var that = this, supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(), supportsAutoLinking = browser.doesAutoLinkingInContentEditable(); if (supportsDisablingOfAutoLinking) { this.commands.exec("autoUrlDetect", false); } if (!this.config.autoLink) { return; } // Only do the auto linking by ourselves when the browser doesn't support auto linking // OR when he supports auto linking but we were able to turn it off (IE9+) if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) { this.parent.on("newword:composer", function() { if (dom.getTextContent(that.element).match(dom.autoLink.URL_REG_EXP)) { that.selection.executeAndRestore(function(startContainer, endContainer) { var uneditables = that.element.querySelectorAll("." + that.config.uneditableContainerClassname), isInUneditable = false; for (var i = uneditables.length; i--;) { if (wysihtml5.dom.contains(uneditables[i], endContainer)) { isInUneditable = true; } } if (!isInUneditable) dom.autoLink(endContainer.parentNode, [that.config.uneditableContainerClassname]); }); } }); dom.observe(this.element, "blur", function() { dom.autoLink(that.element, [that.config.uneditableContainerClassname]); }); } // Assuming we have the following: // <a href="http://www.google.de">http://www.google.de</a> // If a user now changes the url in the innerHTML we want to make sure that // it's synchronized with the href attribute (as long as the innerHTML is still a url) var // Use a live NodeList to check whether there are any links in the document links = this.sandbox.getDocument().getElementsByTagName("a"), // The autoLink helper method reveals a reg exp to detect correct urls urlRegExp = dom.autoLink.URL_REG_EXP, getTextContent = function(element) { var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim(); if (textContent.substr(0, 4) === "www.") { textContent = "http://" + textContent; } return textContent; }; dom.observe(this.element, "keydown", function(event) { if (!links.length) { return; } var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument), link = dom.getParentElement(selectedNode, { nodeName: "A" }, 4), textContent; if (!link) { return; } textContent = getTextContent(link); // keydown is fired before the actual content is changed // therefore we set a timeout to change the href setTimeout(function() { var newTextContent = getTextContent(link); if (newTextContent === textContent) { return; } // Only set href when new href looks like a valid url if (newTextContent.match(urlRegExp)) { link.setAttribute("href", newTextContent); } }, 0); }); }, _initObjectResizing: function() { this.commands.exec("enableObjectResizing", true); // IE sets inline styles after resizing objects // The following lines make sure that the width/height css properties // are copied over to the width/height attributes if (browser.supportsEvent("resizeend")) { var properties = ["width", "height"], propertiesLength = properties.length, element = this.element; dom.observe(element, "resizeend", function(event) { var target = event.target || event.srcElement, style = target.style, i = 0, property; if (target.nodeName !== "IMG") { return; } for (; i<propertiesLength; i++) { property = properties[i]; if (style[property]) { target.setAttribute(property, parseInt(style[property], 10)); style[property] = ""; } } // After resizing IE sometimes forgets to remove the old resize handles wysihtml5.quirks.redraw(element); }); } }, _initUndoManager: function() { this.undoManager = new wysihtml5.UndoManager(this.parent); }, _initLineBreaking: function() { var that = this, USE_NATIVE_LINE_BREAK_INSIDE_TAGS = ["LI", "P", "H1", "H2", "H3", "H4", "H5", "H6"], LIST_TAGS = ["UL", "OL", "MENU"]; function adjust(selectedNode) { var parentElement = dom.getParentElement(selectedNode, { nodeName: ["P", "DIV"] }, 2); if (parentElement && dom.contains(that.element, parentElement)) { that.selection.executeAndRestore(function() { if (that.config.useLineBreaks) { dom.replaceWithChildNodes(parentElement); } else if (parentElement.nodeName !== "P") { dom.renameElement(parentElement, "p"); } }); } } if (!this.config.useLineBreaks) { dom.observe(this.element, ["focus", "keydown"], function() { if (that.isEmpty()) { var paragraph = that.doc.createElement("P"); that.element.innerHTML = ""; that.element.appendChild(paragraph); if (!browser.displaysCaretInEmptyContentEditableCorrectly()) { paragraph.innerHTML = "<br>"; that.selection.setBefore(paragraph.firstChild); } else { that.selection.selectNode(paragraph, true); } } }); } // Under certain circumstances Chrome + Safari create nested <p> or <hX> tags after paste // Inserting an invisible white space in front of it fixes the issue // This is too hacky and causes selection not to replace content on paste in chrome /* if (browser.createsNestedInvalidMarkupAfterPaste()) { dom.observe(this.element, "paste", function(event) { var invisibleSpace = that.doc.createTextNode(wysihtml5.INVISIBLE_SPACE); that.selection.insertNode(invisibleSpace); }); }*/ dom.observe(this.element, "keydown", function(event) { var keyCode = event.keyCode; if (event.shiftKey) { return; } if (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY) { return; } var blockElement = dom.getParentElement(that.selection.getSelectedNode(), { nodeName: USE_NATIVE_LINE_BREAK_INSIDE_TAGS }, 4); if (blockElement) { setTimeout(function() { // Unwrap paragraph after leaving a list or a H1-6 var selectedNode = that.selection.getSelectedNode(), list; if (blockElement.nodeName === "LI") { if (!selectedNode) { return; } list = dom.getParentElement(selectedNode, { nodeName: LIST_TAGS }, 2); if (!list) { adjust(selectedNode); } } if (keyCode === wysihtml5.ENTER_KEY && blockElement.nodeName.match(/^H[1-6]$/)) { adjust(selectedNode); } }, 0); return; } if (that.config.useLineBreaks && keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) { event.preventDefault(); that.commands.exec("insertLineBreak"); } }); } }); })(wysihtml5); ;(function(wysihtml5) { var dom = wysihtml5.dom, doc = document, win = window, HOST_TEMPLATE = doc.createElement("div"), /** * Styles to copy from textarea to the composer element */ TEXT_FORMATTING = [ "background-color", "color", "cursor", "font-family", "font-size", "font-style", "font-variant", "font-weight", "line-height", "letter-spacing", "text-align", "text-decoration", "text-indent", "text-rendering", "word-break", "word-wrap", "word-spacing" ], /** * Styles to copy from textarea to the iframe */ BOX_FORMATTING = [ "background-color", "border-collapse", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-left-color", "border-left-style", "border-left-width", "border-right-color", "border-right-style", "border-right-width", "border-top-color", "border-top-style", "border-top-width", "clear", "display", "float", "margin-bottom", "margin-left", "margin-right", "margin-top", "outline-color", "outline-offset", "outline-width", "outline-style", "padding-left", "padding-right", "padding-top", "padding-bottom", "position", "top", "left", "right", "bottom", "z-index", "vertical-align", "text-align", "-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing", "-webkit-box-shadow", "-moz-box-shadow", "-ms-box-shadow","box-shadow", "-webkit-border-top-right-radius", "-moz-border-radius-topright", "border-top-right-radius", "-webkit-border-bottom-right-radius", "-moz-border-radius-bottomright", "border-bottom-right-radius", "-webkit-border-bottom-left-radius", "-moz-border-radius-bottomleft", "border-bottom-left-radius", "-webkit-border-top-left-radius", "-moz-border-radius-topleft", "border-top-left-radius", "width", "height" ], ADDITIONAL_CSS_RULES = [ "html { height: 100%; }", "body { height: 100%; padding: 1px 0 0 0; margin: -1px 0 0 0; }", "body > p:first-child { margin-top: 0; }", "._wysihtml5-temp { display: none; }", wysihtml5.browser.isGecko ? "body.placeholder { color: graytext !important; }" : "body.placeholder { color: #a9a9a9 !important; }", // Ensure that user see's broken images and can delete them "img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }" ]; /** * With "setActive" IE offers a smart way of focusing elements without scrolling them into view: * http://msdn.microsoft.com/en-us/library/ms536738(v=vs.85).aspx * * Other browsers need a more hacky way: (pssst don't tell my mama) * In order to prevent the element being scrolled into view when focusing it, we simply * move it out of the scrollable area, focus it, and reset it's position */ var focusWithoutScrolling = function(element) { if (element.setActive) { // Following line could cause a js error when the textarea is invisible // See https://github.com/xing/wysihtml5/issues/9 try { element.setActive(); } catch(e) {} } else { var elementStyle = element.style, originalScrollTop = doc.documentElement.scrollTop || doc.body.scrollTop, originalScrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft, originalStyles = { position: elementStyle.position, top: elementStyle.top, left: elementStyle.left, WebkitUserSelect: elementStyle.WebkitUserSelect }; dom.setStyles({ position: "absolute", top: "-99999px", left: "-99999px", // Don't ask why but temporarily setting -webkit-user-select to none makes the whole thing performing smoother WebkitUserSelect: "none" }).on(element); element.focus(); dom.setStyles(originalStyles).on(element); if (win.scrollTo) { // Some browser extensions unset this method to prevent annoyances // "Better PopUp Blocker" for Chrome http://code.google.com/p/betterpopupblocker/source/browse/trunk/blockStart.js#100 // Issue: http://code.google.com/p/betterpopupblocker/issues/detail?id=1 win.scrollTo(originalScrollLeft, originalScrollTop); } } }; wysihtml5.views.Composer.prototype.style = function() { var that = this, originalActiveElement = doc.querySelector(":focus"), textareaElement = this.textarea.element, hasPlaceholder = textareaElement.hasAttribute("placeholder"), originalPlaceholder = hasPlaceholder && textareaElement.getAttribute("placeholder"), originalDisplayValue = textareaElement.style.display, originalDisabled = textareaElement.disabled, displayValueForCopying; this.focusStylesHost = HOST_TEMPLATE.cloneNode(false); this.blurStylesHost = HOST_TEMPLATE.cloneNode(false); this.disabledStylesHost = HOST_TEMPLATE.cloneNode(false); // Remove placeholder before copying (as the placeholder has an affect on the computed style) if (hasPlaceholder) { textareaElement.removeAttribute("placeholder"); } if (textareaElement === originalActiveElement) { textareaElement.blur(); } // enable for copying styles textareaElement.disabled = false; // set textarea to display="none" to get cascaded styles via getComputedStyle textareaElement.style.display = displayValueForCopying = "none"; if ((textareaElement.getAttribute("rows") && dom.getStyle("height").from(textareaElement) === "auto") || (textareaElement.getAttribute("cols") && dom.getStyle("width").from(textareaElement) === "auto")) { textareaElement.style.display = displayValueForCopying = originalDisplayValue; } // --------- iframe styles (has to be set before editor styles, otherwise IE9 sets wrong fontFamily on blurStylesHost) --------- dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.editableArea).andTo(this.blurStylesHost); // --------- editor styles --------- dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.element).andTo(this.blurStylesHost); // --------- apply standard rules --------- dom.insertCSS(ADDITIONAL_CSS_RULES).into(this.element.ownerDocument); // --------- :disabled styles --------- textareaElement.disabled = true; dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.disabledStylesHost); dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.disabledStylesHost); textareaElement.disabled = originalDisabled; // --------- :focus styles --------- textareaElement.style.display = originalDisplayValue; focusWithoutScrolling(textareaElement); textareaElement.style.display = displayValueForCopying; dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.focusStylesHost); dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.focusStylesHost); // reset textarea textareaElement.style.display = originalDisplayValue; dom.copyStyles(["display"]).from(textareaElement).to(this.editableArea); // Make sure that we don't change the display style of the iframe when copying styles oblur/onfocus // this is needed for when the change_view event is fired where the iframe is hidden and then // the blur event fires and re-displays it var boxFormattingStyles = wysihtml5.lang.array(BOX_FORMATTING).without(["display"]); // --------- restore focus --------- if (originalActiveElement) { originalActiveElement.focus(); } else { textareaElement.blur(); } // --------- restore placeholder --------- if (hasPlaceholder) { textareaElement.setAttribute("placeholder", originalPlaceholder); } // --------- Sync focus/blur styles --------- this.parent.on("focus:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.focusStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.focusStylesHost).to(that.element); }); this.parent.on("blur:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element); }); this.parent.observe("disable:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.disabledStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.disabledStylesHost).to(that.element); }); this.parent.observe("enable:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element); }); return this; }; })(wysihtml5); ;/** * Taking care of events * - Simulating 'change' event on contentEditable element * - Handling drag & drop logic * - Catch paste events * - Dispatch proprietary newword:composer event * - Keyboard shortcuts */ (function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser, /** * Map keyCodes to query commands */ shortcuts = { "66": "bold", // B "73": "italic", // I "85": "underline" // U }; var deleteAroundEditable = function(selection, uneditable, element) { // merge node with previous node from uneditable var prevNode = selection.getPreviousNode(uneditable, true), curNode = selection.getSelectedNode(); if (curNode.nodeType !== 1 && curNode.parentNode !== element) { curNode = curNode.parentNode; } if (prevNode) { if (curNode.nodeType == 1) { var first = curNode.firstChild; if (prevNode.nodeType == 1) { while (curNode.firstChild) { prevNode.appendChild(curNode.firstChild); } } else { while (curNode.firstChild) { uneditable.parentNode.insertBefore(curNode.firstChild, uneditable); } } if (curNode.parentNode) { curNode.parentNode.removeChild(curNode); } selection.setBefore(first); } else { if (prevNode.nodeType == 1) { prevNode.appendChild(curNode); } else { uneditable.parentNode.insertBefore(curNode, uneditable); } selection.setBefore(curNode); } } }; var handleDeleteKeyPress = function(event, selection, element, composer) { if (selection.isCollapsed()) { if (selection.caretIsInTheBeginnig('LI')) { event.preventDefault(); composer.commands.exec('outdentList'); } else if (selection.caretIsInTheBeginnig()) { event.preventDefault(); } else { if (selection.caretIsFirstInSelection() && selection.getPreviousNode() && selection.getPreviousNode().nodeName && (/^H\d$/gi).test(selection.getPreviousNode().nodeName) ) { var prevNode = selection.getPreviousNode(); event.preventDefault(); if ((/^\s*$/).test(prevNode.textContent || prevNode.innerText)) { // heading is empty prevNode.parentNode.removeChild(prevNode); } else { var range = prevNode.ownerDocument.createRange(); range.selectNodeContents(prevNode); range.collapse(false); selection.setSelection(range); } } var beforeUneditable = selection.caretIsBeforeUneditable(); // Do a special delete if caret would delete uneditable if (beforeUneditable) { event.preventDefault(); deleteAroundEditable(selection, beforeUneditable, element); } } } else { if (selection.containsUneditable()) { event.preventDefault(); selection.deleteContents(); } } }; var handleTabKeyDown = function(composer, element) { if (!composer.selection.isCollapsed()) { composer.selection.deleteContents(); } else if (composer.selection.caretIsInTheBeginnig('LI')) { if (composer.commands.exec('indentList')) return; } // Is &emsp; close enough to tab. Could not find enough counter arguments for now. composer.commands.exec("insertHTML", "&emsp;"); }; wysihtml5.views.Composer.prototype.observe = function() { var that = this, state = this.getValue(false, false), container = (this.sandbox.getIframe) ? this.sandbox.getIframe() : this.sandbox.getContentEditable(), element = this.element, focusBlurElement = (browser.supportsEventsInIframeCorrectly() || this.sandbox.getContentEditable) ? element : this.sandbox.getWindow(), pasteEvents = ["drop", "paste", "beforepaste"], interactionEvents = ["drop", "paste", "mouseup", "focus", "keyup"]; // --------- destroy:composer event --------- dom.observe(container, "DOMNodeRemoved", function() { clearInterval(domNodeRemovedInterval); that.parent.fire("destroy:composer"); }); // DOMNodeRemoved event is not supported in IE 8 if (!browser.supportsMutationEvents()) { var domNodeRemovedInterval = setInterval(function() { if (!dom.contains(document.documentElement, container)) { clearInterval(domNodeRemovedInterval); that.parent.fire("destroy:composer"); } }, 250); } // --------- User interaction tracking -- dom.observe(focusBlurElement, interactionEvents, function() { setTimeout(function() { that.parent.fire("interaction").fire("interaction:composer"); }, 0); }); if (this.config.handleTables) { if(!this.tableClickHandle && this.doc.execCommand && wysihtml5.browser.supportsCommand(this.doc, "enableObjectResizing") && wysihtml5.browser.supportsCommand(this.doc, "enableInlineTableEditing")) { if (this.sandbox.getIframe) { this.tableClickHandle = dom.observe(container , ["focus", "mouseup", "mouseover"], function() { that.doc.execCommand("enableObjectResizing", false, "false"); that.doc.execCommand("enableInlineTableEditing", false, "false"); that.tableClickHandle.stop(); }); } else { setTimeout(function() { that.doc.execCommand("enableObjectResizing", false, "false"); that.doc.execCommand("enableInlineTableEditing", false, "false"); }, 0); } } this.tableSelection = wysihtml5.quirks.tableCellsSelection(element, that.parent); } // --------- Focus & blur logic --------- dom.observe(focusBlurElement, "focus", function(event) { that.parent.fire("focus", event).fire("focus:composer", event); // Delay storing of state until all focus handler are fired // especially the one which resets the placeholder setTimeout(function() { state = that.getValue(false, false); }, 0); }); dom.observe(focusBlurElement, "blur", function(event) { if (state !== that.getValue(false, false)) { //create change event if supported (all except IE8) var changeevent = event; if(typeof Object.create == 'function') { changeevent = Object.create(event, { type: { value: 'change' } }); } that.parent.fire("change", changeevent).fire("change:composer", changeevent); } that.parent.fire("blur", event).fire("blur:composer", event); }); // --------- Drag & Drop logic --------- dom.observe(element, "dragenter", function() { that.parent.fire("unset_placeholder"); }); dom.observe(element, pasteEvents, function(event) { that.parent.fire(event.type, event).fire(event.type + ":composer", event); }); if (this.config.copyedFromMarking) { // If supported the copied source is based directly on selection // Very useful for webkit based browsers where copy will otherwise contain a lot of code and styles based on whatever and not actually in selection. dom.observe(element, "copy", function(event) { if (event.clipboardData) { event.clipboardData.setData("text/html", that.config.copyedFromMarking + that.selection.getHtml()); event.preventDefault(); } that.parent.fire(event.type, event).fire(event.type + ":composer", event); }); } // --------- neword event --------- dom.observe(element, "keyup", function(event) { var keyCode = event.keyCode; if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) { that.parent.fire("newword:composer"); } }); this.parent.on("paste:composer", function() { setTimeout(function() { that.parent.fire("newword:composer"); }, 0); }); // --------- Make sure that images are selected when clicking on them --------- if (!browser.canSelectImagesInContentEditable()) { dom.observe(element, "mousedown", function(event) { var target = event.target; var allImages = element.querySelectorAll('img'), notMyImages = element.querySelectorAll('.' + that.config.uneditableContainerClassname + ' img'), myImages = wysihtml5.lang.array(allImages).without(notMyImages); if (target.nodeName === "IMG" && wysihtml5.lang.array(myImages).contains(target)) { that.selection.selectNode(target); } }); } if (!browser.canSelectImagesInContentEditable()) { dom.observe(element, "drop", function(event) { // TODO: if I knew how to get dropped elements list from event I could limit it to only IMG element case setTimeout(function() { that.selection.getSelection().removeAllRanges(); }, 0); }); } if (browser.hasHistoryIssue() && browser.supportsSelectionModify()) { dom.observe(element, "keydown", function(event) { if (!event.metaKey && !event.ctrlKey) { return; } var keyCode = event.keyCode, win = element.ownerDocument.defaultView, selection = win.getSelection(); if (keyCode === 37 || keyCode === 39) { if (keyCode === 37) { selection.modify("extend", "left", "lineboundary"); if (!event.shiftKey) { selection.collapseToStart(); } } if (keyCode === 39) { selection.modify("extend", "right", "lineboundary"); if (!event.shiftKey) { selection.collapseToEnd(); } } event.preventDefault(); } }); } // --------- Shortcut logic --------- dom.observe(element, "keydown", function(event) { var keyCode = event.keyCode, command = shortcuts[keyCode]; if ((event.ctrlKey || event.metaKey) && !event.altKey && command) { that.commands.exec(command); event.preventDefault(); } if (keyCode === 8) { // delete key handleDeleteKeyPress(event, that.selection, element, that); } else if (that.config.handleTabKey && keyCode === 9) { event.preventDefault(); handleTabKeyDown(that, element); } }); // --------- Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor --------- dom.observe(element, "keydown", function(event) { var target = that.selection.getSelectedNode(true), keyCode = event.keyCode, parent; if (target && target.nodeName === "IMG" && (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY)) { // 8 => backspace, 46 => delete parent = target.parentNode; // delete the <img> parent.removeChild(target); // and it's parent <a> too if it hasn't got any other child nodes if (parent.nodeName === "A" && !parent.firstChild) { parent.parentNode.removeChild(parent); } setTimeout(function() { wysihtml5.quirks.redraw(element); }, 0); event.preventDefault(); } }); // --------- IE 8+9 focus the editor when the iframe is clicked (without actually firing the 'focus' event on the <body>) --------- if (!this.config.contentEditableMode && browser.hasIframeFocusIssue()) { dom.observe(container, "focus", function() { setTimeout(function() { if (that.doc.querySelector(":focus") !== that.element) { that.focus(); } }, 0); }); dom.observe(this.element, "blur", function() { setTimeout(function() { that.selection.getSelection().removeAllRanges(); }, 0); }); } // --------- Show url in tooltip when hovering links or images --------- var titlePrefixes = { IMG: "Image: ", A: "Link: " }; dom.observe(element, "mouseover", function(event) { var target = event.target, nodeName = target.nodeName, title; if (nodeName !== "A" && nodeName !== "IMG") { return; } var hasTitle = target.hasAttribute("title"); if(!hasTitle){ title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src")); target.setAttribute("title", title); } }); }; })(wysihtml5); ;/** * Class that takes care that the value of the composer and the textarea is always in sync */ (function(wysihtml5) { var INTERVAL = 400; wysihtml5.views.Synchronizer = Base.extend( /** @scope wysihtml5.views.Synchronizer.prototype */ { constructor: function(editor, textarea, composer) { this.editor = editor; this.textarea = textarea; this.composer = composer; this._observe(); }, /** * Sync html from composer to textarea * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea */ fromComposerToTextarea: function(shouldParseHtml) { this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue(false, false)).trim(), shouldParseHtml); }, /** * Sync value of textarea to composer * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer */ fromTextareaToComposer: function(shouldParseHtml) { var textareaValue = this.textarea.getValue(false, false); if (textareaValue) { this.composer.setValue(textareaValue, shouldParseHtml); } else { this.composer.clear(); this.editor.fire("set_placeholder"); } }, /** * Invoke syncing based on view state * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer/textarea */ sync: function(shouldParseHtml) { if (this.editor.currentView.name === "textarea") { this.fromTextareaToComposer(shouldParseHtml); } else { this.fromComposerToTextarea(shouldParseHtml); } }, /** * Initializes interval-based syncing * also makes sure that on-submit the composer's content is synced with the textarea * immediately when the form gets submitted */ _observe: function() { var interval, that = this, form = this.textarea.element.form, startInterval = function() { interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL); }, stopInterval = function() { clearInterval(interval); interval = null; }; startInterval(); if (form) { // If the textarea is in a form make sure that after onreset and onsubmit the composer // has the correct state wysihtml5.dom.observe(form, "submit", function() { that.sync(true); }); wysihtml5.dom.observe(form, "reset", function() { setTimeout(function() { that.fromTextareaToComposer(); }, 0); }); } this.editor.on("change_view", function(view) { if (view === "composer" && !interval) { that.fromTextareaToComposer(true); startInterval(); } else if (view === "textarea") { that.fromComposerToTextarea(true); stopInterval(); } }); this.editor.on("destroy:composer", stopInterval); } }); })(wysihtml5); ;wysihtml5.views.Textarea = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Textarea.prototype */ { name: "textarea", constructor: function(parent, textareaElement, config) { this.base(parent, textareaElement, config); this._observe(); }, clear: function() { this.element.value = ""; }, getValue: function(parse) { var value = this.isEmpty() ? "" : this.element.value; if (parse !== false) { value = this.parent.parse(value); } return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } this.element.value = html; }, cleanUp: function() { var html = this.parent.parse(this.element.value); this.element.value = html; }, hasPlaceholderSet: function() { var supportsPlaceholder = wysihtml5.browser.supportsPlaceholderAttributeOn(this.element), placeholderText = this.element.getAttribute("placeholder") || null, value = this.element.value, isEmpty = !value; return (supportsPlaceholder && isEmpty) || (value === placeholderText); }, isEmpty: function() { return !wysihtml5.lang.string(this.element.value).trim() || this.hasPlaceholderSet(); }, _observe: function() { var element = this.element, parent = this.parent, eventMapping = { focusin: "focus", focusout: "blur" }, /** * Calling focus() or blur() on an element doesn't synchronously trigger the attached focus/blur events * This is the case for focusin and focusout, so let's use them whenever possible, kkthxbai */ events = wysihtml5.browser.supportsEvent("focusin") ? ["focusin", "focusout", "change"] : ["focus", "blur", "change"]; parent.on("beforeload", function() { wysihtml5.dom.observe(element, events, function(event) { var eventName = eventMapping[event.type] || event.type; parent.fire(eventName).fire(eventName + ":textarea"); }); wysihtml5.dom.observe(element, ["paste", "drop"], function() { setTimeout(function() { parent.fire("paste").fire("paste:textarea"); }, 0); }); }); } }); ;/** * WYSIHTML5 Editor * * @param {Element} editableElement Reference to the textarea which should be turned into a rich text interface * @param {Object} [config] See defaultConfig object below for explanation of each individual config option * * @events * load * beforeload (for internal use only) * focus * focus:composer * focus:textarea * blur * blur:composer * blur:textarea * change * change:composer * change:textarea * paste * paste:composer * paste:textarea * newword:composer * destroy:composer * undo:composer * redo:composer * beforecommand:composer * aftercommand:composer * enable:composer * disable:composer * change_view */ (function(wysihtml5) { var undef; var defaultConfig = { // Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body name: undef, // Whether the editor should look like the textarea (by adopting styles) style: true, // Id of the toolbar element, pass falsey value if you don't want any toolbar logic toolbar: undef, // Whether toolbar is displayed after init by script automatically. // Can be set to false if toolobar is set to display only on editable area focus showToolbarAfterInit: true, // Whether urls, entered by the user should automatically become clickable-links autoLink: true, // Includes table editing events and cell selection tracking handleTables: true, // Tab key inserts tab into text as default behaviour. It can be disabled to regain keyboard navigation handleTabKey: true, // Object which includes parser rules to apply when html gets cleaned // See parser_rules/*.js for examples parserRules: { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} }, // Object which includes parser when the user inserts content via copy & paste. If null parserRules will be used instead pasteParserRulesets: null, // Parser method to use when the user inserts content parser: wysihtml5.dom.parse, // Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option composerClassName: "wysihtml5-editor", // Class name to add to the body when the wysihtml5 editor is supported bodyClassName: "wysihtml5-supported", // By default wysihtml5 will insert a <br> for line breaks, set this to false to use <p> useLineBreaks: true, // Array (or single string) of stylesheet urls to be loaded in the editor's iframe stylesheets: [], // Placeholder text to use, defaults to the placeholder attribute on the textarea element placeholderText: undef, // Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5) supportTouchDevices: true, // Whether senseless <span> elements (empty or without attributes) should be removed/replaced with their content cleanUp: true, // Whether to use div instead of secure iframe contentEditableMode: false, // Classname of container that editor should not touch and pass through // Pass false to disable uneditableContainerClassname: "wysihtml5-uneditable-container", // Browsers that support copied source handling will get a marking of the origin of the copied source (for determinig code cleanup rules on paste) // Also copied source is based directly on selection - // (very useful for webkit based browsers where copy will otherwise contain a lot of code and styles based on whatever and not actually in selection). // If falsy value is passed source override is also disabled copyedFromMarking: '<meta name="copied-from" content="wysihtml5">' }; wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.Editor.prototype */ { constructor: function(editableElement, config) { this.editableElement = typeof(editableElement) === "string" ? document.getElementById(editableElement) : editableElement; this.config = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get(); this._isCompatible = wysihtml5.browser.supported(); if (this.editableElement.nodeName.toLowerCase() != "textarea") { this.config.contentEditableMode = true; this.config.noTextarea = true; } if (!this.config.noTextarea) { this.textarea = new wysihtml5.views.Textarea(this, this.editableElement, this.config); this.currentView = this.textarea; } // Sort out unsupported/unwanted browsers here if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) { var that = this; setTimeout(function() { that.fire("beforeload").fire("load"); }, 0); return; } // Add class name to body, to indicate that the editor is supported wysihtml5.dom.addClass(document.body, this.config.bodyClassName); this.composer = new wysihtml5.views.Composer(this, this.editableElement, this.config); this.currentView = this.composer; if (typeof(this.config.parser) === "function") { this._initParser(); } this.on("beforeload", this.handleBeforeLoad); }, handleBeforeLoad: function() { if (!this.config.noTextarea) { this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer); } if (this.config.toolbar) { this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar, this.config.showToolbarAfterInit); } }, isCompatible: function() { return this._isCompatible; }, clear: function() { this.currentView.clear(); return this; }, getValue: function(parse, clearInternals) { return this.currentView.getValue(parse, clearInternals); }, setValue: function(html, parse) { this.fire("unset_placeholder"); if (!html) { return this.clear(); } this.currentView.setValue(html, parse); return this; }, cleanUp: function() { this.currentView.cleanUp(); }, focus: function(setToEnd) { this.currentView.focus(setToEnd); return this; }, /** * Deactivate editor (make it readonly) */ disable: function() { this.currentView.disable(); return this; }, /** * Activate editor */ enable: function() { this.currentView.enable(); return this; }, isEmpty: function() { return this.currentView.isEmpty(); }, hasPlaceholderSet: function() { return this.currentView.hasPlaceholderSet(); }, parse: function(htmlOrElement, clearInternals) { var parseContext = (this.config.contentEditableMode) ? document : ((this.composer) ? this.composer.sandbox.getDocument() : null); var returnValue = this.config.parser(htmlOrElement, { "rules": this.config.parserRules, "cleanUp": this.config.cleanUp, "context": parseContext, "uneditableClass": this.config.uneditableContainerClassname, "clearInternals" : clearInternals }); if (typeof(htmlOrElement) === "object") { wysihtml5.quirks.redraw(htmlOrElement); } return returnValue; }, /** * Prepare html parser logic * - Observes for paste and drop */ _initParser: function() { var that = this, oldHtml, cleanHtml; if (wysihtml5.browser.supportsModenPaste()) { this.on("paste:composer", function(event) { event.preventDefault(); oldHtml = wysihtml5.dom.getPastedHtml(event); if (oldHtml) { that._cleanAndPaste(oldHtml); } }); } else { this.on("beforepaste:composer", function(event) { event.preventDefault(); wysihtml5.dom.getPastedHtmlWithDiv(that.composer, function(pastedHTML) { if (pastedHTML) { that._cleanAndPaste(pastedHTML); } }); }); } }, _cleanAndPaste: function (oldHtml) { var cleanHtml = wysihtml5.quirks.cleanPastedHTML(oldHtml, { "referenceNode": this.composer.element, "rules": this.config.pasteParserRulesets || [{"set": this.config.parserRules}], "uneditableClass": this.config.uneditableContainerClassname }); this.composer.selection.deleteContents(); this.composer.selection.insertHTML(cleanHtml); } }); })(wysihtml5); ;/** * Toolbar Dialog * * @param {Element} link The toolbar link which causes the dialog to show up * @param {Element} container The dialog container * * @example * <!-- Toolbar link --> * <a data-wysihtml5-command="insertImage">insert an image</a> * * <!-- Dialog --> * <div data-wysihtml5-dialog="insertImage" style="display: none;"> * <label> * URL: <input data-wysihtml5-dialog-field="src" value="http://"> * </label> * <label> * Alternative text: <input data-wysihtml5-dialog-field="alt" value=""> * </label> * </div> * * <script> * var dialog = new wysihtml5.toolbar.Dialog( * document.querySelector("[data-wysihtml5-command='insertImage']"), * document.querySelector("[data-wysihtml5-dialog='insertImage']") * ); * dialog.observe("save", function(attributes) { * // do something * }); * </script> */ (function(wysihtml5) { var dom = wysihtml5.dom, CLASS_NAME_OPENED = "wysihtml5-command-dialog-opened", SELECTOR_FORM_ELEMENTS = "input, select, textarea", SELECTOR_FIELDS = "[data-wysihtml5-dialog-field]", ATTRIBUTE_FIELDS = "data-wysihtml5-dialog-field"; wysihtml5.toolbar.Dialog = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.toolbar.Dialog.prototype */ { constructor: function(link, container) { this.link = link; this.container = container; }, _observe: function() { if (this._observed) { return; } var that = this, callbackWrapper = function(event) { var attributes = that._serialize(); if (attributes == that.elementToChange) { that.fire("edit", attributes); } else { that.fire("save", attributes); } that.hide(); event.preventDefault(); event.stopPropagation(); }; dom.observe(that.link, "click", function() { if (dom.hasClass(that.link, CLASS_NAME_OPENED)) { setTimeout(function() { that.hide(); }, 0); } }); dom.observe(this.container, "keydown", function(event) { var keyCode = event.keyCode; if (keyCode === wysihtml5.ENTER_KEY) { callbackWrapper(event); } if (keyCode === wysihtml5.ESCAPE_KEY) { that.fire("cancel"); that.hide(); } }); dom.delegate(this.container, "[data-wysihtml5-dialog-action=save]", "click", callbackWrapper); dom.delegate(this.container, "[data-wysihtml5-dialog-action=cancel]", "click", function(event) { that.fire("cancel"); that.hide(); event.preventDefault(); event.stopPropagation(); }); var formElements = this.container.querySelectorAll(SELECTOR_FORM_ELEMENTS), i = 0, length = formElements.length, _clearInterval = function() { clearInterval(that.interval); }; for (; i<length; i++) { dom.observe(formElements[i], "change", _clearInterval); } this._observed = true; }, /** * Grabs all fields in the dialog and puts them in key=>value style in an object which * then gets returned */ _serialize: function() { var data = this.elementToChange || {}, fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value; } return data; }, /** * Takes the attributes of the "elementToChange" * and inserts them in their corresponding dialog input fields * * Assume the "elementToChange" looks like this: * <a href="http://www.google.com" target="_blank">foo</a> * * and we have the following dialog: * <input type="text" data-wysihtml5-dialog-field="href" value=""> * <input type="text" data-wysihtml5-dialog-field="target" value=""> * * after calling _interpolate() the dialog will look like this * <input type="text" data-wysihtml5-dialog-field="href" value="http://www.google.com"> * <input type="text" data-wysihtml5-dialog-field="target" value="_blank"> * * Basically it adopted the attribute values into the corresponding input fields * */ _interpolate: function(avoidHiddenFields) { var field, fieldName, newValue, focusedElement = document.querySelector(":focus"), fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { field = fields[i]; // Never change elements where the user is currently typing in if (field === focusedElement) { continue; } // Don't update hidden fields // See https://github.com/xing/wysihtml5/pull/14 if (avoidHiddenFields && field.type === "hidden") { continue; } fieldName = field.getAttribute(ATTRIBUTE_FIELDS); newValue = (this.elementToChange && typeof(this.elementToChange) !== 'boolean') ? (this.elementToChange.getAttribute(fieldName) || "") : field.defaultValue; field.value = newValue; } }, /** * Show the dialog element */ show: function(elementToChange) { if (dom.hasClass(this.link, CLASS_NAME_OPENED)) { return; } var that = this, firstField = this.container.querySelector(SELECTOR_FORM_ELEMENTS); this.elementToChange = elementToChange; this._observe(); this._interpolate(); if (elementToChange) { this.interval = setInterval(function() { that._interpolate(true); }, 500); } dom.addClass(this.link, CLASS_NAME_OPENED); this.container.style.display = ""; this.fire("show"); if (firstField && !elementToChange) { try { firstField.focus(); } catch(e) {} } }, /** * Hide the dialog element */ hide: function() { clearInterval(this.interval); this.elementToChange = null; dom.removeClass(this.link, CLASS_NAME_OPENED); this.container.style.display = "none"; this.fire("hide"); } }); })(wysihtml5); ;/** * Converts speech-to-text and inserts this into the editor * As of now (2011/03/25) this only is supported in Chrome >= 11 * * Note that it sends the recorded audio to the google speech recognition api: * http://stackoverflow.com/questions/4361826/does-chrome-have-buil-in-speech-recognition-for-input-type-text-x-webkit-speec * * Current HTML5 draft can be found here * http://lists.w3.org/Archives/Public/public-xg-htmlspeech/2011Feb/att-0020/api-draft.html * * "Accessing Google Speech API Chrome 11" * http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ */ (function(wysihtml5) { var dom = wysihtml5.dom; var linkStyles = { position: "relative" }; var wrapperStyles = { left: 0, margin: 0, opacity: 0, overflow: "hidden", padding: 0, position: "absolute", top: 0, zIndex: 1 }; var inputStyles = { cursor: "inherit", fontSize: "50px", height: "50px", marginTop: "-25px", outline: 0, padding: 0, position: "absolute", right: "-4px", top: "50%" }; var inputAttributes = { "x-webkit-speech": "", "speech": "" }; wysihtml5.toolbar.Speech = function(parent, link) { var input = document.createElement("input"); if (!wysihtml5.browser.supportsSpeechApiOn(input)) { link.style.display = "none"; return; } var lang = parent.editor.textarea.element.getAttribute("lang"); if (lang) { inputAttributes.lang = lang; } var wrapper = document.createElement("div"); wysihtml5.lang.object(wrapperStyles).merge({ width: link.offsetWidth + "px", height: link.offsetHeight + "px" }); dom.insert(input).into(wrapper); dom.insert(wrapper).into(link); dom.setStyles(inputStyles).on(input); dom.setAttributes(inputAttributes).on(input); dom.setStyles(wrapperStyles).on(wrapper); dom.setStyles(linkStyles).on(link); var eventName = "onwebkitspeechchange" in input ? "webkitspeechchange" : "speechchange"; dom.observe(input, eventName, function() { parent.execCommand("insertText", input.value); input.value = ""; }); dom.observe(input, "click", function(event) { if (dom.hasClass(link, "wysihtml5-command-disabled")) { event.preventDefault(); } event.stopPropagation(); }); }; })(wysihtml5); ;/** * Toolbar * * @param {Object} parent Reference to instance of Editor instance * @param {Element} container Reference to the toolbar container element * * @example * <div id="toolbar"> * <a data-wysihtml5-command="createLink">insert link</a> * <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1">insert h1</a> * </div> * * <script> * var toolbar = new wysihtml5.toolbar.Toolbar(editor, document.getElementById("toolbar")); * </script> */ (function(wysihtml5) { var CLASS_NAME_COMMAND_DISABLED = "wysihtml5-command-disabled", CLASS_NAME_COMMANDS_DISABLED = "wysihtml5-commands-disabled", CLASS_NAME_COMMAND_ACTIVE = "wysihtml5-command-active", CLASS_NAME_ACTION_ACTIVE = "wysihtml5-action-active", dom = wysihtml5.dom; wysihtml5.toolbar.Toolbar = Base.extend( /** @scope wysihtml5.toolbar.Toolbar.prototype */ { constructor: function(editor, container, showOnInit) { this.editor = editor; this.container = typeof(container) === "string" ? document.getElementById(container) : container; this.composer = editor.composer; this._getLinks("command"); this._getLinks("action"); this._observe(); if (showOnInit) { this.show(); } if (editor.config.classNameCommandDisabled != null) { CLASS_NAME_COMMAND_DISABLED = editor.config.classNameCommandDisabled; } if (editor.config.classNameCommandsDisabled != null) { CLASS_NAME_COMMANDS_DISABLED = editor.config.classNameCommandsDisabled; } if (editor.config.classNameCommandActive != null) { CLASS_NAME_COMMAND_ACTIVE = editor.config.classNameCommandActive; } if (editor.config.classNameActionActive != null) { CLASS_NAME_ACTION_ACTIVE = editor.config.classNameActionActive; } var speechInputLinks = this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"), length = speechInputLinks.length, i = 0; for (; i<length; i++) { new wysihtml5.toolbar.Speech(this, speechInputLinks[i]); } }, _getLinks: function(type) { var links = this[type + "Links"] = wysihtml5.lang.array(this.container.querySelectorAll("[data-wysihtml5-" + type + "]")).get(), length = links.length, i = 0, mapping = this[type + "Mapping"] = {}, link, group, name, value, dialog; for (; i<length; i++) { link = links[i]; name = link.getAttribute("data-wysihtml5-" + type); value = link.getAttribute("data-wysihtml5-" + type + "-value"); group = this.container.querySelector("[data-wysihtml5-" + type + "-group='" + name + "']"); dialog = this._getDialog(link, name); mapping[name + ":" + value] = { link: link, group: group, name: name, value: value, dialog: dialog, state: false }; } }, _getDialog: function(link, command) { var that = this, dialogElement = this.container.querySelector("[data-wysihtml5-dialog='" + command + "']"), dialog, caretBookmark; if (dialogElement) { if (wysihtml5.toolbar["Dialog_" + command]) { dialog = new wysihtml5.toolbar["Dialog_" + command](link, dialogElement); } else { dialog = new wysihtml5.toolbar.Dialog(link, dialogElement); } dialog.on("show", function() { caretBookmark = that.composer.selection.getBookmark(); that.editor.fire("show:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.on("save", function(attributes) { if (caretBookmark) { that.composer.selection.setBookmark(caretBookmark); } that._execCommand(command, attributes); that.editor.fire("save:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.on("cancel", function() { that.editor.focus(false); that.editor.fire("cancel:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); } return dialog; }, /** * @example * var toolbar = new wysihtml5.Toolbar(); * // Insert a <blockquote> element or wrap current selection in <blockquote> * toolbar.execCommand("formatBlock", "blockquote"); */ execCommand: function(command, commandValue) { if (this.commandsDisabled) { return; } var commandObj = this.commandMapping[command + ":" + commandValue]; // Show dialog when available if (commandObj && commandObj.dialog && !commandObj.state) { commandObj.dialog.show(); } else { this._execCommand(command, commandValue); } }, _execCommand: function(command, commandValue) { // Make sure that composer is focussed (false => don't move caret to the end) this.editor.focus(false); this.composer.commands.exec(command, commandValue); this._updateLinkStates(); }, execAction: function(action) { var editor = this.editor; if (action === "change_view") { if (editor.textarea) { if (editor.currentView === editor.textarea) { editor.fire("change_view", "composer"); } else { editor.fire("change_view", "textarea"); } } } if (action == "showSource") { editor.fire("showSource"); } }, _observe: function() { var that = this, editor = this.editor, container = this.container, links = this.commandLinks.concat(this.actionLinks), length = links.length, i = 0; for (; i<length; i++) { // 'javascript:;' and unselectable=on Needed for IE, but done in all browsers to make sure that all get the same css applied // (you know, a:link { ... } doesn't match anchors with missing href attribute) if (links[i].nodeName === "A") { dom.setAttributes({ href: "javascript:;", unselectable: "on" }).on(links[i]); } else { dom.setAttributes({ unselectable: "on" }).on(links[i]); } } // Needed for opera and chrome dom.delegate(container, "[data-wysihtml5-command], [data-wysihtml5-action]", "mousedown", function(event) { event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-command]", "click", function(event) { var link = this, command = link.getAttribute("data-wysihtml5-command"), commandValue = link.getAttribute("data-wysihtml5-command-value"); that.execCommand(command, commandValue); event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-action]", "click", function(event) { var action = this.getAttribute("data-wysihtml5-action"); that.execAction(action); event.preventDefault(); }); editor.on("interaction:composer", function() { that._updateLinkStates(); }); editor.on("focus:composer", function() { that.bookmark = null; }); if (this.editor.config.handleTables) { editor.on("tableselect:composer", function() { that.container.querySelectorAll('[data-wysihtml5-hiddentools="table"]')[0].style.display = ""; }); editor.on("tableunselect:composer", function() { that.container.querySelectorAll('[data-wysihtml5-hiddentools="table"]')[0].style.display = "none"; }); } editor.on("change_view", function(currentView) { // Set timeout needed in order to let the blur event fire first if (editor.textarea) { setTimeout(function() { that.commandsDisabled = (currentView !== "composer"); that._updateLinkStates(); if (that.commandsDisabled) { dom.addClass(container, CLASS_NAME_COMMANDS_DISABLED); } else { dom.removeClass(container, CLASS_NAME_COMMANDS_DISABLED); } }, 0); } }); }, _updateLinkStates: function() { var commandMapping = this.commandMapping, actionMapping = this.actionMapping, i, state, action, command; // every millisecond counts... this is executed quite often for (i in commandMapping) { command = commandMapping[i]; if (this.commandsDisabled) { state = false; dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } else { state = this.composer.commands.state(command.name, command.value); dom.removeClass(command.link, CLASS_NAME_COMMAND_DISABLED); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_DISABLED); } } if (command.state === state) { continue; } command.state = state; if (state) { dom.addClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.addClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { if (typeof(state) === "object" || wysihtml5.lang.object(state).isArray()) { if (!command.dialog.multiselect && wysihtml5.lang.object(state).isArray()) { // Grab first and only object/element in state array, otherwise convert state into boolean // to avoid showing a dialog for multiple selected elements which may have different attributes // eg. when two links with different href are selected, the state will be an array consisting of both link elements // but the dialog interface can only update one state = state.length === 1 ? state[0] : true; command.state = state; } command.dialog.show(state); } else { command.dialog.hide(); } } } else { dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } } for (i in actionMapping) { action = actionMapping[i]; if (action.name === "change_view") { action.state = this.editor.currentView === this.editor.textarea; if (action.state) { dom.addClass(action.link, CLASS_NAME_ACTION_ACTIVE); } else { dom.removeClass(action.link, CLASS_NAME_ACTION_ACTIVE); } } } }, show: function() { this.container.style.display = ""; }, hide: function() { this.container.style.display = "none"; } }); })(wysihtml5); ;(function(wysihtml5) { wysihtml5.toolbar.Dialog_createTable = wysihtml5.toolbar.Dialog.extend({ show: function(elementToChange) { this.base(elementToChange); } }); })(wysihtml5); ;(function(wysihtml5) { var dom = wysihtml5.dom, SELECTOR_FIELDS = "[data-wysihtml5-dialog-field]", ATTRIBUTE_FIELDS = "data-wysihtml5-dialog-field"; wysihtml5.toolbar.Dialog_foreColorStyle = wysihtml5.toolbar.Dialog.extend({ multiselect: true, _serialize: function() { var data = {}, fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0; for (; i<length; i++) { data[fields[i].getAttribute(ATTRIBUTE_FIELDS)] = fields[i].value; } return data; }, _interpolate: function(avoidHiddenFields) { var field, fieldName, newValue, focusedElement = document.querySelector(":focus"), fields = this.container.querySelectorAll(SELECTOR_FIELDS), length = fields.length, i = 0, firstElement = (this.elementToChange) ? ((wysihtml5.lang.object(this.elementToChange).isArray()) ? this.elementToChange[0] : this.elementToChange) : null, colorStr = (firstElement) ? firstElement.getAttribute('style') : null, color = (colorStr) ? wysihtml5.quirks.styleParser.parseColor(colorStr, "color") : null; for (; i<length; i++) { field = fields[i]; // Never change elements where the user is currently typing in if (field === focusedElement) { continue; } // Don't update hidden fields3 if (avoidHiddenFields && field.type === "hidden") { continue; } if (field.getAttribute(ATTRIBUTE_FIELDS) === "color") { if (color) { if (color[3] && color[3] != 1) { field.value = "rgba(" + color[0] + "," + color[1] + "," + color[2] + "," + color[3] + ");"; } else { field.value = "rgb(" + color[0] + "," + color[1] + "," + color[2] + ");"; } } else { field.value = "rgb(0,0,0);"; } } } } }); })(wysihtml5); ;(function(wysihtml5) { var dom = wysihtml5.dom, SELECTOR_FIELDS = "[data-wysihtml5-dialog-field]", ATTRIBUTE_FIELDS = "data-wysihtml5-dialog-field"; wysihtml5.toolbar.Dialog_fontSizeStyle = wysihtml5.toolbar.Dialog.extend({ multiselect: true, _serialize: function() { return {"size" : this.container.querySelector('[data-wysihtml5-dialog-field="size"]').value}; }, _interpolate: function(avoidHiddenFields) { var focusedElement = document.querySelector(":focus"), field = this.container.querySelector("[data-wysihtml5-dialog-field='size']"), firstElement = (this.elementToChange) ? ((wysihtml5.lang.object(this.elementToChange).isArray()) ? this.elementToChange[0] : this.elementToChange) : null, styleStr = (firstElement) ? firstElement.getAttribute('style') : null, size = (styleStr) ? wysihtml5.quirks.styleParser.parseFontSize(styleStr) : null; if (field && field !== focusedElement && size && !(/^\s*$/).test(size)) { field.value = size; } } }); })(wysihtml5); /*! handlebars v1.3.0 Copyright (C) 2011 by Yehuda Katz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @license */ var Handlebars=function(){var a=function(){"use strict";function a(a){this.string=a}var b;return a.prototype.toString=function(){return""+this.string},b=a}(),b=function(a){"use strict";function b(a){return h[a]||"&amp;"}function c(a,b){for(var c in b)Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c])}function d(a){return a instanceof g?a.toString():a||0===a?(a=""+a,j.test(a)?a.replace(i,b):a):""}function e(a){return a||0===a?m(a)&&0===a.length?!0:!1:!0}var f={},g=a,h={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},i=/[&<>"'`]/g,j=/[&<>"'`]/;f.extend=c;var k=Object.prototype.toString;f.toString=k;var l=function(a){return"function"==typeof a};l(/x/)&&(l=function(a){return"function"==typeof a&&"[object Function]"===k.call(a)});var l;f.isFunction=l;var m=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===k.call(a):!1};return f.isArray=m,f.escapeExpression=d,f.isEmpty=e,f}(a),c=function(){"use strict";function a(a,b){var d;b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn);for(var e=Error.prototype.constructor.call(this,a),f=0;f<c.length;f++)this[c[f]]=e[c[f]];d&&(this.lineNumber=d,this.column=b.firstColumn)}var b,c=["description","fileName","lineNumber","message","name","number","stack"];return a.prototype=new Error,b=a}(),d=function(a,b){"use strict";function c(a,b){this.helpers=a||{},this.partials=b||{},d(this)}function d(a){a.registerHelper("helperMissing",function(a){if(2===arguments.length)return void 0;throw new h("Missing helper: '"+a+"'")}),a.registerHelper("blockHelperMissing",function(b,c){var d=c.inverse||function(){},e=c.fn;return m(b)&&(b=b.call(this)),b===!0?e(this):b===!1||null==b?d(this):l(b)?b.length>0?a.helpers.each(b,c):d(this):e(b)}),a.registerHelper("each",function(a,b){var c,d=b.fn,e=b.inverse,f=0,g="";if(m(a)&&(a=a.call(this)),b.data&&(c=q(b.data)),a&&"object"==typeof a)if(l(a))for(var h=a.length;h>f;f++)c&&(c.index=f,c.first=0===f,c.last=f===a.length-1),g+=d(a[f],{data:c});else for(var i in a)a.hasOwnProperty(i)&&(c&&(c.key=i,c.index=f,c.first=0===f),g+=d(a[i],{data:c}),f++);return 0===f&&(g=e(this)),g}),a.registerHelper("if",function(a,b){return m(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||g.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){return m(a)&&(a=a.call(this)),g.isEmpty(a)?void 0:b.fn(a)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)})}function e(a,b){p.log(a,b)}var f={},g=a,h=b,i="1.3.0";f.VERSION=i;var j=4;f.COMPILER_REVISION=j;var k={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"};f.REVISION_CHANGES=k;var l=g.isArray,m=g.isFunction,n=g.toString,o="[object Object]";f.HandlebarsEnvironment=c,c.prototype={constructor:c,logger:p,log:e,registerHelper:function(a,b,c){if(n.call(a)===o){if(c||b)throw new h("Arg not supported with multiple helpers");g.extend(this.helpers,a)}else c&&(b.not=c),this.helpers[a]=b},registerPartial:function(a,b){n.call(a)===o?g.extend(this.partials,a):this.partials[a]=b}};var p={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(p.level<=a){var c=p.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}};f.logger=p,f.log=e;var q=function(a){var b={};return g.extend(b,a),b};return f.createFrame=q,f}(b,c),e=function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=m;if(b!==c){if(c>b){var d=n[c],e=n[b];throw new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){if(!b)throw new l("No environment passed to template");var c=function(a,c,d,e,f,g){var h=b.VM.invokePartial.apply(this,arguments);if(null!=h)return h;if(b.compile){var i={helpers:e,partials:f,data:g};return f[c]=b.compile(a,{data:void 0!==g},b),f[c](d,i)}throw new l("The partial "+c+" could not be compiled when running in runtime-only mode")},d={escapeExpression:k.escapeExpression,invokePartial:c,programs:[],program:function(a,b,c){var d=this.programs[a];return c?d=g(a,b,c):d||(d=this.programs[a]=g(a,b)),d},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c={},k.extend(c,b),k.extend(c,a)),c},programWithDepth:b.VM.programWithDepth,noop:b.VM.noop,compilerInfo:null};return function(c,e){e=e||{};var f,g,h=e.partial?e:b;e.partial||(f=e.helpers,g=e.partials);var i=a.call(d,h,c,f,g,e.data);return e.partial||b.VM.checkRevision(d.compilerInfo),i}}function f(a,b,c){var d=Array.prototype.slice.call(arguments,3),e=function(a,e){return e=e||{},b.apply(this,[a,e.data||c].concat(d))};return e.program=a,e.depth=d.length,e}function g(a,b,c){var d=function(a,d){return d=d||{},b(a,d.data||c)};return d.program=a,d.depth=0,d}function h(a,b,c,d,e,f){var g={partial:!0,helpers:d,partials:e,data:f};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,g):void 0}function i(){return""}var j={},k=a,l=b,m=c.COMPILER_REVISION,n=c.REVISION_CHANGES;return j.checkRevision=d,j.template=e,j.programWithDepth=f,j.program=g,j.invokePartial=h,j.noop=i,j}(b,c,d),f=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c,j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();return m.create=l,f=m}(d,a,c,b,e);return f}();this["wysihtml5"] = this["wysihtml5"] || {}; this["wysihtml5"]["tpl"] = this["wysihtml5"]["tpl"] || {}; this["wysihtml5"]["tpl"]["blockquote"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } function program3(depth0,data) { return " \n <span class=\"fa fa-quote-left\"></span>\n "; } function program5(depth0,data) { return "\n <span class=\"glyphicon glyphicon-quote\"></span>\n "; } buffer += "<li>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"blockquote\" data-wysihtml5-display-format-name=\"false\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n</li>\n"; return buffer; }); this["wysihtml5"]["tpl"]["color"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } buffer += "<li class=\"dropdown\">\n <a class=\"btn btn-default dropdown-toggle "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\" data-toggle=\"dropdown\" tabindex=\"-1\">\n <span class=\"current-color\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.black)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n <b class=\"caret\"></b>\n </a>\n <ul class=\"dropdown-menu\">\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"black\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"black\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.black)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"silver\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"silver\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.silver)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"gray\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"gray\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.gray)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"maroon\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"maroon\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.maroon)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"red\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"red\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.red)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"purple\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"purple\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.purple)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"green\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"green\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.green)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"olive\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"olive\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.olive)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"navy\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"navy\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.navy)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"blue\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"blue\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.blue)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><div class=\"wysihtml5-colors\" data-wysihtml5-command-value=\"orange\"></div><a class=\"wysihtml5-colors-title\" data-wysihtml5-command=\"foreColor\" data-wysihtml5-command-value=\"orange\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.colours)),stack1 == null || stack1 === false ? stack1 : stack1.orange)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n </ul>\n</li>\n"; return buffer; }); this["wysihtml5"]["tpl"]["emphasis"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } function program3(depth0,data) { var buffer = "", stack1; buffer += "\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"small\" title=\"CTRL+S\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.emphasis)),stack1 == null || stack1 === false ? stack1 : stack1.small)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n "; return buffer; } buffer += "<li>\n <div class=\"btn-group\">\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"bold\" title=\"CTRL+B\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.emphasis)),stack1 == null || stack1 === false ? stack1 : stack1.bold)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"italic\" title=\"CTRL+I\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.emphasis)),stack1 == null || stack1 === false ? stack1 : stack1.italic)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"underline\" title=\"CTRL+U\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.emphasis)),stack1 == null || stack1 === false ? stack1 : stack1.underline)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.emphasis)),stack1 == null || stack1 === false ? stack1 : stack1.small), {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n</li>\n"; return buffer; }); this["wysihtml5"]["tpl"]["font-styles"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } function program3(depth0,data) { return "\n <span class=\"fa fa-font\"></span>\n "; } function program5(depth0,data) { return "\n <span class=\"glyphicon glyphicon-font\"></span>\n "; } buffer += "<li class=\"dropdown\">\n <a class=\"btn btn-default dropdown-toggle "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\" data-toggle=\"dropdown\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <span class=\"current-font\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.normal)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n <b class=\"caret\"></b>\n </a>\n <ul class=\"dropdown-menu\">\n <li><a data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"p\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.normal)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><a data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"h1\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.h1)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><a data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"h2\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.h2)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><a data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"h3\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.h3)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><a data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"h4\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.h4)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><a data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"h5\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.h5)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n <li><a data-wysihtml5-command=\"formatBlock\" data-wysihtml5-command-value=\"h6\" tabindex=\"-1\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.font_styles)),stack1 == null || stack1 === false ? stack1 : stack1.h6)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a></li>\n </ul>\n</li>\n"; return buffer; }); this["wysihtml5"]["tpl"]["html"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } function program3(depth0,data) { return "\n <span class=\"fa fa-pencil\"></span>\n "; } function program5(depth0,data) { return "\n <span class=\"glyphicon glyphicon-pencil\"></span>\n "; } buffer += "<li>\n <div class=\"btn-group\">\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-action=\"change_view\" title=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.html)),stack1 == null || stack1 === false ? stack1 : stack1.edit)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n </div>\n</li>\n"; return buffer; }); this["wysihtml5"]["tpl"]["image"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { return "modal-sm"; } function program3(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } function program5(depth0,data) { return "\n <span class=\"fa fa-file-image-o\"></span>\n "; } function program7(depth0,data) { return "\n <span class=\"glyphicon glyphicon-picture\"></span>\n "; } buffer += "<li>\n <div class=\"bootstrap-wysihtml5-insert-image-modal modal fade\" data-wysihtml5-dialog=\"insertImage\">\n <div class=\"modal-dialog "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.smallmodals), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <a class=\"close\" data-dismiss=\"modal\">&times;</a>\n <h3>" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.image)),stack1 == null || stack1 === false ? stack1 : stack1.insert)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</h3>\n </div>\n <div class=\"modal-body\">\n <div class=\"form-group\">\n <input value=\"http://\" class=\"bootstrap-wysihtml5-insert-image-url form-control\" data-wysihtml5-dialog-field=\"src\">\n </div> \n </div>\n <div class=\"modal-footer\">\n <a class=\"btn btn-default\" data-dismiss=\"modal\" data-wysihtml5-dialog-action=\"cancel\" href=\"#\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.image)),stack1 == null || stack1 === false ? stack1 : stack1.cancel)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n <a class=\"btn btn-primary\" data-dismiss=\"modal\" data-wysihtml5-dialog-action=\"save\" href=\"#\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.image)),stack1 == null || stack1 === false ? stack1 : stack1.insert)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n </div>\n </div>\n </div>\n </div>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"insertImage\" title=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.image)),stack1 == null || stack1 === false ? stack1 : stack1.insert)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n</li>\n"; return buffer; }); this["wysihtml5"]["tpl"]["link"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { return "modal-sm"; } function program3(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } function program5(depth0,data) { return "\n <span class=\"fa fa-share-square-o\"></span>\n "; } function program7(depth0,data) { return "\n <span class=\"glyphicon glyphicon-share\"></span>\n "; } buffer += "<li>\n <div class=\"bootstrap-wysihtml5-insert-link-modal modal fade\" data-wysihtml5-dialog=\"createLink\">\n <div class=\"modal-dialog "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.smallmodals), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <a class=\"close\" data-dismiss=\"modal\">&times;</a>\n <h3>" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.link)),stack1 == null || stack1 === false ? stack1 : stack1.insert)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</h3>\n </div>\n <div class=\"modal-body\">\n <div class=\"form-group\">\n <input value=\"http://\" class=\"bootstrap-wysihtml5-insert-link-url form-control\" data-wysihtml5-dialog-field=\"href\">\n </div> \n <div class=\"checkbox\">\n <label> \n <input type=\"checkbox\" class=\"bootstrap-wysihtml5-insert-link-target\" checked>" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.link)),stack1 == null || stack1 === false ? stack1 : stack1.target)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </label>\n </div>\n </div>\n <div class=\"modal-footer\">\n <a class=\"btn btn-default\" data-dismiss=\"modal\" data-wysihtml5-dialog-action=\"cancel\" href=\"#\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.link)),stack1 == null || stack1 === false ? stack1 : stack1.cancel)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n <a href=\"#\" class=\"btn btn-primary\" data-dismiss=\"modal\" data-wysihtml5-dialog-action=\"save\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.link)),stack1 == null || stack1 === false ? stack1 : stack1.insert)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</a>\n </div>\n </div>\n </div>\n </div>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"createLink\" title=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.link)),stack1 == null || stack1 === false ? stack1 : stack1.insert)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n</li>\n"; return buffer; }); this["wysihtml5"]["tpl"]["lists"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "btn-" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); return buffer; } function program3(depth0,data) { return "\n <span class=\"fa fa-list-ul\"></span>\n "; } function program5(depth0,data) { return "\n <span class=\"glyphicon glyphicon-list\"></span>\n "; } function program7(depth0,data) { return "\n <span class=\"fa fa-list-ol\"></span>\n "; } function program9(depth0,data) { return "\n <span class=\"glyphicon glyphicon-th-list\"></span>\n "; } function program11(depth0,data) { return "\n <span class=\"fa fa-outdent\"></span>\n "; } function program13(depth0,data) { return "\n <span class=\"glyphicon glyphicon-indent-right\"></span>\n "; } function program15(depth0,data) { return "\n <span class=\"fa fa-indent\"></span>\n "; } function program17(depth0,data) { return "\n <span class=\"glyphicon glyphicon-indent-left\"></span>\n "; } buffer += "<li>\n <div class=\"btn-group\">\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"insertUnorderedList\" title=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.lists)),stack1 == null || stack1 === false ? stack1 : stack1.unordered)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"insertOrderedList\" title=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.lists)),stack1 == null || stack1 === false ? stack1 : stack1.ordered)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(9, program9, data),fn:self.program(7, program7, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"Outdent\" title=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.lists)),stack1 == null || stack1 === false ? stack1 : stack1.outdent)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n <a class=\"btn "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.size), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " btn-default\" data-wysihtml5-command=\"Indent\" title=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.locale)),stack1 == null || stack1 === false ? stack1 : stack1.lists)),stack1 == null || stack1 === false ? stack1 : stack1.indent)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" tabindex=\"-1\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.toolbar)),stack1 == null || stack1 === false ? stack1 : stack1.fa), {hash:{},inverse:self.program(17, program17, data),fn:self.program(15, program15, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </a>\n </div>\n</li>\n"; return buffer; });(function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define('bootstrap.wysihtml5', ['jquery', 'wysihtml5', 'bootstrap', 'bootstrap.wysihtml5.templates', 'bootstrap.wysihtml5.commands'], factory); } else { // Browser globals factory(jQuery, wysihtml5); // jshint ignore:line } }(function ($, wysihtml5) { 'use strict'; var bsWysihtml5 = function($, wysihtml5) { var templates = function(key, locale, options) { if(wysihtml5.tpl[key]) { return wysihtml5.tpl[key]({locale: locale, options: options}); } }; var Wysihtml5 = function(el, options) { this.el = el; var toolbarOpts = $.extend(true, {}, defaultOptions, options); for(var t in toolbarOpts.customTemplates) { if (toolbarOpts.customTemplates.hasOwnProperty(t)) { wysihtml5.tpl[t] = toolbarOpts.customTemplates[t]; } } this.toolbar = this.createToolbar(el, toolbarOpts); this.editor = this.createEditor(toolbarOpts); }; Wysihtml5.prototype = { constructor: Wysihtml5, createEditor: function(options) { options = options || {}; // Add the toolbar to a clone of the options object so multiple instances // of the WYISYWG don't break because 'toolbar' is already defined options = $.extend(true, {}, options); options.toolbar = this.toolbar[0]; this.initializeEditor(this.el[0], options); }, initializeEditor: function(el, options) { var editor = new wysihtml5.Editor(this.el[0], options); editor.on('beforeload', this.syncBootstrapDialogEvents); editor.on('beforeload', this.loadParserRules); // #30 - body is in IE 10 not created by default, which leads to nullpointer // 2014/02/13 - adapted to wysihtml5-0.4, does not work in IE if(editor.composer.editableArea.contentDocument) { this.addMoreShortcuts(editor, editor.composer.editableArea.contentDocument.body || editor.composer.editableArea.contentDocument, options.shortcuts); } else { this.addMoreShortcuts(editor, editor.composer.editableArea, options.shortcuts); } if(options && options.events) { for(var eventName in options.events) { if (options.events.hasOwnProperty(eventName)) { editor.on(eventName, options.events[eventName]); } } } return editor; }, loadParserRules: function() { if($.type(this.config.parserRules) === 'string') { $.ajax({ dataType: 'json', url: this.config.parserRules, context: this, error: function (jqXHR, textStatus, errorThrown) { console.log(errorThrown); }, success: function (parserRules) { this.config.parserRules = parserRules; console.log('parserrules loaded'); } }); } if(this.config.pasteParserRulesets && $.type(this.config.pasteParserRulesets) === 'string') { $.ajax({ dataType: 'json', url: this.config.pasteParserRulesets, context: this, error: function (jqXHR, textStatus, errorThrown) { console.log(errorThrown); }, success: function (pasteParserRulesets) { this.config.pasteParserRulesets = pasteParserRulesets; } }); } }, //sync wysihtml5 events for dialogs with bootstrap events syncBootstrapDialogEvents: function() { var editor = this; $.map(this.toolbar.commandMapping, function(value) { return [value]; }).filter(function(commandObj) { return commandObj.dialog; }).map(function(commandObj) { return commandObj.dialog; }).forEach(function(dialog) { dialog.on('show', function() { $(this.container).modal('show'); }); dialog.on('hide', function() { $(this.container).modal('hide'); setTimeout(editor.composer.focus, 0); }); $(dialog.container).on('shown.bs.modal', function () { $(this).find('input, select, textarea').first().focus(); }); }); this.on('change_view', function() { $(this.toolbar.container.children).find('a.btn').not('[data-wysihtml5-action="change_view"]').toggleClass('disabled'); }); }, createToolbar: function(el, options) { var self = this; var toolbar = $('<ul/>', { 'class' : 'wysihtml5-toolbar', 'style': 'display:none' }); var culture = options.locale || defaultOptions.locale || 'en'; if(!locale.hasOwnProperty(culture)) { console.debug('Locale \'' + culture + '\' not found. Available locales are: ' + Object.keys(locale) + '. Falling back to \'en\'.'); culture = 'en'; } var localeObject = $.extend(true, {}, locale.en, locale[culture]); for(var key in options.toolbar) { if(options.toolbar[key]) { toolbar.append(templates(key, localeObject, options)); } } toolbar.find('a[data-wysihtml5-command="formatBlock"]').click(function(e) { var target = e.delegateTarget || e.target || e.srcElement, el = $(target), showformat = el.data('wysihtml5-display-format-name'), formatname = el.data('wysihtml5-format-name') || el.html(); if(showformat === undefined || showformat === 'true') { self.toolbar.find('.current-font').text(formatname); } }); toolbar.find('a[data-wysihtml5-command="foreColor"]').click(function(e) { var target = e.target || e.srcElement; var el = $(target); self.toolbar.find('.current-color').text(el.html()); }); this.el.before(toolbar); return toolbar; }, addMoreShortcuts: function(editor, el, shortcuts) { /* some additional shortcuts */ wysihtml5.dom.observe(el, 'keydown', function(event) { var keyCode = event.keyCode, command = shortcuts[keyCode]; if ((event.ctrlKey || event.metaKey || event.altKey) && command && wysihtml5.commands[command]) { var commandObj = editor.toolbar.commandMapping[command + ':null']; if (commandObj && commandObj.dialog && !commandObj.state) { commandObj.dialog.show(); } else { wysihtml5.commands[command].exec(editor.composer, command); } event.preventDefault(); } }); } }; // these define our public api var methods = { resetDefaults: function() { $.fn.wysihtml5.defaultOptions = $.extend(true, {}, $.fn.wysihtml5.defaultOptionsCache); }, bypassDefaults: function(options) { return this.each(function () { var $this = $(this); $this.data('wysihtml5', new Wysihtml5($this, options)); }); }, shallowExtend: function (options) { var settings = $.extend({}, $.fn.wysihtml5.defaultOptions, options || {}, $(this).data()); var that = this; return methods.bypassDefaults.apply(that, [settings]); }, deepExtend: function(options) { var settings = $.extend(true, {}, $.fn.wysihtml5.defaultOptions, options || {}); var that = this; return methods.bypassDefaults.apply(that, [settings]); }, init: function(options) { var that = this; return methods.shallowExtend.apply(that, [options]); } }; $.fn.wysihtml5 = function ( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.wysihtml5' ); } }; $.fn.wysihtml5.Constructor = Wysihtml5; var defaultOptions = $.fn.wysihtml5.defaultOptions = { toolbar: { 'font-styles': true, 'color': false, 'emphasis': { 'small': true }, 'blockquote': true, 'lists': true, 'html': false, 'link': true, 'image': true, 'smallmodals': false }, useLineBreaks: false, parserRules: { classes: { 'wysiwyg-color-silver' : 1, 'wysiwyg-color-gray' : 1, 'wysiwyg-color-white' : 1, 'wysiwyg-color-maroon' : 1, 'wysiwyg-color-red' : 1, 'wysiwyg-color-purple' : 1, 'wysiwyg-color-fuchsia' : 1, 'wysiwyg-color-green' : 1, 'wysiwyg-color-lime' : 1, 'wysiwyg-color-olive' : 1, 'wysiwyg-color-yellow' : 1, 'wysiwyg-color-navy' : 1, 'wysiwyg-color-blue' : 1, 'wysiwyg-color-teal' : 1, 'wysiwyg-color-aqua' : 1, 'wysiwyg-color-orange' : 1 }, tags: { 'b': {}, 'i': {}, 'strong': {}, 'em': {}, 'p': {}, 'br': {}, 'ol': {}, 'ul': {}, 'li': {}, 'h1': {}, 'h2': {}, 'h3': {}, 'h4': {}, 'h5': {}, 'h6': {}, 'blockquote': {}, 'u': 1, 'img': { 'check_attributes': { 'width': 'numbers', 'alt': 'alt', 'src': 'url', 'height': 'numbers' } }, 'a': { 'check_attributes': { 'href': 'url' }, 'set_attributes': { 'target': '_blank', 'rel': 'nofollow' } }, 'span': 1, 'div': 1, 'small': 1, 'code': 1, 'pre': 1 } }, locale: 'en', shortcuts: { '83': 'small',// S '75': 'createLink'// K } }; if (typeof $.fn.wysihtml5.defaultOptionsCache === 'undefined') { $.fn.wysihtml5.defaultOptionsCache = $.extend(true, {}, $.fn.wysihtml5.defaultOptions); } var locale = $.fn.wysihtml5.locale = {}; }; bsWysihtml5($, wysihtml5); })); (function(wysihtml5) { wysihtml5.commands.small = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, "small"); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, "small"); } }; })(wysihtml5); /** * English translation for bootstrap-wysihtml5 */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define('bootstrap.wysihtml5.en-US', ['jquery', 'bootstrap.wysihtml5'], factory); } else { // Browser globals factory(jQuery); } }(function ($) { $.fn.wysihtml5.locale.en = $.fn.wysihtml5.locale['en-US'] = { font_styles: { normal: 'Normal text', h1: 'Heading 1', h2: 'Heading 2', h3: 'Heading 3', h4: 'Heading 4', h5: 'Heading 5', h6: 'Heading 6' }, emphasis: { bold: 'Bold', italic: 'Italic', underline: 'Underline', small: 'Small' }, lists: { unordered: 'Unordered list', ordered: 'Ordered list', outdent: 'Outdent', indent: 'Indent' }, link: { insert: 'Insert link', cancel: 'Cancel', target: 'Open link in new window' }, image: { insert: 'Insert image', cancel: 'Cancel' }, html: { edit: 'Edit HTML' }, colours: { black: 'Black', silver: 'Silver', gray: 'Grey', maroon: 'Maroon', red: 'Red', purple: 'Purple', green: 'Green', olive: 'Olive', navy: 'Navy', blue: 'Blue', orange: 'Orange' } }; }));
var Dotenv = require('dotenv-webpack'); module.exports = { entry: './src/main/js/app.jsx', devtool: 'sourcemaps', cache: true, mode: 'development', output: { path: __dirname, filename: './src/main/resources/static/built/bundle.js' }, node: { net: 'empty', }, module: { rules: [ { // test: path.join(__dirname, '.'), // exclude: /(node_modules)/, test: /\.jsx$/, use: [{ loader: 'babel-loader', options: { presets: ["@babel/preset-env", "@babel/preset-react"] } }] } ], }, plugins: [ new Dotenv() ] };
const jwt = require('jsonwebtoken'); const secret = process.env.NODE_ENV === 'production' ? process.env.JWT_SECRET : 'secret'; const authService = () => { const issue = payload => jwt.sign(payload, secret, { expiresIn: 10800 }); const verify = (token, cb) => jwt.verify(token, secret, {}, cb); return { issue, verify, }; }; module.exports = authService;
// Module dependencies const logger = require('../../config/logger'); const manager = require('./news.manager'); const rockol = require('../../sources/rockol/rockol.wrapper'); const rollingStone = require('../../sources/rollingstone/rollingstone.wrapper'); const soundsBlog = require('../../sources/soundsblog/soundsblog.wrapper'); const artistService = require('../artists/artists.service'); // Define how often to update the info (1 days) const VALIDITY = 1000 * 60 * 60 * 24; //Define the name of the sources const ROCKOL_NAME = 'Rockol'; const ROLLINGSTONE_NAME = 'RollingStone'; const SOUNDSBLOG_NAME = 'SoundsBlog'; // Export module functions module.exports.getNews = getNews; async function getNews(id) { try { let artist = await artistService.getArtist(id); let news = await manager.getNewsFromCache(artist); if (!news) { logger.verbose(`News for artist ${id} is not in cache`); news = await fetchNews(artist); await manager.saveNewsToCache(news); logger.verbose(`News for artist ${id} has been saved to cache`); } else if (new Date(news.updated) < Date.now() - VALIDITY) { logger.verbose(`News for artist ${id} is in cache but not up to date`); news = await fetchNews(artist); await manager.updateNewsInCache(news); logger.verbose(`News for artist ${id} has been updated in cache`); } return news; } catch (err) { logger.error(`Error occurred getting the artist ${id} - ${err}`); } } async function fetchNews(artist) { try { let rockolInfo,rollingstoneInfo, soundsblogInfo; [rockolInfo, rollingstoneInfo, soundsblogInfo] = await Promise.all([rockol.getArtistNews(artist.name), rollingStone.getArtistNews(artist.name), soundsBlog.getArtistNews(artist.name)]); for (let rockolNews of rockolInfo) { rockolNews.source = ROCKOL_NAME; } for (let rollingstoneNews of rollingstoneInfo) { rollingstoneNews.source = ROLLINGSTONE_NAME; } for (let soundsblogNews of soundsblogInfo) { soundsblogNews.source = SOUNDSBLOG_NAME; } let news = rockolInfo.concat(rollingstoneInfo).concat(soundsblogInfo).sort((news1, news2) => { return new Date(news2.date) - new Date(news1.date); }); return { artist : { id : artist.id, name : artist.name, }, news : news, updated : new Date(Date.now()) }; } catch (err) { logger.error(`Error occurred while fetching updated news about the artist ${artist.id} - ${err}`); } }
""" Dialogs that query users and verify the answer before accepting. Query is the generic base class for a popup dialog. The user must either enter a valid answer or close the dialog. Entries are validated when <Return> is entered or [Ok] is clicked. Entries are ignored when [Cancel] or [X] are clicked. The 'return value' is .result set to either a valid answer or None. Subclass SectionName gets a name for a new config file section. Configdialog uses it for new highlight theme and keybinding set names. Subclass ModuleName gets a name for File => Open Module. Subclass HelpSource gets menu item and path for additions to Help menu. """ # Query and Section name result from splitting GetCfgSectionNameDialog # of configSectionNameDialog.py (temporarily config_sec.py) into # generic and specific parts. 3.6 only, July 2016. # ModuleName.entry_ok came from editor.EditorWindow.load_module. # HelpSource was extracted from configHelpSourceEdit.py (temporarily # config_help.py), with darwin code moved from ok to path_ok. import importlib import os import shlex from sys import executable, platform # Platform is set for one test. from tkinter import Toplevel, StringVar, BooleanVar, W, E, S from tkinter.ttk import Frame, Button, Entry, Label, Checkbutton from tkinter import filedialog from tkinter.font import Font class Query(Toplevel): """Base class for getting verified answer from a user. For this base class, accept any non-blank string. """ def __init__(self, parent, title, message, *, text0='', used_names={}, _htest=False, _utest=False): """Create modal popup, return when destroyed. Additional subclass init must be done before this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ self.parent = parent # Needed for Font call. self.message = message self.text0 = text0 self.used_names = used_names Toplevel.__init__(self, parent) self.withdraw() # Hide while configuring, especially geometry. self.title(title) self.transient(parent) self.grab_set() windowingsystem = self.tk.call('tk', 'windowingsystem') if windowingsystem == 'aqua': try: self.tk.call('::tk::unsupported::MacWindowStyle', 'style', self._w, 'moveableModal', '') except: pass self.bind("<Command-.>", self.cancel) self.bind('<Key-Escape>', self.cancel) self.protocol("WM_DELETE_WINDOW", self.cancel) self.bind('<Key-Return>', self.ok) self.bind("<KP_Enter>", self.ok) self.create_widgets() self.update_idletasks() # Need here for winfo_reqwidth below. self.geometry( # Center dialog over parent (or below htest box). "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) self.resizable(height=False, width=False) if not _utest: self.deiconify() # Unhide now that geometry set. self.wait_window() def create_widgets(self, ok_text='OK'): # Do not replace. """Create entry (rows, extras, buttons. Entry stuff on rows 0-2, spanning cols 0-2. Buttons on row 99, cols 1, 2. """ # Bind to self the widgets needed for entry_ok or unittest. self.frame = frame = Frame(self, padding=10) frame.grid(column=0, row=0, sticky='news') frame.grid_columnconfigure(0, weight=1) entrylabel = Label(frame, anchor='w', justify='left', text=self.message) self.entryvar = StringVar(self, self.text0) self.entry = Entry(frame, width=30, textvariable=self.entryvar) self.entry.focus_set() self.error_font = Font(name='TkCaptionFont', exists=True, root=self.parent) self.entry_error = Label(frame, text=' ', foreground='red', font=self.error_font) # Display or blank error by setting ['text'] =. entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W) self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E, pady=[10,0]) self.entry_error.grid(column=0, row=2, columnspan=3, padx=5, sticky=W+E) self.create_extra() self.button_ok = Button( frame, text=ok_text, default='active', command=self.ok) self.button_cancel = Button( frame, text='Cancel', command=self.cancel) self.button_ok.grid(column=1, row=99, padx=5) self.button_cancel.grid(column=2, row=99, padx=5) def create_extra(self): pass # Override to add widgets. def showerror(self, message, widget=None): #self.bell(displayof=self) (widget or self.entry_error)['text'] = 'ERROR: ' + message def entry_ok(self): # Example: usually replace. "Return non-blank entry or None." entry = self.entry.get().strip() if not entry: self.showerror('blank line.') return None return entry def ok(self, event=None): # Do not replace. '''If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. ''' self.entry_error['text'] = '' entry = self.entry_ok() if entry is not None: self.result = entry self.destroy() else: # [Ok] moves focus. (<Return> does not.) Move it back. self.entry.focus_set() def cancel(self, event=None): # Do not replace. "Set dialog result to None and destroy tk widget." self.result = None self.destroy() def destroy(self): self.grab_release() super().destroy() class SectionName(Query): "Get a name for a config file section name." # Used in ConfigDialog.GetNewKeysName, .GetNewThemeName (837) def __init__(self, parent, title, message, used_names, *, _htest=False, _utest=False): super().__init__(parent, title, message, used_names=used_names, _htest=_htest, _utest=_utest) def entry_ok(self): "Return sensible ConfigParser section name or None." name = self.entry.get().strip() if not name: self.showerror('no name specified.') return None elif len(name)>30: self.showerror('name is longer than 30 characters.') return None elif name in self.used_names: self.showerror('name is already in use.') return None return name class ModuleName(Query): "Get a module name for Open Module menu entry." # Used in open_module (editor.EditorWindow until move to iobinding). def __init__(self, parent, title, message, text0, *, _htest=False, _utest=False): super().__init__(parent, title, message, text0=text0, _htest=_htest, _utest=_utest) def entry_ok(self): "Return entered module name as file path or None." name = self.entry.get().strip() if not name: self.showerror('no name specified.') return None # XXX Ought to insert current file's directory in front of path. try: spec = importlib.util.find_spec(name) except (ValueError, ImportError) as msg: self.showerror(str(msg)) return None if spec is None: self.showerror("module not found") return None if not isinstance(spec.loader, importlib.abc.SourceLoader): self.showerror("not a source-based module") return None try: file_path = spec.loader.get_filename(name) except AttributeError: self.showerror("loader does not support get_filename", parent=self) return None return file_path class HelpSource(Query): "Get menu name and help source for Help menu." # Used in ConfigDialog.HelpListItemAdd/Edit, (941/9) def __init__(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = 'Name for item on Help menu:' super().__init__( parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest) def create_extra(self): "Add path widjets to rows 10-12." frame = self.frame pathlabel = Label(frame, anchor='w', justify='left', text='Help File Path: Enter URL or browse for file') self.pathvar = StringVar(self, self.filepath) self.path = Entry(frame, textvariable=self.pathvar, width=40) browse = Button(frame, text='Browse', width=8, command=self.browse_file) self.path_error = Label(frame, text=' ', foreground='red', font=self.error_font) pathlabel.grid(column=0, row=10, columnspan=3, padx=5, pady=[10,0], sticky=W) self.path.grid(column=0, row=11, columnspan=2, padx=5, sticky=W+E, pady=[10,0]) browse.grid(column=2, row=11, padx=5, sticky=W+S) self.path_error.grid(column=0, row=12, columnspan=3, padx=5, sticky=W+E) def askfilename(self, filetypes, initdir, initfile): # htest # # Extracted from browse_file so can mock for unittests. # Cannot unittest as cannot simulate button clicks. # Test by running htest, such as by running this file. return filedialog.Open(parent=self, filetypes=filetypes)\ .show(initialdir=initdir, initialfile=initfile) def browse_file(self): filetypes = [ ("HTML Files", "*.htm *.html", "TEXT"), ("PDF Files", "*.pdf", "TEXT"), ("Windows Help Files", "*.chm"), ("Text Files", "*.txt", "TEXT"), ("All Files", "*")] path = self.pathvar.get() if path: dir, base = os.path.split(path) else: base = None if platform[:3] == 'win': dir = os.path.join(os.path.dirname(executable), 'Doc') if not os.path.isdir(dir): dir = os.getcwd() else: dir = os.getcwd() file = self.askfilename(filetypes, dir, base) if file: self.pathvar.set(file) item_ok = SectionName.entry_ok # localize for test override def path_ok(self): "Simple validity check for menu file path" path = self.path.get().strip() if not path: #no path specified self.showerror('no help file path specified.', self.path_error) return None elif not path.startswith(('www.', 'http')): if path[:5] == 'file:': path = path[5:] if not os.path.exists(path): self.showerror('help file path does not exist.', self.path_error) return None if platform == 'darwin': # for Mac Safari path = "file://" + path return path def entry_ok(self): "Return apparently valid (name, path) or None" self.path_error['text'] = '' name = self.item_ok() path = self.path_ok() return None if name is None or path is None else (name, path) class CustomRun(Query): """Get settings for custom run of module. 1. Command line arguments to extend sys.argv. 2. Whether to restart Shell or not. """ # Used in runscript.run_custom_event def __init__(self, parent, title, *, cli_args=[], _htest=False, _utest=False): """cli_args is a list of strings. The list is assigned to the default Entry StringVar. The strings are displayed joined by ' ' for display. """ message = 'Command Line Arguments for sys.argv:' super().__init__( parent, title, message, text0=cli_args, _htest=_htest, _utest=_utest) def create_extra(self): "Add run mode on rows 10-12." frame = self.frame self.restartvar = BooleanVar(self, value=True) restart = Checkbutton(frame, variable=self.restartvar, onvalue=True, offvalue=False, text='Restart shell') self.args_error = Label(frame, text=' ', foreground='red', font=self.error_font) restart.grid(column=0, row=10, columnspan=3, padx=5, sticky='w') self.args_error.grid(column=0, row=12, columnspan=3, padx=5, sticky='we') def cli_args_ok(self): "Validity check and parsing for command line arguments." cli_string = self.entry.get().strip() try: cli_args = shlex.split(cli_string, posix=True) except ValueError as err: self.showerror(str(err)) return None return cli_args def entry_ok(self): "Return apparently valid (cli_args, restart) or None" cli_args = self.cli_args_ok() restart = self.restartvar.get() return None if cli_args is None else (cli_args, restart) if __name__ == '__main__': from unittest import main main('idlelib.idle_test.test_query', verbosity=2, exit=False) from idlelib.idle_test.htest import run run(Query, HelpSource, CustomRun)
'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } /** * The variables 'firstInteger', 'firstDecimal', and 'firstString' are declared for you -- do not modify them. * Print three lines: * 1. The sum of 'firstInteger' and the Number representation of 'secondInteger'. * 2. The sum of 'firstDecimal' and the Number representation of 'secondDecimal'. * 3. The concatenation of 'firstString' and 'secondString' ('firstString' must be first). * * Parameter(s): * secondInteger - The string representation of an integer. * secondDecimal - The string representation of a floating-point number. * secondString - A string consisting of one or more space-separated words. **/ function performOperation(secondInteger, secondDecimal, secondString) { // Declare a variable named 'firstInteger' and initialize with integer value 4. const firstInteger = 4; // Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0. const firstDecimal = 4.0; // Declare a variable named 'firstString' and initialize with the string "HackerRank". const firstString = 'HackerRank '; // Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number type) on a new line. console.log(firstInteger + parseInt(secondInteger)); console.log(firstDecimal + parseFloat(secondDecimal)); console.log(firstString + secondString); // Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number type) on a new line. // Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The variable 'firstString' must be printed first. }
/** * @license AngularJS v1.3.10 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function() {'use strict'; /** * @description * * This object provides a utility for producing rich Error messages within * Angular. It can be called as follows: * * var exampleMinErr = minErr('example'); * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); * * The above creates an instance of minErr in the example namespace. The * resulting error will have a namespaced error code of example.one. The * resulting error will replace {0} with the value of foo, and {1} with the * value of bar. The object is not restricted in the number of arguments it can * take. * * If fewer arguments are specified than necessary for interpolation, the extra * interpolation markers will be preserved in the final string. * * Since data will be parsed statically during a build step, some restrictions * are applied with respect to how minErr instances are created and called. * Instances should have names of the form namespaceMinErr for a minErr created * using minErr('namespace') . Error codes, namespaces and template strings * should all be static strings, not variables or general expressions. * * @param {string} module The namespace to use for the new minErr instance. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning * error from returned function, for cases when a particular type of error is useful. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance */ function minErr(module, ErrorConstructor) { ErrorConstructor = ErrorConstructor || Error; return function() { var code = arguments[0], prefix = '[' + (module ? module + ':' : '') + code + '] ', template = arguments[1], templateArgs = arguments, message, i; message = prefix + template.replace(/\{\d+\}/g, function(match) { var index = +match.slice(1, -1), arg; if (index + 2 < templateArgs.length) { return toDebugString(templateArgs[index + 2]); } return match; }); message = message + '\nhttp://errors.angularjs.org/1.3.10/' + (module ? module + '/' : '') + code; for (i = 2; i < arguments.length; i++) { message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' + encodeURIComponent(toDebugString(arguments[i])); } return new ErrorConstructor(message); }; } /** * @ngdoc type * @name angular.Module * @module ng * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { var $injectorMinErr = minErr('$injector'); var ngMinErr = minErr('ng'); function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } var angular = ensure(window, 'angular', Object); // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap angular.$$minErr = angular.$$minErr || minErr; return ensure(angular, 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @module ng * @description * * The `angular.module` is a global place for creating, registering and retrieving Angular * modules. * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an * existing module (the name passed as the first argument to `module`) is retrieved. * * * # Module * * A module is a collection of services, directives, controllers, filters, and configuration information. * `angular.module` is used to configure the {@link auto.$injector $injector}. * * ```js * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(['$locationProvider', function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }]); * ``` * * Then you can create an injector and load your modules like this: * * ```js * var injector = angular.injector(['ng', 'myModule']) * ``` * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {!Array.<string>=} requires If specified then new module is being created. If * unspecified then the module is being retrieved for further configuration. * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } }; assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + "the module name or forgot to load it. If registering a module ensure that you " + "specify the dependencies as the second argument.", name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var configBlocks = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke', 'push', configBlocks); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _configBlocks: configBlocks, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @module ng * * @description * Holds the list of modules which the injector will load before the current module is * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @module ng * * @description * Name of the module. */ name: name, /** * @ngdoc method * @name angular.Module#provider * @module ng * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the * service. * @description * See {@link auto.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @module ng * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link auto.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @module ng * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link auto.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @module ng * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link auto.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @module ng * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @module ng * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an * animation. * @description * * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. * * * Defines an animation hook that can be later used with * {@link ngAnimate.$animate $animate} service and directives that use this service. * * ```js * module.animation('.animation-name', function($inject1, $inject2) { * return { * eventName : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction(element) { * //code to cancel the animation * } * } * } * }) * ``` * * See {@link ng.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ animation: invokeLater('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @module ng * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @module ng * @param {string|Object} name Controller name, or an object map of controllers where the * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @module ng * @param {string|Object} name Directive name, or an object map of directives where the * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @module ng * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. * For more about how to configure services, see * {@link providers#provider-recipe Provider Recipe}. */ config: config, /** * @ngdoc method * @name angular.Module#run * @module ng * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod, queue) { if (!queue) queue = invokeQueue; return function() { queue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; }; } }); }; }); } setupModuleLoader(window); })(window); /** * Closure compiler type information * * @typedef { { * requires: !Array.<string>, * invokeQueue: !Array.<Array.<*>>, * * service: function(string, Function):angular.Module, * factory: function(string, Function):angular.Module, * value: function(string, *):angular.Module, * * filter: function(string, Function):angular.Module, * * init: function(Function):angular.Module * } } */ angular.Module;
/* * Copyright 2018 TWO SIGMA OPEN SOURCE, 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. */ var BeakerXPageObject = require('../beakerx.po.js'); var beakerxPO; describe('Testing of table Actions ', function () { beforeAll(function () { beakerxPO = new BeakerXPageObject(); beakerxPO.runNotebookByUrl('/test/ipynb/groovy/TableMenuTest.ipynb'); }, 2); afterAll(function () { beakerxPO.closeAndHaltNotebook(); }); function getSubMenu(cellIndex, commandIndex){ var tblDisplay = beakerxPO.getTableDisplayByIndex(cellIndex); return beakerxPO.getTableIndexSubMenu(beakerxPO.getTableIndexMenu(tblDisplay), commandIndex)[0]; }; function getTableColumnMenu(cellIndex, x, y){ if(!x) { x = 50; } if(!y) { y = 10; } var tblDisplay = beakerxPO.getTableDisplayByIndex(cellIndex); tblDisplay.moveToObject('canvas', x, y); tblDisplay.leftClick('canvas', x, y); browser.waitUntil(function(){ var menu = browser.$('ul.dropdown-menu.bko-table-menu-content'); return menu != null && menu.isVisible(); }, 10000, 'column menu is not visible'); return browser.$('ul.dropdown-menu.bko-table-menu-content'); }; function checkColumnMenu(cellIndex, codeCell, menuName, fileName){ var colMenu = getTableColumnMenu(cellIndex); colMenu.click('[data-command="' + menuName + '"]'); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, 250, 150); beakerxPO.checkImageData(imageData.value, imageDir, fileName); }; function createColumnMenu(cellIndex, codeCell, menuName, fileName){ var colMenu = getTableColumnMenu(cellIndex); colMenu.click('[data-command="' + menuName + '"]'); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, 250, 150); beakerxPO.createTableImage(imageData.value, imageDir, fileName); }; var cellIndex; var imageDir = 'groovy/tableMenu'; describe('Show/Hide menu Items ', function () { var maxWidth; it('Should display table ', function () { cellIndex = 0; var width = 200, height = 100; var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); codeCell.moveToObject('canvas', 40, 40); browser.pause(500); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, width, height); beakerxPO.checkImageData(imageData.value, imageDir, 'cell1_case1.png'); }); it('Hide All Columns', function () { var tblDisplay = beakerxPO.getTableDisplayByIndex(cellIndex); maxWidth = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); var tableMenu = beakerxPO.getTableIndexMenu(tblDisplay); tableMenu.click('[data-command="Hide All Columns"]'); var minWidth = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); expect(maxWidth).toBeGreaterThan(minWidth); }); it('Show All Columns', function () { var tblDisplay = beakerxPO.getTableDisplayByIndex(cellIndex); var width_1 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); var tableMenu = beakerxPO.getTableIndexMenu(tblDisplay); tableMenu.click('[data-command="Show All Columns"]'); var width_2 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); expect(width_2).toBeGreaterThan(width_1); expect(maxWidth).toEqual(width_2); }); var subMenu; it('Hide "m3" column', function () { var width_1 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); subMenu = getSubMenu(cellIndex, 0).$$('li'); expect(subMenu.length).toEqual(11); expect(subMenu[0].getText()).toEqual('m3'); subMenu[0].click('div.fa.fa-check'); var width_2 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); expect(width_1).toBeGreaterThan(width_2); }); it('Hide all columns by checking submenu items', function () { var width_1 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); for(var i = 1; i < subMenu.length; i += 1){ subMenu[i].click('div.fa.fa-check'); } var width_2 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'width')); expect(width_1).toBeGreaterThan(width_2); }); }); describe('Menu option "Format"', function () { var width = 150, height = 150; it('Should format index column to "date"', function () { cellIndex += 2; beakerxPO.runCodeCellByIndex(cellIndex); var subMenu = getSubMenu(cellIndex, 1).$$('li'); expect(subMenu.length).toEqual(13); subMenu[8].click(); var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, width, height); beakerxPO.checkImageData(imageData.value, imageDir, 'cell2_case1.png'); }); it('Should format index column to "formatted integer"', function () { var subMenu = getSubMenu(cellIndex, 1).$$('li'); subMenu[2].click(); var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, width, height); beakerxPO.checkImageData(imageData.value, imageDir, 'cell2_case2.png'); }); }); describe('Menu option "Rows to show"', function () { it('Select "show 10 rows"', function () { beakerxPO.runCodeCellByIndex(cellIndex); var hight_1 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'height')); var subMenu = getSubMenu(cellIndex, 2).$$('li'); expect(subMenu.length).toEqual(5); subMenu[0].click(); var hight_2 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'height')); expect(hight_1).toBeGreaterThan(hight_2); }); it('Select "show All rows"', function () { var hight_1 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'height')); var subMenu = getSubMenu(cellIndex, 2).$$('li'); subMenu[4].click(); var hight_2 = parseInt(beakerxPO.getDataGridCssPropertyByIndex(cellIndex, 'height')); expect(hight_2).toBeGreaterThan(hight_1); }); }); describe('Menu option "Clear selection"', function () { var width = 250, height = 150; it('Should select values', function () { cellIndex += 3; var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); codeCell.leftClick('canvas', 60, 60); browser.keys('Shift'); codeCell.leftClick('canvas', 120, 120); browser.keys('\uE000'); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, width, height); beakerxPO.checkImageData(imageData.value, imageDir, 'cell3_case1.png'); }); it('Should clear selection', function () { var tblDisplay = beakerxPO.getTableDisplayByIndex(cellIndex); var tableMenu = beakerxPO.getTableIndexMenu(tblDisplay); tableMenu.click('[data-command="Clear selection"]'); var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, width, height); beakerxPO.checkImageData(imageData.value, imageDir, 'cell3_case2.png'); }); }); describe('Column menu option "Hide column"', function () { it('Should hide column', function () { cellIndex += 3; var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Hide column', 'cell4_case1.png'); }); }); describe('Column menu option "Sort Ascending"', function () { it('Should sort column', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Sort Ascending', 'cell4_case2.png'); }); }); describe('Column menu option "Sort Descending"', function () { it('Should sort column', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Sort Descending', 'cell4_case3.png'); }); }); describe('Column menu option "No Sort"', function () { it('Should display column without sorting', function () { var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'No Sort', 'cell4_case4.png'); }); }); describe('Column menu option "Align Left"', function () { it('Should align to the left', function () { var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Align Left', 'cell4_case5.png'); }); }); describe('Column menu option "Align Center"', function () { it('Should align to the center', function () { var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Align Center', 'cell4_case6.png'); }); }); describe('Column menu option "Align Right"', function () { it('Should align to the right', function () { var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Align Right', 'cell4_case7.png'); }); }); describe('Column menu option "Heatmap"', function () { it('Should display Heatmap in column', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Heatmap', 'cell4_case8.png'); }); }); describe('Column menu option "Data Bars"', function () { it('Should display Data Bars in column', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Data Bars', 'cell4_case9.png'); }); }); describe('Column menu option "Color by unique"', function () { it('Should display Color by unique in column', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Color by unique', 'cell4_case10.png'); }); }); describe('Column menu option "Reset formatting"', function () { it('Should reset formatting for column', function () { var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Reset formatting', 'cell4_case11.png'); }); }); describe('Column menu option "Fix Left"', function () { it('Should Fix Left column', function () { var codeCell = beakerxPO.getCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Fix Left', 'cell4_case12.png'); }); }); describe('Column menu option "Move column to front"', function () { it('Should move column to front', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); var colMenu = getTableColumnMenu(cellIndex, 230, 10); colMenu.click('[data-command="Move column to front"]'); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, 250, 150); beakerxPO.checkImageData(imageData.value, imageDir, 'cell4_case13.png'); }); }); describe('Column menu option "Move column to end"', function () { it('Should move column to end', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); checkColumnMenu(cellIndex, codeCell, 'Move column to end', 'cell4_case14.png'); }); }); describe('Column menu option "Format double with precision is 2"', function () { it('Should format double with precision is 2', function () { cellIndex += 5; var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); var colMenu = getTableColumnMenu(cellIndex); var subMenu1 = beakerxPO.getTableIndexSubMenu(colMenu, 0)[0]; var subMenu2 = beakerxPO.getTableIndexSubMenu(subMenu1, 0)[1]; subMenu2.click('li[data-command="precision_2"]'); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, 250, 150); beakerxPO.checkImageData(imageData.value, imageDir, 'cell5_case1.png'); }); }); describe('Column menu option "Search for Substring"', function () { it('Should select values with "9"', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); var colMenu = getTableColumnMenu(cellIndex); colMenu.click('[data-command="Search for Substring"]'); var input = codeCell.$$('div.p-Widget.input-clear-growing')[0].$('input'); input.click(); browser.keys('9'); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, 250, 115); beakerxPO.checkImageData(imageData.value, imageDir, 'cell5_case2.png'); }); }); describe('Index menu option "Search for Substring"', function () { it('Should select index with "9"', function () { var codeCell = beakerxPO.runCodeCellByIndex(cellIndex); var tblDisplay = beakerxPO.getTableDisplayByIndex(cellIndex); var tableMenu = beakerxPO.getTableIndexMenu(tblDisplay); tableMenu.click('[data-command="Search for Substring"]'); var input = codeCell.$$('div.p-Widget.input-clear-growing')[11].$('input'); input.click(); browser.keys('9'); var canvas = codeCell.$('canvas'); var imageData = beakerxPO.getCanvasImageData(canvas, 250, 65); beakerxPO.checkImageData(imageData.value, imageDir, 'cell5_case3.png'); }); }); });
var a = require("../lib/actions") var sq = require("../lib/spawnQueue") var motion = require("../lib/motion") const u = require("../lib/utils") const settings = require("../config/settings") var rM = { name: "remoteMiner", type: "miner", /** @param {Creep} creep **/ run: function(creep) { if(creep.spawning){ return } if(creep.ticksToLive == creep.memory.spawnBuffer + (creep.body.length * CREEP_SPAWN_TIME) && Game.spawns[creep.memory.city].memory.remoteMiner > 0) { sq.respawn(creep) } if(creep.hits < creep.hitsMax && creep.pos.roomName == Game.spawns[creep.memory.city].pos.roomName){ Game.spawns[creep.memory.city].memory.towersActive = true motion.newMove(creep, Game.spawns[creep.memory.city].pos, 7) return } if(!creep.memory.source) { rM.nextSource(creep) return } const source = Game.getObjectById(creep.memory.source) rM.setMoveStatus(creep) rM.maybeMove(creep, source) if(!source) return if(creep.memory.construction && rM.build(creep, source)) return if(creep.memory.link){ const link = Game.getObjectById(creep.memory.link) if(link){ if(source.energy > 0 && creep.store.getFreeCapacity() > 0) creep.harvest(source) if(!creep.store.getFreeCapacity()) a.charge(creep, link) return } else { creep.memory.link = null } } else if(creep.memory.container){ const container = Game.getObjectById(creep.memory.container) if(container){ if(container.hits < container.hitsMax * 0.3 && creep.store.getUsedCapacity() > 0 && !creep.store.getFreeCapacity()){ creep.repair(container) } else if(source.energy > 0 && (container.store.getFreeCapacity() > 0 || creep.store.getFreeCapacity() > 0)){ creep.harvest(source) } else if (container.hits < container.hitsMax * 0.9 && creep.store.getUsedCapacity() > 0){ creep.repair(container) } } else { creep.memory.container = null } } else if(source.energy > 0){ creep.harvest(source) } if(Game.time % settings.minerUpdateTime == 0){ if(creep.pos.isNearTo(source.pos) && !creep.memory.spawnBuffer){ creep.memory.spawnBuffer = PathFinder.search(Game.spawns[creep.memory.city].pos, source.pos).cost } //update container/link status //if we have a link no need to search if(creep.memory.link && Game.getObjectById(creep.memory.link)) return //get Destination assigns structures/sites anyway so might as well reuse rM.getDestination(creep, source) if(!creep.memory.link && !creep.memory.container && !creep.memory.construction && creep.body.length > 5) rM.placeContainer(creep, source) } }, placeContainer: function(creep, source){ const spawn = Game.spawns[creep.memory.city] if(spawn.memory.sources[source.id][STRUCTURE_CONTAINER + "Pos"]){ const pos = spawn.memory.sources[source.id][STRUCTURE_CONTAINER + "Pos"] source.room.createConstructionSite(Math.floor(pos/50), pos%50, STRUCTURE_CONTAINER) return } if(creep.memory.miningPos || creep.memory.destination){ const pos = creep.memory.miningPos || creep.memory.destination if(creep.pos.isEqualTo(new RoomPosition(pos.x, pos.y, pos.roomName))){ spawn.memory.sources[source.id][STRUCTURE_CONTAINER + "Pos"] = creep.pos.x * 50 + creep.pos.y creep.pos.createConstructionSite(STRUCTURE_CONTAINER) } } }, build: function (creep, source){ const cSite = Game.getObjectById(creep.memory.construction) if(!cSite){ creep.memory.construction = null return false } if(creep.store.getUsedCapacity() > creep.store.getCapacity()/2){ creep.build(cSite) } else { creep.harvest(source) } return true }, maybeMove: function(creep, source){ if(creep.memory.moveStatus == "static"){ if(!source){ creep.memory.destination = creep.memory.sourcePos return } if(!creep.memory.destination || new RoomPosition(creep.memory.destination.x, creep.memory.destination.y, creep.memory.destination.roomName).isEqualTo(creep.memory.sourcePos.x, creep.memory.sourcePos.y)) creep.memory.destination = rM.getDestination(creep, source) return } if(!source){ motion.newMove(creep, new RoomPosition(creep.memory.sourcePos.x, creep.memory.sourcePos.y, creep.memory.sourcePos.roomName), 1) return } if(!creep.memory.miningPos){ creep.memory.miningPos = rM.getDestination(creep, source) if(!creep.memory.miningPos) return } const miningPos = new RoomPosition(creep.memory.miningPos.x, creep.memory.miningPos.y, creep.memory.miningPos.roomName) if(!creep.pos.isEqualTo(miningPos)) motion.newMove(creep, miningPos) }, getLinkMiningPos: function(link, source){ for(let i = link.pos.x - 1; i <= link.pos.x + 1; i++){ for(let j = link.pos.y - 1; j <= link.pos.y + 1; j++){ const testPos = new RoomPosition(i, j, link.pos.roomName) if(testPos.isNearTo(source) && !rM.isPositionBlocked(testPos)) return testPos } } return null }, getDestination: function(creep, source) { //look for links const link = rM.findStruct(creep, source, STRUCTURE_LINK) if(link){ creep.memory.link = link.id return rM.getLinkMiningPos(link, source) } const linkSite = rM.findStruct(creep, source, STRUCTURE_LINK, true) if(linkSite){ creep.memory.construction = linkSite.id return rM.getLinkMiningPos(linkSite, source) } //look for containers const container = rM.findStruct(creep, source, STRUCTURE_CONTAINER) if(container){ creep.memory.container = container.id return container.pos } const containerSite = rM.findStruct(creep, source, STRUCTURE_CONTAINER, true) if(containerSite){ creep.memory.construction = containerSite.id return containerSite.pos } //look for empty space to mine for(let i = source.pos.x - 1; i <= source.pos.x + 1; i++){ for(let j = source.pos.y - 1;j <= source.pos.y + 1; j++){ if(!rM.isPositionBlocked(new RoomPosition(i, j, source.pos.roomName))) return new RoomPosition(i, j, source.pos.roomName) } } }, findStruct: function(creep, source, structureType, construction = false){ const type = construction ? LOOK_CONSTRUCTION_SITES : LOOK_STRUCTURES const memory = Game.spawns[creep.memory.city].memory const structPos = memory.sources[source.id][structureType + "Pos"] if(structPos){ const realPos = new RoomPosition(Math.floor(structPos/50), structPos%50, source.pos.roomName) const look = realPos.lookFor(type) const structure = _.find(look, struct => struct.structureType == structureType && (!struct.owner || struct.my)) if(structure) return structure } return null }, isPositionBlocked: function(roomPos){ const look = roomPos.look() for(const lookObject of look){ if((lookObject.type == LOOK_TERRAIN && lookObject[LOOK_TERRAIN] == "wall")//no constant for wall atm || (lookObject.type == LOOK_STRUCTURES && OBSTACLE_OBJECT_TYPES[lookObject[LOOK_STRUCTURES].structureType])) { return true } } return false }, setMoveStatus: function(creep) { if(!creep.memory.moveStatus) creep.memory.moveStatus = creep.getActiveBodyparts(MOVE) ? "mobile" : "static" }, canCarry: function(creep){ return creep.getActiveBodyparts(CARRY) > 0 }, harvestTarget: function(creep) { var source = Game.getObjectById(creep.memory.source) if(!creep.pos.inRangeTo(source, 2)){ motion.newMove(creep, source.pos, 2) return } if (creep.body.length === 15 && creep.pos.isNearTo(source) && Game.time % 2 === 0) { return } if(a.harvest(creep, source) === 1 && !creep.memory.spawnBuffer){ creep.memory.spawnBuffer = PathFinder.search(Game.spawns[creep.memory.city].pos, source.pos).cost } }, /** pick a target id for creep **/ nextSource: function(creep) { var city = creep.memory.city var miners = _.filter(u.splitCreepsByCity()[city], c => c.memory.role === rM.name && c.ticksToLive > (c.memory.spawnBuffer || 50)) var occupied = [] _.each(miners, function(minerInfo){ occupied.push(minerInfo.memory.source) }) const sourceMap = Game.spawns[city].memory.sources || {} var sources = Object.keys(sourceMap) var openSources = _.filter(sources, Id => !occupied.includes(Id)) if (openSources.length){ creep.memory.source = openSources[0] creep.memory.sourcePos = Game.spawns[city].memory.sources[openSources[0]] } } } module.exports = rM
const merge = require('webpack-merge'); const distCommonWebpackConfig = require('./webpack.dist.common.conf'); module.exports = merge(distCommonWebpackConfig, { entry: { "/lib.rem/actionsheet/index": "./src/components/actionsheet/index.js", "/lib.rem/badge/index": "./src/components/badge/index.js", "/lib.rem/button/index": "./src/components/button/index.js", "/lib.rem/cell/index": "./src/components/cell/index.js", "/lib.rem/cityselect/index": "./src/components/cityselect/index.js", "/lib.rem/dialog/index": "./src/components/dialog/index.js", "/lib.rem/grids/index": "./src/components/grids/index.js", "/lib.rem/icons/index": "./src/components/icons/index.js", "/lib.rem/infinitescroll/index": "./src/components/infinitescroll/index.js", "/lib.rem/keyboard/index": "./src/components/keyboard/index.js", "/lib.rem/layout/index": "./src/components/layout/index.js", "/lib.rem/list/index": "./src/components/list/index.js", "/lib.rem/navbar/index": "./src/components/navbar/index.js", "/lib.rem/progressbar/index": "./src/components/progressbar/index.js", "/lib.rem/pullrefresh/index": "./src/components/pullrefresh/index.js", "/lib.rem/scrolltab/index": "./src/components/scrolltab/index.js", "/lib.rem/sendcode/index": "./src/components/sendcode/index.js", "/lib.rem/slider/index": "./src/components/slider/index.js", "/lib.rem/spinner/index": "./src/components/spinner/index.js", "/lib.rem/switch/index": "./src/components/switch/index.js", "/lib.rem/tab/index": "./src/components/tab/index.js", "/lib.rem/tabbar/index": "./src/components/tabbar/index.js", "/lib.rem/countup/index": "./src/components/countup/index.js", "/lib.rem/popup/index": "./src/components/popup/index.js", "/lib.rem/rate/index": "./src/components/rate/index.js", "/lib.rem/countdown/index": "./src/components/countdown/index.js", "/lib.rem/textarea/index": "./src/components/textarea/index.js", "/lib.rem/rollnotice/index": "./src/components/rollnotice/index.js", "/lib.rem/input/index": "./src/components/input/index.js", "/lib.rem/flexbox/index": "./src/components/flexbox/index.js", "/lib.rem/radio/index": "./src/components/radio/index.js", "/lib.rem/checkbox/index": "./src/components/checkbox/index.js", "/lib.rem/backtop/index": "./src/components/backtop/index.js", "/lib.rem/accordion/index": "./src/components/accordion/index.js", "/lib.rem/datetime/index": "./src/components/datetime/index.js", "/lib.rem/lightbox/index": "./src/components/lightbox/index.js", "/lib.rem/timeline/index": "./src/components/timeline/index.js", "/lib.rem/step/index": "./src/components/step/index.js", "/lib.rem/checklist/index": "./src/components/checklist/index.js", "/lib.rem/search/index": "./src/components/search/index.js", "/lib.rem/scrollnav/index": "./src/components/scrollnav/index.js", "/lib.rem/preview/index": "./src/components/preview/index.js", "/lib.rem/imagepreview/index": "./src/components/imagepreview/index.js", } });
(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI AreaSelector 1.0.0 * https://github.com/borgboyone/jquery-ui-areaselector * * Copyright 2019 Anthony Wells * Released under the MIT license. * https://raw.githubusercontent.com/borgboyone/jquery-ui-areaselector/master/LICENSE * * http://borgboyone.github.io/jquery-ui-areaselector/ */ var areaSelector = $.widget('aw.areaSelector', $.ui.mouse, { version: '1.0.0', options: { 'disabled': false, 'appendTo': "self", 'visible': true, 'aspectRatio': null, 'selection': null, // initialSelection 'unscaledSize': null, 'minSelectionSize': null, 'maxSelectionSize': null, 'enableKeyboard': false, 'hideMask': false, /* callbacks */ 'start': null, 'resize': null, 'drag': null, 'stop': null, 'move': null }, /** Mouse Functions **/ _mouseCapture: function( event ) { return !this.options.disabled && this.capture; }, _mouseDown: function( event ) { if (this.options.disabled) return false; this.capture = !( this.helper.find('.ui-areaselector-selectedarea')[0] === event.target || $.contains( this.helper.find('.ui-areaselector-selectedarea')[0], event.target ) ) && ( event.which === 1 ); if (this.capture) { this.temporarySelection = this.selection; // this.proxy = true? this._processSelection( {x:Math.round((event.pageX - this.position.left - this.gutter.left) / this.scaleX), y:Math.round((event.pageY - this.position.top - this.gutter.left) / this.scaleY), width:1, height:1} ); this._updateUI(); this.helper.find('.ui-areaselector-selectedarea').focus(); this.pageX = event.pageX; this.pageY = event.pageY; } return this._super( event ); }, // if _mouseUp and capture && not _mouseStart, selection to null? or if capture capture = true? _mouseStart: function( event ) { event.pageX = event.pageX - this.pageX + (this.selection.width + this.selection.x) - (this.pageX - this.position.left - this.gutter.left); // difference between areaWidth and displacedWidth from mouseDown ((selection.width + selection.x) - this.pageX) event.pageY = event.pageY - this.pageY + (this.selection.height + this.selection.y) - (this.pageY - this.position.top - this.gutter.top); event.target = this.helper.find('.ui-areaselector-selectedarea'); var resizable = event.target.resizable('instance'); resizable.axis = 'se'; // might be able to set this based on the difference compared to this.selection.height, etc... // in case they don't move the mouse! So _mouseStart would look for proxyOriginalSelection, which it will delete this.proxyOriginalSelection = this.temporarySelection; delete this.temporarySelection; return resizable._mouseStart(event); }, _mouseDrag: function( event ) { event.pageX = event.pageX - this.pageX; event.pageY = event.pageY - this.pageY; event.target = this.helper.find('.ui-areaselector-selectedarea'); return event.target.resizable('instance')._mouseDrag(event); }, _mouseStop: function( event ) { this.capture = false; // should this be true? event.pageX = event.pageX - this.pageX; event.pageY = event.pageY - this.pageY; event.target = this.helper.find('.ui-areaselector-selectedarea'); return event.target.resizable('instance')._mouseStop(event); }, /** UI Widget Functions **/ _create: function() { this._super(); // validate options (there is no easy way to validate the user supplied options alone in the jquery ui widget framework) // overriding _createWidget would allow for this but it's not guaranteed that this function will be available this.processedOptions = this._validateOptions( this.options ); this.appendTo = !this.options.appendTo || this.options.appendTo === "self" ? this.element : (this.options.appendTo === "parent" ? this.element.parent() : $(this.options.appendTo)); // Wrap appendTo if it cannot hold child nodes if ( this.appendTo[ 0 ].nodeName.match( /^(canvas|textarea|input|select|button|img)$/i ) ) { this.appendToWrapped = this.appendTo; this.appendTo = this._wrap( this.appendTo ); } // set-up working environment variables this._setUpEnvironment(); this.element.addClass("ui-areaselector"); // create UI and initialize UI elements based on options this._createUI(); this.originalElement = this.element; this.element = this.helper; this._updateUI(); // set-up resizable and draggable var areaSelector = this; this.helper.find('.ui-areaselector-selectedarea') .resizable({ disabled:this.disabled, containment:"parent", handles:"all", classes:null, aspectRatio: this.aspectRatio ? this.aspectRatio['width'] / this.aspectRatio['height'] : false, minWidth: this.minSelectionSize && this.minSelectionSize['width'] ? this.minSelectionSize['width'] : null, minHeight: this.minSelectionSize && this.minSelectionSize['height'] ? this.minSelectionSize['height'] : null, // we don't need start if we set up the mask in mouseDown (verify this) We'll still need the trigger start: function( event, ui ) { areaSelector.originalSelection = 'proxyOriginalSelector' in areaSelector ? areaSelector.proxyOriginalSelector : areaSelector.selection; delete areaSelector.proxyOriginalSelector; var selection = {'x': ui.position['left'], 'y': ui.position['top'], 'width': ui.size['width'], 'height': ui.size['height']}; if (areaSelector._trigger("start", event, {action:"resize", selection:selection, originalSelection:areaSelector.originalSelection}) === false) return false; areaSelector.originalElement.addClass('ui-areaselector-selecting'); areaSelector.selection = selection; areaSelector._updateUI(true); }, resize: function( event, ui ) { var selection = {'x': ui.position['left'], 'y': ui.position['top'], 'width': Math.max(ui.size['width'], 0), 'height': Math.max(ui.size['height'], 0)}; // should we get the result from _trigger before updating the UI? Allow for false and then cancel? if (areaSelector._trigger("resize", event, {action:"resize", selection:selection, originalSelection:areaSelector.originalSelection}) === false) return false; areaSelector.selection = selection; areaSelector._updateUI(true); }, stop: function(event, ui ) { if (areaSelector._trigger("stop", event, {action:"resize", selection:areaSelector.selection, originalSelection:areaSelector.originalSelection}) === false) return false; areaSelector.originalElement.removeClass('ui-areaselector-selecting'); if ((areaSelector.selection['width'] === 0) || (areaSelector.selection['height'] === 0)) { areaSelector.selection = null; areaSelector._updateUI(); } } }) .draggable({ disabled:this.disabled, containment:"parent", cursor:"move", start: function( event, ui ) { areaSelector.originalSelection = areaSelector.selection; var selection = {'x': ui.position['left'], 'y': ui.position['top'], 'width': areaSelector.selection['width'], 'height': areaSelector.selection['height']}; if (areaSelector._trigger("start", event, {action:"drag", selection:selection, originalSelection:areaSelector.originalSelection}) === false) return false; areaSelector.originalElement.addClass('ui-areaselector-selecting'); areaSelector.selection = selection; areaSelector._updateUI(true); }, drag: function( event, ui ) { var selection = {'x': ui.position['left'], 'y': ui.position['top'], 'width': areaSelector.selection['width'], 'height': areaSelector.selection['height']}; if (areaSelector._trigger("drag", event, {action:"drag", selection:selection, originalSelection:areaSelector.originalSelection}) === false) return false; areaSelector.selection = selection; areaSelector._updateUI(true); }, stop: function( event, ui ) { if (areaSelector._trigger("stop", event, {action:"drag", selection:areaSelector.selection, originalSelection:areaSelector.originalSelection}) === false) return false; areaSelector.originalElement.removeClass('ui-areaselector-selecting'); } }); this._mouseInit(); if (this.options.enableKeyboard) { var keyHandler = function(event) { // return false if the keyCode doesn't match the events we handle if ( ![$.ui.keyCode.ESCAPE, $.ui.keyCode.UP, $.ui.keyCode.DOWN, $.ui.keyCode.LEFT, $.ui.keyCode.RIGHT].includes(event.keyCode) ) return false; var active = this.originalElement.is(".ui-areaselector-selecting"); if ((active && [$.ui.keyCode.UP, $.ui.keyCode.DOWN, $.ui.keyCode.LEFT, $.ui.keyCode.RIGHT].includes(event.keyCode)) || (!active && [$.ui.keyCode.ESCAPE].includes(event.keyCode))) return false; if ( event.keyCode === $.ui.keyCode.ESCAPE ) { this.cancel(); return true; } var x = this.selection['x'], y = this.selection['y'], handled = false; switch(event.keyCode) { case $.ui.keyCode.UP: if (this.selection['y'] > 0) { y = Math.max(this.selection['y'] - 1, 0); handled = true; } break; case $.ui.keyCode.DOWN: if (this.selection['y'] < this.height - this.selection['height']) { y = Math.min(this.selection['y'] + 1, this.height - this.selection['height']); handled = true; } break; case $.ui.keyCode.LEFT: if (this.selection['x'] > 0) { x = Math.max(this.selection['x'] - 1, 0); handled = true; } break; case $.ui.keyCode.RIGHT: if (this.selection['x'] < this.width - this.selection['width']) { x = Math.min(this.selection['x'] + 1, this.width - this.selection['width']); handled = true; } break; } if (handled) { var selection = {'x': x, 'y': y, 'width': this.selection['width'], 'height': this.selection['height']}; if (this._trigger('move', event, {action: 'move', selection: selection, originalSelection: this.selection}) !== false) { this.selection = selection; this._updateUI(); return true; } } return false; }; // should we allow the selector to be focusable regardless? what about ui-focusable? Check that // also mouseDown should make areSelector have the focus in this case this._on(this.helper.find('.ui-areaselector-selectedarea'), { 'keydown':function (event) { if (keyHandler.call(this, event)) { event.preventDefault(); event.stopPropagation(); } } }); } if (this.options.visible) this._setOptionVisible(true); }, _destroy: function() { var selectedArea = this.helper.find('.ui-areaselector-selectedarea'); selectedArea.draggable('instance').destroy(); // not really necessary selectedArea.resizable('instance').destroy(); // not really necessary this.helper = this.helper.remove(); if (this.appendToWrapped) this._unwrap( this.appendToWrapped ); this.element = this.originalElement; this.element.removeClass('ui-areaselector'); this._super(); }, _setOption: function( key, value ) { //this._validateOption? this._super(key, value); if ( key === "visible" ) this._setOptionVisible( value ); else if ( key === "hideMask" ) this._setOptionHideMask( value ); }, _setOptionDisabled: function( value ) { this._super(); var selectedArea = this.helper.find('.ui-areaselector-selectedarea'); if ( value ) { this.stop(); selectedArea.draggable('instance').disable(); selectedArea.resizable('instance').disable(); } else { selectedArea.draggable('instance').enable(); selectedArea.resizable('instance').enable(); } }, _setOptionVisible: function( value ) { if ( value ) { this.helper.css('visibility', 'visible'); } else { this.stop(); this.helper.css('visibility', 'hidden'); } }, _setOptionHideMask: function( value ) { if ( value ) { this._addClass(this.helper, 'ui-areaselector-hidemask'); } else { this._removeClass(this.helper, 'ui-areaselector-hidemask'); } }, /** Publically Accessible Functions **/ enable: function() { return this._setOptions( { disabled: false } ); }, disable: function() { return this._setOptions( { disabled: true } ); }, show: function() { return this._setOptions( { visible: true } ); }, hide: function() { return this._setOptions( { visible: false } ); }, area: function(selection) { if (typeof selection !== "undefined") { this.stop(); if (selection === null) { this.selection = null; } else { this._processSelection(this._validateSelection(selection)); // this.options.skipOptionValidation ? selection : this._validate... } this._updateUI(); return this; } else { return this.selection === null ? null : {x:this.selection['x'] / this.scaleX, y:this.selection['y'] / this.scaleY, width:this.selection['width'] / this.scaleX, height:this.selection['height'] / this.scaleY}; } }, stop: function() { if (this.originalElement.is(".ui-areaselector-selecting")) { // selecting()? var selectedArea = this.helper.find('.ui-areaselector-selectedarea'); if (selectedArea.is(".ui-resizable-resizing")) { selectedArea.resizable('instance').cancel(); } else if (selectedArea.is(".ui-draggable-dragging")) { selectedArea.draggable('instance').cancel(); } // CHECK: if (this.capture) we may need to issue mouseUp here this.capture = false; this.originalElement.removeClass("ui-areaselector-selecting"); } }, cancel: function() { if (this.originalElement.is(".ui-areaselector-selecting")) { this.stop(); this.selection = this.originalSelection; this._updateUI(); } return this; }, refresh: function( options ) { var isDisabled = !!this.options.disabled, isVisible = !!this.options.visible; // this.stop(); redundant if (!isDisabled) this.disable(); if (isVisible) this.hide(); //this.selection = null; // not necessary if ( options ) { this.processedOptions = $.extend(this.processedOptions, this._validateOptions(options)); } this._setUpEnvironment(); this._updateOverlay(); this._updateUI(); if (!isDisabled) this.enable(); if (isVisible) this.show(); return this; }, resize: function() { var origProcessedSelectionOption = this.processedOptions['selection']; // if size hasn't changed should we return? this.stop(); this.processedOptions['selection'] = this.area(); this._setUpEnvironment(); this._updateOverlay(); // not expected for resize, but for consistency this._updateUI(); this.processedOptions['selection'] = origProcessedSelectionOption; return this; }, /** Area Selector Specific Internal Functions **/ _validateOptions: function( o ) { var po = {}; // appendTo if (!o.appendTo) throw new Error("Option 'appendTo' must be a non empty value"); if (!((o.appendTo === "self") || (o.appendTo === "parent")) && ($(o.appendTo).length === 0)) throw new Error("No DOM element matching option 'appendTo' found in the document"); // aspectRatio if (o.aspectRatio) { if (typeof o.aspectRatio === "string") { if (/^\d+:\d+$/.test(o.aspectRatio)) { var values = o.aspectRatio.split(":"); po.aspectRatio = {width:parseInt(values[0]), height:parseInt(values[1])}; } else throw new Error("Option 'aspectRatio' must be of the form integer:integer"); } else if ( (typeof o.aspecRatio === "object") && !Array.isArray(o.aspectRatio)) { if (!(('width' in o.aspectRatio) && this._isStrictPositiveInteger(o.aspectRatio['width']) && (o.aspectRatio['width'] > 0) && ('height' in o.aspectRatio) && this._isStrictPositiveInteger(o.aspectRatio['height']) && (o.aspectRatio['height'] > 0))) throw new Error("Option 'aspectRatio' must contain both 'width' and 'height' properties with positive integer values greater than zero"); po.aspectRatio = {width: o.aspectRatio['width'] + 0, height: o.aspectRatio['height'] + 0}; } else if ( typeof o.aspectRatio === "number" ) { if (o.aspectRatio <= 0 ) throw new Error("Option 'aspectRatio' must be larger than 0"); po.aspectRatio = {width: o.aspectRatio + 0, height: 1}; } else throw new Error("Unknown format for provided option 'aspectRatio'"); } else { po.aspectRatio = null; } // unscaledSize if (o.unscaledSize) { if ( !((typeof o.unscaledSize == "object") && ('width' in o.unscaledSize) && ('height' in o.unscaledSize) && this._isStrictPositiveInteger(o.unscaledSize['width']) && this._isStrictPositiveInteger(o.unscaledSize['height']) && (o.unscaledSize['width'] > 0) && (o.unscaledSize['height'] > 0)) ) throw new Error("Option 'unscaledSize' must contain both 'width' and 'height' properties with positive integer values greater than zero"); po.unscaledSize = {width:o.unscaledSize['width'] + 0, height:o.unscaledSize['height'] + 0}; } else { po.unscaledSize = null; } // initialSelection po.selection = this._validateSelection( o.selection ); // minSelectionSize if (o.minSelectionSize) { // width or height may be omitted, must not be larger than unscaledSize (if provided) if (!((typeof o.minSelectionSize === "object") && (('width' in o.minSelectionSize) || ('height' in o.minSelectionSize))) || ((('width' in o.minSelectionSize) && !this._isStrictInteger(o.minSelectionSize['width'])) || (('height' in o.minSelectionSize) && !this._isStrictInteger(o.minSelectionSize['height'])))) throw new Error("Option 'minSelectionSize' must contain either of or both 'width' and 'height' properties with positive integer values"); po.minSelectionSize = {width:'width' in o.minSelectionSize ? o.minSelectionSize['width'] + 0 : null, height:'height' in o.minSelectionSize ? o.minSelectionSize['height'] + 0 : null}; if (po.aspectRatio && po.minSelectionSize['width'] && po.minSelectionSize['height'] && ((po.aspectRatio['width'] / po.aspectRatio['height']) != (po.minSelectionSize['width'] / po.minSelectionSize['height']))) { po.minSelectionSize = this._adjustForAspectRatio(po.minSelectionSize, "smallest_exterior"); console.warn("Option 'minSelectionSize' width and height does not match provided 'aspectRatio'. Adjusting accordingly."); } if (po.unscaledSize && ('width' in po.minSelectionSize) && (po.minSelectionSize['width'] > po.unscaledSize['width'])) throw new Error("Option 'minSelectionSize.width' cannot be larger than 'unscaledSize.width"); if (po.unscaledSize && ('height' in po.minSelectionSize) && (po.minSelectionSize['height'] > po.unscaledSize['height'])) throw new Error("Option 'minSelectionSize.height' cannot be larger than 'unscaledSize.height"); } else { po.minSelectionSize = null; } // maxSelectionSize if (o.maxSelectionSize) { // width or height may be omitted must not be less than minSelectionSize if (!((typeof o.maxSelectionSize === "object") && (('width' in o.maxSelectionSize) || ('height' in o.maxSelectionSize))) || ((('width' in o.maxSelectionSize) && !this._isStrictPositiveInteger(o.maxSelectionSize['width'])) || (('height' in o.maxSelectionSize) && !this._isStrictPositiveInteger(o.maxSelectionSize['height'])))) throw new Error("Option 'maxSelectionSize' must contain either of or both 'width' and 'height' properties with positive integer values"); po.maxSelectionSize = {width:'width' in o.maxSelectionSize ? o.maxSelectionSize['width'] + 0 : null, height:'height' in o.maxSelectionSize ? o.maxSelectionSize['height'] + 0: null}; if (po.minSelectionSize && (po.minSelectionSize['width']) && (po.maxSelectionSize['width']) && (po.minSelectionSize['width'] > po.maxSelectionSize['width'])) throw new Error("Option 'minSelectionSize.width' cannot be larger than 'maxSelectionSize.width"); if (po.minSelectionSize && (po.minSelectionSize['height']) && (po.maxSelectionSize['height']) && (po.minSelectionSize['height'] > po.maxSelectionSize['height'])) throw new Error("Option 'minSelectionSize.height' cannot be larger than 'maxSelectionSize.height"); } return po; }, _validateSelection: function( selection ) { if (selection) { if (typeof selection === "string") { if (!['auto', 'none'].includes(selection)) throw new Error("Option 'initialSelection' must be one of 'auto', or 'none'"); return selection; } else if ( (typeof selection === "object") && !Array.isArray(selection) ) { if ( !(('x' in selection) && this._isStrictInteger(selection['x']) && ('y' in selection) && this._isStrictInteger(selection['y']) && ('width' in selection) && this._isStrictInteger(selection['width']) && ('height' in selection) && this._isStrictInteger(selection['height'])) ) throw new Error("Option 'initialSelection' must contain 'x', 'y', 'width' and 'height' properties with positive integer values"); return {'x': selection['x'] + 0, 'y': selection['y'] + 0, 'width': selection['width'] + 0, 'height': selection['height'] + 0}; } else throw new Error("Unknown format for provided option 'initialSelection'"); } return null; }, _setUpEnvironment: function() { var o = this.processedOptions; this.position = this.appendTo.position(); this.gutter = {left: (parseFloat(this.appendTo.css('border-left-width')) || 0) + (parseFloat(this.appendTo.css('margin-left')) || 0), top: (parseFloat(this.appendTo.css('border-top-width')) || 0) + (parseFloat(this.appendTo.css('margin-top')) || 0)}; this.width = this.appendTo.innerWidth(); this.height = this.appendTo.innerHeight(); this.scaleX = o.unscaledSize ? this.width / o.unscaledSize['width'] : 1; this.scaleY = o.unscaledSize ? this.height / o.unscaledSize['height'] : 1; this.minSelectionSize = o.minSelectionSize ? {'width': o.minSelectionSize['width'] ? Math.min(this.width, o.minSelectionSize['width'] * this.scaleX) : null, 'height': o.minSelectionSize['height'] ? Math.min(this.height, o.minSelectionSize['height'] * this.scaleY) : null} : null; if (!o.unscaledSize) { if (this.minSelectionSize['width'] && (this.minSelectionSize['width'] > this.width)) { console.warn("Option 'minSelectionSize.width' is larger than the current width. Dropping 'minSelectionSize.width'."); this.minSelectionSize['width'] = null; } if (this.minSelectionSize['height'] && (this.minSelectionSize['height'] > this.height)) { console.warn("Option 'minSelectionSize.height' is larger than the current height. Dropping 'minSelectionSize.height'."); this.minSelectionSize['height'] = null; } } this.aspectRatio = o.aspectRatio; if (this.aspectRatio) { if (this.minSelectionSize['width'] && (this.minSelectionSize['width'] / this.aspectRatio['width'] * this.aspectRatio['height'] > this.height)) { console.warn("Option 'minSelectionSize.width' in conjunction with the provided 'aspectRatio' results in a value that is larger than the current height. Dropping 'minSelectionSize.width'."); this.minSelectionSize['height'] = null; } if (this.minSelectionSize['height'] && (this.minSelectionSize['height'] / this.aspectRatio['height'] * this.aspectRatio['width'] > this.width)) { console.warn("Option 'minSelectionSize.height' in conjunction with the provided 'aspectRatio' results in a value that is larger than the current width. Dropping 'minSelectionSize.height'."); this.minSelectionSize['height'] = null; } } this.maxSelectionSize = o.maxSize ? {'width': o.maxSize['width'] ? o.maxSize['width'] * this.scaleX : null, 'height': o.maxSize['height'] ? o.maxSize['height'] * this.scaleY : null} : null; this._processSelection(o.selection); }, _processSelection: function( selection ) { if ( selection ) { if ( selection === 'auto' && this.aspectRatio === null ) { this.selection = {'x':0,'y':0,'width':this.width,'height':this.height}; } else if ( (selection === 'auto') ) { // autoCrop based on aspectRatio var largestRectangle = this._adjustForAspectRatio( {width:this.width, height:this.height} ); this.selection = {'x': (this.width - largestRectangle['width']) / 2, 'y': (this.height - largestRectangle['height']) / 2, 'width': largestRectangle['width'], 'height': largestRectangle['height']}; } else if (selection == 'none') { this.selection = null; } else { var x = Math.max(Math.min(selection['x'] * this.scaleX, this.width), 0), y = Math.max(Math.min(selection['y'] * this.scaleY, this.height), 0), width = Math.max(this.minSelectionSize ? this.minSelectionSize['width'] : 0, Math.min(this.maxSelectionSize ? this.maxSelectionSize['width'] : Infinity, selection['width'] * this.scaleX)), height = Math.max(this.minSelectionSize ? this.minSelectionSize['height'] : 0, Math.min(this.maxSelectionSize ? this.maxSelectionSize['height'] : Infinity, selection['height'] * this.scaleY)); // , this.width - o.selection['x'] * this.scaleX if ( x + width > this.width ) { width = Math.max(this.minSelectionSize ? this.minSelectionSize['width'] : 0, this.width - x); x = this.width - width; /*<= adjusts x for minSelectionSize and truncates*/ } if ( y + height > this.height ) { height = Math.max(this.minSelectionSize ? this.minSelectionSize['height'] : 0, this.height - y); y = this.height - height; } if (this.aspectRatio) { var temp = this._adjustForAspectRatio( {width: width, height: height}, "smallest_exterior" ); width = temp['width']; height = temp['height']; if (width > this.width) { width = this.width; height = this.aspectRatio['height'] / this.aspectRatio['width'] * width; x = 0; } else if (x + width > this.width) { x = this.width - width; } if (height > this.height) { height = this.height; width = this.aspectRatio['width'] / this.aspectRatio['height'] * height; y = 0; } else if (y + height > this.height) { y = this.height - height; } } this.selection = {'x':x, 'y':y, 'width':width, 'height':height}; } } else this.selection = null; return this.selection; }, _adjustForAspectRatio: function( size, method ) { if ( !method ) method = "largest_interior"; var arw = this.aspectRatio['width'], arh = this.aspectRatio['height'], width = size['width'], height = size['height']; if ( method === "largest_interior") { if (arh * width > arw * height) { width = height * arw / arh; } else if (arh * width < arw * height) { height = width * arh / arw; } } else { // smallest_exterior or smallest_encapsulating if (arh * width > arw * height) { height = width * arh / arw; } else if (arh * width < arw * height) { width = height * arw / arh; } } return {width:width, height:height}; }, _createUI: function() { var helper = $( '<div class="ui-areaselector-overlay' + (this.options.hideMask ? ' ui-areaselector-hidemask' : '') + '" style="position:absolute;visibility:hidden;width:' + this.width + 'px;height:' + this.height + 'px;">' + '<div class="ui-areaselector-selectedarea" style="display:none;"></div>' + '<div class="ui-areaselector-mask ui-areaselector-mask-top"></div>' + '<div class="ui-areaselector-mask ui-areaselector-mask-left"></div>' + '<div class="ui-areaselector-mask ui-areaselector-mask-right"></div>' + '<div class="ui-areaselector-mask ui-areaselector-mask-bottom"></div>' + '</div>'); if ( !(/^relative|absolute|fixed$/).test(this.appendTo.css('position')) ) helper.css({left: this.position.left, top: this.position.top, 'margin-left': this.gutter.left, 'margin-top': this.gutter.top}); // allow selectedarea to be focusable /*this._focusable(*/helper.find('.ui-areaselector-selectedarea').attr('tabindex', -1)/*)*/; this.helper = helper.appendTo(this.appendTo); }, _updateOverlay: function() { if ( !(/^relative|absolute|fixed$/).test(this.helper.parent().css('position')) ) this.helper.css({left: this.position.left, top: this.position.top, 'margin-left': this.gutter.left, 'margin-top': this.gutter.top}); }, // call this to initialize the UI as well! _updateUI: function( maskOnly ) { if (this.selection === null) { if ( !maskOnly ) { this.helper.find('.ui-areaselector-selectedarea').hide(); } this.helper .find('.ui-areaselector-mask-top').css({left:'0', top:'0', width:'0', height:'0'}).end() .find('.ui-areaselector-mask-left').css({left:'0', top:'0', width:'0', height:'0'}).end() .find('.ui-areaselector-mask-right').css({left:'0', top:'0', width:'0', height:'0'}).end() .find('.ui-areaselector-mask-bottom').css({left:'0', top: '0', width:'0', height:'0'}); } else { var selection = this.selection; if ( !maskOnly ) { this.helper.find('.ui-areaselector-selectedarea').css({left:selection.x, top:selection.y, width:selection.width, height:selection.height}).show(); } this.helper .find('.ui-areaselector-mask-top').css({left:'0', top:'0', width:this.width, height:selection.y}).end() .find('.ui-areaselector-mask-left').css({left:'0', top:selection.y, width:selection.x, height:selection.height}).end() .find('.ui-areaselector-mask-right').css({left:(selection.width + selection.x), top:selection.y, width: (this.width - (selection.width + selection.x)), height:selection.height}).end() .find('.ui-areaselector-mask-bottom').css({left:'0', top: (selection.y + selection.height), width:this.width, height: (this.height - (selection.y + selection.height))}); } }, _wrap: function( element ) { var wrapper = element.wrap( $( "<div class='ui-wrapper' style='overflow: hidden;'></div>" ).css( { position: element.css( "position" ), width: element.outerWidth(), height: element.outerHeight(), top: element.css( "top" ), left: element.css( "left" ) } ) ).parent(), margins = { marginTop: element.css( "marginTop" ), marginRight: element.css( "marginRight" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ) }; wrapper.css( margins ); element.css( "margin", 0 ); return wrapper; }, _unwrap: function ( element ) { var wrapper = element.parent(), margins = { marginTop: wrapper.css( "marginTop" ), marginRight: wrapper.css( "marginRight" ), marginBottom: wrapper.css( "marginBottom" ), marginLeft: wrapper.css( "marginLeft" ) }; element.css( { position: wrapper.css( "position" ), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css( "top" ), left: wrapper.css( "left" ) } ); element.unwrap().css( margins ); }, _isStrictInteger: function( value ) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; //return !isNaN( parseInt( value )); }, _isStrictPositiveInteger: function( value ) { return this._isStrictInteger( value ) && value >= 0; } }); }));
from setuptools import setup setup( name="timekeeper", version="0.1.1", description="Send runtime measurements of your code to InfluxDB", author="Torsten Rehn", author_email="torsten@rehn.email", license="ISC", url="https://github.com/trehn/timekeeper", keywords=["profiling", "profile", "metrics", "instrumentation", "measure", "influxdb"], classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: ISC License (ISCL)", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Monitoring", ], install_requires=[ "influxdb >= 2.0.0", ], py_modules=['timekeeper'], )
/* * /MathJax/jax/element/mml/optable/BasicLatin.js * * Copyright (c) 2009-2013 The MathJax Consortium * * 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. */ (function(a){var c=a.mo.OPTYPES;var b=a.TEXCLASS;MathJax.Hub.Insert(a.mo.prototype,{OPTABLE:{prefix:{"||":[0,0,b.BIN,{fence:true,stretchy:true,symmetric:true}],"|||":[0,0,b.ORD,{fence:true,stretchy:true,symmetric:true}]},postfix:{"!!":[1,0,b.BIN],"'":c.ACCENT,"++":[0,0,b.BIN],"--":[0,0,b.BIN],"..":[0,0,b.BIN],"...":c.ORD,"||":[0,0,b.BIN,{fence:true,stretchy:true,symmetric:true}],"|||":[0,0,b.ORD,{fence:true,stretchy:true,symmetric:true}]},infix:{"!=":c.BIN4,"&&":c.BIN4,"**":[1,1,b.BIN],"*=":c.BIN4,"+=":c.BIN4,"-=":c.BIN4,"->":c.BIN5,"//":[1,1,b.BIN],"/=":c.BIN4,":=":c.BIN4,"<=":c.BIN5,"<>":[1,1,b.BIN],"==":c.BIN4,">=":c.BIN5,"@":c.ORD11,"||":[2,2,b.BIN,{fence:true,stretchy:true,symmetric:true}],"|||":[2,2,b.ORD,{fence:true,stretchy:true,symmetric:true}]}}});MathJax.Ajax.loadComplete(a.optableDir+"/BasicLatin.js")})(MathJax.ElementJax.mml);
var Users = function () { grid = null; responseUsers = []; return { init: function() { grid = new Datatable(); grid.init({ src: $("#users-table"), onSuccess: function (e) { }, onError: function (e) { }, loadingMessage: "Loading...", dataTable: { "columns": [ { "data": "name" }, { "data": "email" }, { "data": "access_level" }, { "data": "null" } ], ajax: { url: "/auth/list?level=0", data: null, dataSrc: function (response) { console.log(response) responseUsers = response.data; return response.data; } }, "columnDefs": [{ "searchable": false, "orderable": false, "targets": 0 }], } }); var t = grid.getDataTable(); var drowElem = this.drowtableElements; grid.getTable().on('draw.dt', function () { drowElem(t); }); }, drowtableElements: function (t) { if (!t) { return; } var isAutorized = $.Auth.isAutorized(); if (isAutorized) { t.column(3).nodes().each(function (cell, i) { var user = responseUsers[i]; var edit_button = '<a href="/users/_update_user?id=' + user["id"] + '" class="btn btn-sm btn-circle btn-default btn-editable"><i class="fa fa-edit"></i></a>'; var disable_button = '<a href="#" class="btn btn-sm btn-circle btn-default btn-editable delete" data-id="' + user["id"] + '"><i class="fa fa-close"></i></a>'; cell.innerHTML = edit_button + disable_button; }); } }, reloadTable: function () { grid.getDataTable().ajax.url("/auth/list").load(); }, bindEvents: function () { $("#users-table").on("click", "a.delete", function (event) { event.preventDefault(); var button = $(this); var id = button.attr("data-id"); var data = { id: id } $("#ajax").modal("show"); $.ajax({ type: "POST", beforeSend: function (request) { request.setRequestHeader("_Autorize", $.Auth.getAuthCookie()); }, url: "/auth/delete/", data: JSON.stringify(data) }).done(function () { $("#ajax").modal("hide"); Users.reloadTable(); }); }); } } }(); var Main = function () { grid = null; responseUsers = []; return { init: function () { grid = new Datatable(); grid.init({ src: $("#mains-table"), onSuccess: function (e) { }, onError: function (e) { }, loadingMessage: "Loading...", dataTable: { "columns": [ { "data": "name" }, { "data": "email" }, { "data": "access_level" }, { "data": "null" } ], ajax: { url: "/auth/list?level=1", data: null, dataSrc: function (response) { console.log(response) responseUsers = response.data; return response.data; } }, "columnDefs": [{ "searchable": false, "orderable": false, "targets": 0 }], } }); var t = grid.getDataTable(); var drowElem = this.drowtableElements; grid.getTable().on('draw.dt', function () { drowElem(t); }); }, drowtableElements: function (t) { if (!t) { return; } var isAutorized = $.Auth.isAutorized(); if (isAutorized) { t.column(3).nodes().each(function (cell, i) { var user = responseUsers[i]; var edit_button = '<a href="/users/_update_main?id=' + user["id"] + '" class="btn btn-sm btn-circle btn-default btn-editable"><i class="fa fa-edit"></i></a>'; var binded_button = '<a href="/users/_binded?id=' + user["id"] + '&level=0" class="btn btn-sm btn-circle btn-default btn-editable"><i class="fa fa-user"></i></a>'; var disable_button = '<a href="#" class="btn btn-sm btn-circle btn-default btn-editable delete" data-id="' + user["id"] + '"><i class="fa fa-close"></i></a>'; cell.innerHTML = binded_button + edit_button + disable_button; }); } }, reloadTable: function () { grid.getDataTable().ajax.url("/auth/list").load(); }, bindEvents: function () { $("#mains-table").on("click", "a.delete", function (event) { event.preventDefault(); var button = $(this); var id = button.attr("data-id"); var data = { id: id } $("#ajax").modal("show"); $.ajax({ type: "POST", beforeSend: function (request) { request.setRequestHeader("_Autorize", $.Auth.getAuthCookie()); }, url: "/auth/delete/", data: JSON.stringify(data) }).done(function () { $("#ajax").modal("hide"); Users.reloadTable(); }); }); } } }(); var Managers = function () { grid = null; responseUsers = []; return { init: function () { grid = new Datatable(); grid.init({ src: $("#managers-table"), onSuccess: function (e) { }, onError: function (e) { }, loadingMessage: "Loading...", dataTable: { "columns": [ { "data": "name" }, { "data": "email" }, { "data": "access_level" }, { "data": "null" } ], ajax: { url: "/auth/list?level=2", data: null, dataSrc: function (response) { console.log(response) responseUsers = response.data; return response.data; } }, "columnDefs": [{ "searchable": false, "orderable": false, "targets": 0 }], } }); var t = grid.getDataTable(); var drowElem = this.drowtableElements; grid.getTable().on('draw.dt', function () { drowElem(t); }); }, drowtableElements: function (t) { if (!t) { return; } var isAutorized = $.Auth.isAutorized(); if (isAutorized) { t.column(3).nodes().each(function (cell, i) { var user = responseUsers[i]; var edit_button = '<a href="/users/_update?id=' + user["id"] + '" class="btn btn-sm btn-circle btn-default btn-editable"><i class="fa fa-edit"></i></a>'; var binded_button = '<a href="/users/_binded?id=' + user["id"] + '&level=1" class="btn btn-sm btn-circle btn-default btn-editable"><i class="fa fa-user"></i></a>'; var disable_button = '<a href="#" class="btn btn-sm btn-circle btn-default btn-editable delete" data-id="' + user["id"] + '"><i class="fa fa-close"></i></a>'; cell.innerHTML = binded_button + edit_button + disable_button; }); } }, reloadTable: function () { grid.getDataTable().ajax.url("/auth/list").load(); }, bindEvents: function () { $("#mains-table").on("click", "a.delete", function (event) { event.preventDefault(); var button = $(this); var id = button.attr("data-id"); var data = { id: id } $("#ajax").modal("show"); $.ajax({ type: "POST", beforeSend: function (request) { request.setRequestHeader("_Autorize", $.Auth.getAuthCookie()); }, url: "/auth/delete/", data: JSON.stringify(data) }).done(function () { $("#ajax").modal("hide"); Users.reloadTable(); }); }); } } }(); jQuery(document).ready(function () { Users.init(); Users.bindEvents(); Main.init(); Main.bindEvents(); Managers.init(); Managers.bindEvents(); });
""" Copyright (c) 2015-2022 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from collections import namedtuple import json from pathlib import Path from typing import Any, Dict from atomic_reactor.plugins.fetch_docker_archive import FetchDockerArchivePlugin from atomic_reactor.plugins.add_help import AddHelpPlugin import koji import koji_cli.lib import os import requests from atomic_reactor.plugins.gather_builds_metadata import GatherBuildsMetadataPlugin from atomic_reactor.plugins.koji_import import KojiImportPlugin, KojiImportSourceContainerPlugin from atomic_reactor.plugins.rpmqa import RPMqaPlugin from atomic_reactor.plugins.add_filesystem import AddFilesystemPlugin from atomic_reactor.plugins.fetch_sources import PLUGIN_FETCH_SOURCES_KEY from atomic_reactor.plugin import PluginFailedException from atomic_reactor.inner import DockerBuildWorkflow, TagConf from atomic_reactor.util import (ManifestDigest, DockerfileImages, get_manifest_media_version, graceful_chain_get, RegistryClient) from atomic_reactor.source import GitSource, PathSource from atomic_reactor.constants import (IMAGE_TYPE_DOCKER_ARCHIVE, KOJI_BTYPE_OPERATOR_MANIFESTS, PLUGIN_ADD_FILESYSTEM_KEY, PLUGIN_EXPORT_OPERATOR_MANIFESTS_KEY, PLUGIN_MAVEN_URL_SOURCES_METADATA_KEY, PLUGIN_GROUP_MANIFESTS_KEY, PLUGIN_KOJI_PARENT_KEY, PLUGIN_RESOLVE_COMPOSES_KEY, BASE_IMAGE_KOJI_BUILD, PARENT_IMAGES_KOJI_BUILDS, BASE_IMAGE_BUILD_ID_KEY, PLUGIN_PIN_OPERATOR_DIGESTS_KEY, PLUGIN_PUSH_OPERATOR_MANIFESTS_KEY, PLUGIN_RESOLVE_REMOTE_SOURCE, PLUGIN_VERIFY_MEDIA_KEY, PARENT_IMAGE_BUILDS_KEY, PARENT_IMAGES_KEY, OPERATOR_MANIFESTS_ARCHIVE, REMOTE_SOURCE_TARBALL_FILENAME, REMOTE_SOURCE_JSON_FILENAME, MEDIA_TYPE_DOCKER_V2_SCHEMA2, MEDIA_TYPE_DOCKER_V2_MANIFEST_LIST, KOJI_BTYPE_REMOTE_SOURCE_FILE, KOJI_KIND_IMAGE_BUILD, KOJI_KIND_IMAGE_SOURCE_BUILD, KOJI_SUBTYPE_OP_APPREGISTRY, KOJI_SUBTYPE_OP_BUNDLE, KOJI_SOURCE_ENGINE, DOCKERFILE_FILENAME, REPO_CONTAINER_CONFIG, PLUGIN_CHECK_AND_SET_PLATFORMS_KEY, PLUGIN_FETCH_MAVEN_KEY) from atomic_reactor.utils.flatpak_util import FlatpakUtil from tests.flatpak import (MODULEMD_AVAILABLE, setup_flatpak_composes, setup_flatpak_compose_info) from tests.mock_env import MockEnv from tests.util import add_koji_map_in_workflow from tests.constants import OSBS_BUILD_LOG_FILENAME from flexmock import flexmock import pytest import subprocess from osbs.api import OSBS from osbs.exceptions import OsbsException from osbs.utils import ImageName LogEntry = namedtuple('LogEntry', ['platform', 'line']) NAMESPACE = 'mynamespace' PIPELINE_RUN_NAME = 'test-pipeline-run' SOURCES_FOR_KOJI_NVR = 'component-release-version' SOURCES_SIGNING_INTENT = 'some_intent' REMOTE_SOURCE_FILE_FILENAME = 'pnc-sources.tar.gz' PUSH_OPERATOR_MANIFESTS_RESULTS = { "endpoint": 'registry.url/endpoint', "registryNamespace": 'test_org', "repository": 'test_repo', "release": 'test_release', } class X(object): pass class MockedPodResponse(object): def get_container_image_ids(self): return {'buildroot:latest': '0123456'} class MockedClientSession(object): TAG_TASK_ID = 1234 DEST_TAG = 'images-candidate' def __init__(self, hub, opts=None, task_states=None): self.metadata: Dict[str, Any] = {} # destination filename on Koji => file content self.uploaded_files: Dict[str, bytes] = {} self.build_tags = {} self.task_states = task_states or ['OPEN'] self.task_states = list(self.task_states) self.task_states.reverse() self.tag_task_state = self.task_states.pop() self.getLoggedInUser = lambda: {'name': 'osbs'} self.blocksize = None self.server_dir = None self.refunded_build = False self.fail_state = None def krb_login(self, principal=None, keytab=None, proxyuser=None): return True def ssl_login(self, cert, ca, serverca, proxyuser=None): return True def logout(self): pass def uploadWrapper(self, localfile, path, name=None, callback=None, blocksize=1048576, overwrite=True): self.blocksize = blocksize with open(localfile, 'rb') as fp: self.uploaded_files[name] = fp.read() def CGImport(self, metadata, server_dir, token=None): # metadata cannot be defined in __init__ because tests assume # the attribute will not be defined unless this method is called self.metadata = metadata # pylint: disable=attribute-defined-outside-init self.server_dir = server_dir return {"id": "123"} def getBuildTarget(self, target): return {'dest_tag_name': self.DEST_TAG} def getTaskInfo(self, task_id, request=False): assert task_id == self.TAG_TASK_ID # For extra code coverage, imagine Koji denies the task ever # existed. if self.tag_task_state is None: return None return {'state': koji.TASK_STATES[self.tag_task_state], 'owner': 1234} def getUser(self, user_id): return {'name': 'osbs'} def taskFinished(self, task_id): try: self.tag_task_state = self.task_states.pop() except IndexError: # No more state changes pass return self.tag_task_state in ['CLOSED', 'FAILED', 'CANCELED', None] FAKE_SIGMD5 = b'0' * 32 FAKE_RPM_OUTPUT = ( b'name1;1.0;1;x86_64;0;' + FAKE_SIGMD5 + b';(none);' b'RSA/SHA256, Mon 29 Jun 2015 13:58:22 BST, Key ID abcdef01234567\n' b'gpg-pubkey;01234567;01234567;(none);(none);(none);(none);(none)\n' b'gpg-pubkey-doc;01234567;01234567;noarch;(none);' + FAKE_SIGMD5 + b';(none);(none)\n' b'name2;2.0;2;x86_64;0;' + FAKE_SIGMD5 + b';' + b'RSA/SHA256, Mon 29 Jun 2015 13:58:22 BST, Key ID bcdef012345678;(none)\n' b'\n') FAKE_OS_OUTPUT = 'fedora-22' REGISTRY = 'docker.example.com' def fake_subprocess_output(cmd): if cmd.startswith('/bin/rpm'): return FAKE_RPM_OUTPUT elif 'os-release' in cmd: return FAKE_OS_OUTPUT else: raise RuntimeError class MockedPopen(object): def __init__(self, cmd, *args, **kwargs): self.cmd = cmd def wait(self): return 0 def communicate(self): return (fake_subprocess_output(self.cmd), '') def fake_Popen(cmd, *args, **kwargs): return MockedPopen(cmd, *args, **kwargs) def fake_digest(image): tag = image.to_str(registry=False) return 'sha256:{0:032x}'.format(len(tag)) def is_string_type(obj): return isinstance(obj, str) class MockResponse(object): def __init__(self, build_json=None): self.json = build_json def get_annotations(self): return graceful_chain_get(self.json, "metadata", "annotations") class BuildInfo(object): def __init__(self, help_file=None, help_valid=True, media_types=None, digests=None): self.annotations = {} if media_types: self.annotations['media-types'] = json.dumps(media_types) if help_valid: self.annotations['help_file'] = json.dumps(help_file) if digests: digest_annotation = [] for digest_item in digests: digest_annotation_item = { "version": get_manifest_media_version(digest_item), "digest": digest_item.default, } digest_annotation.append(digest_annotation_item) self.annotations['digests'] = json.dumps(digest_annotation) self.build = MockResponse({'metadata': {'annotations': self.annotations}}) def mock_reactor_config(workflow, allow_multiple_remote_sources=False): config = {'version': 1, 'koji': {'hub_url': '/', 'root_url': '', 'auth': {} }, 'allow_multiple_remote_sources': allow_multiple_remote_sources, 'openshift': {'url': 'openshift_url'}, 'registries': [{'url': REGISTRY, 'insecure': False}]} workflow.conf.conf = config def mock_environment(workflow: DockerBuildWorkflow, source_dir: Path, session=None, name=None, oci=False, component=None, version=None, release=None, source=None, build_process_failed=False, build_process_canceled=False, additional_tags=None, has_config=None, add_tag_conf_primaries=True, container_first=False, yum_repourls=None, has_op_appregistry_manifests=False, has_op_bundle_manifests=False, push_operator_manifests_enabled=False, source_build=False, has_remote_source=False, has_remote_source_file=False, has_pnc_build_metadata=False, scratch=False): if session is None: session = MockedClientSession('') if source is None: source = GitSource('git', 'git://hostname/path') platforms = ['x86_64'] workflow.data.plugins_results[PLUGIN_CHECK_AND_SET_PLATFORMS_KEY] = platforms workflow.data.plugins_results[PLUGIN_RESOLVE_COMPOSES_KEY] = {'composes': None} mock_reactor_config(workflow) workflow.user_params['scratch'] = scratch if yum_repourls: workflow.data.all_yum_repourls = yum_repourls workflow.data.image_id = '123456imageid' workflow.data.dockerfile_images = DockerfileImages(['Fedora:22']) flexmock(workflow.imageutil).should_receive('base_image_inspect').and_return({}) setattr(workflow.data, 'tag_conf', TagConf()) setattr(workflow.data, 'reserved_build_id ', None) setattr(workflow.data, 'reserved_token', None) with open(source_dir / DOCKERFILE_FILENAME, 'wt') as df: df.write('FROM base\n' 'LABEL BZComponent={component} com.redhat.component={component}\n' 'LABEL Version={version} version={version}\n' 'LABEL Release={release} release={release}\n' .format(component=component, version=version, release=release)) if has_op_appregistry_manifests: df.write('LABEL com.redhat.delivery.appregistry=true\n') if has_op_bundle_manifests: df.write('LABEL com.redhat.delivery.operator.bundle=true\n') if container_first: with open(source_dir / REPO_CONTAINER_CONFIG, 'wt') as container_conf: container_conf.write('go:\n' ' modules:\n' ' - module: example.com/packagename\n') tag_conf = workflow.data.tag_conf if name and version: tag_conf.add_unique_image('{}:{}-timestamp'.format(name, version)) if name and version and release and add_tag_conf_primaries: tag_conf.add_primary_image("{0}:{1}-{2}".format(name, version, release)) tag_conf.add_floating_image(f"{name}:{version}") tag_conf.add_floating_image(f"{name}:latest") if additional_tags: image: str for image in [f"{name}:{tag}" for tag in additional_tags]: tag_conf.add_floating_image(image) flexmock(subprocess, Popen=fake_Popen) flexmock(koji, ClientSession=lambda hub, opts: session) (flexmock(GitSource) .should_receive('path') .and_return(str(source_dir))) logs = { "taskRun1": {"containerA": "log message A", "containerB": "log message B"}, "taskRun2": {"containerC": "log message C"}, } (flexmock(OSBS) .should_receive('get_build_logs') .with_args(PIPELINE_RUN_NAME) .and_return(logs)) setattr(workflow, 'source', source) setattr(workflow.source, 'lg', X()) setattr(workflow.source.lg, 'commit_id', '123456') setattr(workflow.source.lg, 'git_path', str(source_dir)) workflow.build_dir.init_build_dirs(platforms, workflow.source) def custom_get(method, url, headers, **kwargs): if url == manifest_url: return manifest_response if url == config_blob_url: return config_blob_response for image in tag_conf.images: if oci: digest = ManifestDigest(v1='sha256:not-used', oci=fake_digest(image)) else: digest = ManifestDigest(v1='sha256:not-used', v2=fake_digest(image)) (flexmock(RegistryClient) .should_receive('get_manifest_digests') .and_return(digest)) manifest_response = requests.Response() MEDIA_TYPE = 'application/vnd.oci.image.manifest.v1+json' manifest_json = { "schemaVersion": 2, "mediaType": MEDIA_TYPE, "config": { "mediaType": MEDIA_TYPE, "digest": fake_digest(image), "size": 314 }, } (flexmock(manifest_response, raise_for_status=lambda: None, json=manifest_json, headers={ 'Content-Type': MEDIA_TYPE, 'Docker-Content-Digest': fake_digest(image) })) if oci: digest_str = digest.oci else: digest_str = digest.v2 manifest_url = "https://{}/v2/{}/manifests/{}".format(REGISTRY, image.to_str(tag=False), digest_str) config_blob_url = "https://{}/v2/{}/blobs/{}".format(REGISTRY, image.to_str(tag=False), digest_str) if has_config: config_json = {'config': {'architecture': 'x86_64'}, 'container_config': {}} else: config_json = None config_blob_response = requests.Response() (flexmock(config_blob_response, raise_for_status=lambda: None, json=config_json)) (flexmock(requests.Session) .should_receive('request') .replace_with(custom_get)) if not source_build: workflow.data.plugins_results[FetchDockerArchivePlugin.key] = { workflow.build_dir.any_platform.platform: {"type": IMAGE_TYPE_DOCKER_ARCHIVE} } build_dir_path = workflow.build_dir.any_platform.path image_tar = build_dir_path / 'image.tar.gz' image_tar.write_text('x' * 2**12, "utf-8") workflow.data.plugin_failed = build_process_failed if build_process_failed and build_process_canceled: workflow.data.build_canceled = True workflow.prebuild_plugins_conf = {} workflow.data.plugins_results[PLUGIN_FETCH_SOURCES_KEY] = { 'sources_for_nvr': SOURCES_FOR_KOJI_NVR, 'signing_intent': SOURCES_SIGNING_INTENT, } workflow.data.plugins_results[RPMqaPlugin.key] = [ "name1;1.0;1;x86_64;0;2000;" + FAKE_SIGMD5.decode() + ";23000;" "RSA/SHA256, Tue 30 Aug 2016 00:00:00, Key ID 01234567890abc;(none)", "name2;2.0;1;x86_64;0;3000;" + FAKE_SIGMD5.decode() + ";24000" "RSA/SHA256, Tue 30 Aug 2016 00:00:00, Key ID 01234567890abd;(none)", ] workflow.data.plugins_results[GatherBuildsMetadataPlugin.key] = { 'x86_64': { 'buildroots': [ { 'container': { 'type': 'none', 'arch': 'x86_64' }, 'content_generator': { 'version': '1.6.23', 'name': 'atomic-reactor' }, 'host': { 'os': 'Red Hat Enterprise Linux Server 7.3 (Maipo)', 'arch': 'x86_64' }, 'id': 1, 'components': [], 'tools': [], } ], 'metadata_version': 0, 'output': [ { 'type': 'log', 'arch': 'noarch', 'filename': 'openshift-final.log', 'filesize': 106690, 'checksum': '2efa754467c0d2ea1a98fb8bfe435955', 'checksum_type': 'md5', 'buildroot_id': 1 }, { 'type': 'log', 'arch': 'noarch', 'filename': 'build.log', 'filesize': 1660, 'checksum': '8198de09fc5940cf7495e2657039ee72', 'checksum_type': 'md5', 'buildroot_id': 1 }, { 'extra': { 'image': { 'arch': 'x86_64' }, 'docker': { 'repositories': [ 'docker-registry.example.com:8888/myproject/hello-world:unique-tag', 'docker-registry.example.com:8888/myproject/hello-world@sha256:...', ], 'parent_id': 'sha256:bf203442', 'id': '123456', } }, 'checksum': '58a52e6f3ed52818603c2744b4e2b0a2', 'filename': 'test.x86_64.tar.gz', 'buildroot_id': 1, 'components': [ { 'name': 'tzdata', 'sigmd5': 'd9dc4e4f205428bc08a52e602747c1e9', 'arch': 'noarch', 'epoch': None, 'version': '2016d', 'signature': '199e2f91fd431d51', 'release': '1.el7', 'type': 'rpm' }, { 'name': 'setup', 'sigmd5': 'b1e5ca72c71f94112cd9fb785b95d4da', 'arch': 'noarch', 'epoch': None, 'version': '2.8.71', 'signature': '199e2f91fd431d51', 'release': '6.el7', 'type': 'rpm' }, ], 'type': 'docker-image', 'checksum_type': 'md5', 'arch': 'x86_64', 'filesize': 71268781 } ] } } if has_op_appregistry_manifests or has_op_bundle_manifests: build_dir_path = workflow.build_dir.any_platform.path archive_file = build_dir_path / OPERATOR_MANIFESTS_ARCHIVE archive_file.write_bytes(b'20220329') results = workflow.data.plugins_results results[PLUGIN_EXPORT_OPERATOR_MANIFESTS_KEY] = str(archive_file) if has_remote_source: source_path = build_dir_path / REMOTE_SOURCE_TARBALL_FILENAME source_path.write_text('dummy file', 'utf-8') remote_source_result = [ { "name": None, "url": "https://cachito.com/api/v1/requests/21048/download", "remote_source_json": { "filename": REMOTE_SOURCE_JSON_FILENAME, "json": {"stub": "data"}, }, "remote_source_tarball": { "filename": REMOTE_SOURCE_TARBALL_FILENAME, "path": str(source_path), }, } ] workflow.data.plugins_results[PLUGIN_RESOLVE_REMOTE_SOURCE] = remote_source_result else: workflow.data.plugins_results[PLUGIN_RESOLVE_REMOTE_SOURCE] = None if has_remote_source_file: filepath = build_dir_path / REMOTE_SOURCE_FILE_FILENAME filepath.write_text('dummy file', 'utf-8') workflow.data.plugins_results[PLUGIN_MAVEN_URL_SOURCES_METADATA_KEY] = { 'remote_source_files': [ { 'file': str(filepath), 'metadata': { 'type': KOJI_BTYPE_REMOTE_SOURCE_FILE, 'checksum_type': 'md5', 'checksum': '5151c', 'filename': REMOTE_SOURCE_FILE_FILENAME, 'filesize': os.path.getsize(filepath), 'extra': { 'source-url': 'example.com/dummy.tar.gz', 'artifacts': [ { 'url': 'example.com/dummy.jar', 'checksum_type': 'md5', 'checksum': 'abc', 'filename': 'dummy.jar' } ], 'typeinfo': { KOJI_BTYPE_REMOTE_SOURCE_FILE: {} }, }, } } ], } workflow.data.plugins_results[PLUGIN_FETCH_MAVEN_KEY] = { 'no_source': [{ 'url': 'example.com/dummy-no-source.jar', 'checksum_type': 'md5', 'checksum': 'abc', 'filename': 'dummy-no-source.jar' }], } if has_pnc_build_metadata: workflow.data.plugins_results[PLUGIN_FETCH_MAVEN_KEY] = { 'pnc_build_metadata': { 'builds': [ {'id': 12345}, {'id': 12346} ] } } if push_operator_manifests_enabled: workflow.data.plugins_results[PLUGIN_PUSH_OPERATOR_MANIFESTS_KEY] = \ PUSH_OPERATOR_MANIFESTS_RESULTS @pytest.fixture def workflow(workflow): """Add additional data to provide pipeline_run_name specifically.""" workflow.user_params.update({ 'koji_task_id': MockedClientSession.TAG_TASK_ID, }) return workflow @pytest.fixture def _os_env(monkeypatch): monkeypatch.setenv('OPENSHIFT_CUSTOM_BUILD_BASE_IMAGE', 'buildroot:latest') def create_runner(workflow, ssl_certs=False, principal=None, keytab=None, target=None, blocksize=None, upload_plugin_name=KojiImportPlugin.key, userdata=None): args = {} if target: args['target'] = target args['poll_interval'] = 0 if blocksize: args['blocksize'] = blocksize if userdata: args['userdata'] = userdata add_koji_map_in_workflow(workflow, hub_url='', ssl_certs_dir='/' if ssl_certs else None, krb_principal=principal, krb_keytab=keytab) return (MockEnv(workflow) .for_plugin(upload_plugin_name, args=args) .create_runner()) @pytest.mark.usefixtures('user_params') class TestKojiImport(object): def test_koji_import_get_buildroot(self, workflow, source_dir): metadatas = { 'ppc64le': { 'buildroots': [ { 'container': { 'type': 'docker', 'arch': 'ppc64le' }, 'id': 1 } ], }, 'x86_64': { 'buildroots': [ { 'container': { 'type': 'docker', 'arch': 'x86_64' }, 'id': 1 } ], }, } results = [ { 'container': { 'arch': 'ppc64le', 'type': 'docker', }, 'id': 'ppc64le-1', }, { 'container': { 'arch': 'x86_64', 'type': 'docker', }, 'id': 'x86_64-1', }, ] session = MockedClientSession('') mock_environment(workflow, source_dir, session=session, build_process_failed=True, name='ns/name', version='1.0', release='1') add_koji_map_in_workflow(workflow, hub_url='') workflow.data.plugins_results[GatherBuildsMetadataPlugin.key] = metadatas plugin = KojiImportPlugin(workflow) assert plugin.get_buildroot() == results def test_koji_import_no_build_metadata(self, workflow, source_dir): mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1') runner = create_runner(workflow) # No metadata workflow.user_params = {} workflow.pipeline_run_name = None with pytest.raises(PluginFailedException): runner.run() def test_koji_import_wrong_source_type(self, workflow, source_dir): source = PathSource('path', f'file://{source_dir}') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1') runner = create_runner(workflow) setattr(workflow, 'source', source) with pytest.raises(PluginFailedException) as exc: runner.run() assert "plugin 'koji_import' raised an exception: RuntimeError" in str(exc.value) @pytest.mark.parametrize(('isolated'), [ False, True, None ]) def test_isolated_metadata_json(self, workflow, source_dir, isolated): session = MockedClientSession('') mock_environment(workflow, source_dir, session=session, name='ns/name', version='1.0', release='1') runner = create_runner(workflow) if isolated is not None: workflow.user_params['isolated'] = isolated runner.run() build_metadata = session.metadata['build']['extra']['image']['isolated'] if isolated: assert build_metadata is True else: assert build_metadata is False @pytest.mark.parametrize(('userdata'), [ None, {}, {'custom': 'userdata'}, ]) def test_userdata_metadata(self, workflow, source_dir, userdata): session = MockedClientSession('') mock_environment(workflow, source_dir, session=session, name='ns/name', version='1.0', release='1') runner = create_runner(workflow, userdata=userdata) runner.run() build_extra_metadata = session.metadata['build']['extra'] if userdata: assert build_extra_metadata['custom_user_metadata'] == userdata else: assert 'custom_user_metadata' not in build_extra_metadata @pytest.mark.parametrize(('koji_task_id', 'expect_success'), [ (12345, True), ('x', False), ]) def test_koji_import_log_task_id(self, workflow, source_dir, caplog, koji_task_id, expect_success): session = MockedClientSession('') session.getTaskInfo = lambda x: {'owner': 1234, 'state': 1} setattr(session, 'getUser', lambda x: {'name': 'dev1'}) mock_environment(workflow, source_dir, session=session, name='ns/name', version='1.0', release='1') runner = create_runner(workflow) workflow.user_params['koji_task_id'] = koji_task_id runner.run() metadata = session.metadata assert 'build' in metadata build = metadata['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) if expect_success: assert "Koji Task ID {}".format(koji_task_id) in caplog.text assert 'container_koji_task_id' in extra extra_koji_task_id = extra['container_koji_task_id'] assert isinstance(extra_koji_task_id, int) assert extra_koji_task_id == koji_task_id else: assert "invalid task ID" in caplog.text assert 'container_koji_task_id' not in extra @pytest.mark.parametrize('params', [ { 'should_raise': False, 'principal': None, 'keytab': None, }, { 'should_raise': False, 'principal': 'principal@EXAMPLE.COM', 'keytab': 'FILE:/var/run/secrets/mysecret', }, { 'should_raise': True, 'principal': 'principal@EXAMPLE.COM', 'keytab': None, }, { 'should_raise': True, 'principal': None, 'keytab': 'FILE:/var/run/secrets/mysecret', }, ]) def test_koji_import_krb_args(self, workflow, source_dir, params): session = MockedClientSession('') expectation = flexmock(session).should_receive('krb_login').and_return(True) name = 'name' version = '1.0' release = '1' mock_environment(workflow, source_dir, session=session, name=name, version=version, release=release) runner = create_runner(workflow, principal=params['principal'], keytab=params['keytab']) if params['should_raise']: expectation.never() with pytest.raises(PluginFailedException): runner.run() else: expectation.once() runner.run() def test_koji_import_krb_fail(self, workflow, source_dir): session = MockedClientSession('') (flexmock(session) .should_receive('krb_login') .and_raise(RuntimeError) .once()) mock_environment(workflow, source_dir, session=session, name='ns/name', version='1.0', release='1') runner = create_runner(workflow) with pytest.raises(PluginFailedException): runner.run() def test_koji_import_ssl_fail(self, workflow, source_dir): session = MockedClientSession('') (flexmock(session) .should_receive('ssl_login') .and_raise(RuntimeError) .once()) mock_environment(workflow, source_dir, session=session, name='ns/name', version='1.0', release='1') runner = create_runner(workflow, ssl_certs=True) with pytest.raises(PluginFailedException): runner.run() @pytest.mark.parametrize('fail_method', [ 'get_build_logs', ]) def test_koji_import_osbs_fail(self, workflow, source_dir, fail_method): mock_environment(workflow, source_dir, name='name', version='1.0', release='1') (flexmock(OSBS) .should_receive(fail_method) .and_raise(OsbsException)) runner = create_runner(workflow) runner.run() @staticmethod def check_components(components): assert isinstance(components, list) assert len(components) > 0 for component_rpm in components: assert isinstance(component_rpm, dict) assert set(component_rpm.keys()) == { 'type', 'name', 'version', 'release', 'epoch', 'arch', 'sigmd5', 'signature', } assert component_rpm['type'] == 'rpm' assert component_rpm['name'] assert is_string_type(component_rpm['name']) assert component_rpm['name'] != 'gpg-pubkey' assert component_rpm['version'] assert is_string_type(component_rpm['version']) assert component_rpm['release'] epoch = component_rpm['epoch'] assert epoch is None or isinstance(epoch, int) assert is_string_type(component_rpm['arch']) assert component_rpm['signature'] != '(none)' def validate_buildroot(self, buildroot, source=False): assert isinstance(buildroot, dict) assert set(buildroot.keys()) == { 'id', 'host', 'content_generator', 'container', 'components', 'tools', } host = buildroot['host'] assert isinstance(host, dict) assert set(host.keys()) == {'os', 'arch'} # assert host['os'] # assert is_string_type(host['os']) assert host['arch'] assert is_string_type(host['arch']) assert host['arch'] != 'amd64' content_generator = buildroot['content_generator'] assert isinstance(content_generator, dict) assert set(content_generator.keys()) == {'name', 'version'} assert content_generator['name'] assert is_string_type(content_generator['name']) assert content_generator['version'] assert is_string_type(content_generator['version']) container = buildroot['container'] assert isinstance(container, dict) assert set(container.keys()) == {'type', 'arch'} assert container['type'] == 'none' assert container['arch'] assert is_string_type(container['arch']) def validate_output(self, output, has_config, source=False): assert isinstance(output, dict) assert 'buildroot_id' in output assert 'filename' in output assert output['filename'] assert is_string_type(output['filename']) assert 'filesize' in output assert int(output['filesize']) > 0 assert 'arch' in output assert output['arch'] assert is_string_type(output['arch']) assert 'checksum' in output assert output['checksum'] assert is_string_type(output['checksum']) assert 'checksum_type' in output assert output['checksum_type'] == 'md5' assert is_string_type(output['checksum_type']) assert 'type' in output if output['type'] == 'log': assert set(output.keys()) == { 'buildroot_id', 'filename', 'filesize', 'arch', 'checksum', 'checksum_type', 'type', } assert output['arch'] == 'noarch' else: assert set(output.keys()) == { 'buildroot_id', 'filename', 'filesize', 'arch', 'checksum', 'checksum_type', 'type', 'components', 'extra', } assert output['type'] == 'docker-image' assert is_string_type(output['arch']) assert output['arch'] != 'noarch' assert output['arch'] in output['filename'] if not source: self.check_components(output['components']) else: assert output['components'] == [] extra = output['extra'] assert isinstance(extra, dict) assert set(extra.keys()) == {'image', 'docker'} image = extra['image'] assert isinstance(image, dict) assert set(image.keys()) == {'arch'} assert image['arch'] == output['arch'] # what else? assert 'docker' in extra docker = extra['docker'] assert isinstance(docker, dict) if source: expected_keys_set = { 'tags', 'digests', 'layer_sizes', 'repositories', 'id', } else: expected_keys_set = { 'parent_id', 'id', 'repositories', 'tags', 'floating_tags', 'unique_tags', } if has_config: expected_keys_set.add('config') assert set(docker.keys()) == expected_keys_set if not source: assert is_string_type(docker['parent_id']) assert is_string_type(docker['id']) repositories = docker['repositories'] assert isinstance(repositories, list) repositories_digest = list(filter(lambda repo: '@sha256' in repo, repositories)) assert sorted(repositories_digest) == sorted(set(repositories_digest)) def test_koji_import_import_fail(self, workflow, source_dir, caplog): session = MockedClientSession('') (flexmock(session) .should_receive('CGImport') .and_raise(RuntimeError)) name = 'ns/name' version = '1.0' release = '1' target = 'images-docker-candidate' mock_environment(workflow, source_dir, name=name, version=version, release=release, session=session) runner = create_runner(workflow, target=target) with pytest.raises(PluginFailedException): runner.run() assert 'metadata:' in caplog.text @pytest.mark.parametrize(('parent_id', 'expect_success', 'expect_error'), [ (1234, True, False), (None, False, False), ('x', False, True), ('NO-RESULT', False, False), ]) def test_koji_import_parent_id(self, parent_id, expect_success, expect_error, workflow, source_dir, caplog): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) koji_parent_result = None if parent_id != 'NO-RESULT': koji_parent_result = { BASE_IMAGE_KOJI_BUILD: {'id': parent_id}, } workflow.data.plugins_results[PLUGIN_KOJI_PARENT_KEY] = koji_parent_result runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) if expect_error: assert 'invalid koji parent id' in caplog.text if expect_success: image = extra['image'] assert isinstance(image, dict) assert BASE_IMAGE_BUILD_ID_KEY in image parent_image_koji_build_id = image[BASE_IMAGE_BUILD_ID_KEY] assert isinstance(parent_image_koji_build_id, int) assert parent_image_koji_build_id == parent_id else: if 'image' in extra: assert BASE_IMAGE_BUILD_ID_KEY not in extra['image'] @pytest.mark.parametrize('base_from_scratch', [True, False]) # noqa: F811 def test_produces_metadata_for_parent_images( self, workflow, source_dir, base_from_scratch ): koji_session = MockedClientSession('') mock_environment(workflow, source_dir, session=koji_session, name='ns/name', version='1.0', release='1') koji_parent_result = { BASE_IMAGE_KOJI_BUILD: dict(id=16, extra='build info'), PARENT_IMAGES_KOJI_BUILDS: { str(ImageName.parse('base')): dict(nvr='base-16.0-1', id=16, extra='build_info'), }, } workflow.data.plugins_results[PLUGIN_KOJI_PARENT_KEY] = koji_parent_result dockerfile_images = ['base:latest', 'scratch', 'some:1.0'] if base_from_scratch: dockerfile_images.append('scratch') workflow.data.dockerfile_images = DockerfileImages(dockerfile_images) runner = create_runner(workflow) runner.run() image_metadata = koji_session.metadata['build']['extra']['image'] key = PARENT_IMAGE_BUILDS_KEY assert key in image_metadata assert image_metadata[key]['base:latest'] == dict(nvr='base-16.0-1', id=16) assert 'extra' not in image_metadata[key]['base:latest'] key = BASE_IMAGE_BUILD_ID_KEY if base_from_scratch: assert key not in image_metadata else: assert key in image_metadata assert image_metadata[key] == 16 key = PARENT_IMAGES_KEY assert key in image_metadata assert image_metadata[key] == dockerfile_images @pytest.mark.parametrize(('task_id', 'expect_success'), [ (1234, True), ('x', False), ]) def test_koji_import_filesystem_koji_task_id( self, task_id, expect_success, workflow, source_dir, caplog ): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) workflow.data.plugins_results[AddFilesystemPlugin.key] = { 'base-image-id': 'abcd', 'filesystem-koji-task-id': task_id, } runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) if expect_success: assert 'filesystem_koji_task_id' in extra filesystem_koji_task_id = extra['filesystem_koji_task_id'] assert isinstance(filesystem_koji_task_id, int) assert filesystem_koji_task_id == task_id else: assert 'invalid task ID' in caplog.text assert 'filesystem_koji_task_id' not in extra def test_koji_import_filesystem_koji_task_id_missing( self, workflow, source_dir, caplog ): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) workflow.data.plugins_results[AddFilesystemPlugin.key] = { 'base-image-id': 'abcd', } runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'filesystem_koji_task_id' not in extra assert AddFilesystemPlugin.key in caplog.text @pytest.mark.parametrize('blocksize', (None, 1048576)) @pytest.mark.parametrize(('verify_media', 'expect_id'), ( (['v1', 'v2', 'v2_list'], 'ab12'), (['v1'], 'ab12'), (False, 'ab12') )) @pytest.mark.parametrize('has_reserved_build', (True, False)) @pytest.mark.parametrize(('task_states', 'skip_import'), [ (['OPEN'], False), (['FAILED'], True), ]) def test_koji_import_success(self, workflow, source_dir, caplog, blocksize, verify_media, expect_id, has_reserved_build, task_states, skip_import): session = MockedClientSession('', task_states=task_states) component = 'component' name = 'ns/name' version = '1.0' release = '1' mock_environment(workflow, source_dir, session=session, component=component, name=name, version=version, release=release) if verify_media: workflow.data.plugins_results[PLUGIN_VERIFY_MEDIA_KEY] = verify_media expected_media_types = verify_media or [] workflow.data.image_id = expect_id build_token = 'token_12345' build_id = '123' if has_reserved_build: workflow.data.reserved_build_id = build_id workflow.data.reserved_token = build_token if has_reserved_build: (flexmock(session) .should_call('CGImport') .with_args(dict, str, token=build_token) ) else: (flexmock(session) .should_call('CGImport') .with_args(dict, str) ) target = 'images-docker-candidate' runner = create_runner(workflow, target=target, blocksize=blocksize) runner.run() if skip_import: log_msg = "Koji task is not in Open state, but in {}, not importing build".\ format(task_states[0]) assert log_msg in caplog.text return data = session.metadata assert set(data.keys()) == { 'metadata_version', 'build', 'buildroots', 'output', } assert data['metadata_version'] in ['0', 0] build = data['build'] assert isinstance(build, dict) buildroots = data['buildroots'] assert isinstance(buildroots, list) assert len(buildroots) > 0 output_files = data['output'] assert isinstance(output_files, list) expected_keys = { 'name', 'version', 'release', 'source', 'start_time', 'end_time', 'extra', # optional but always supplied 'owner', } if has_reserved_build: expected_keys.add('build_id') assert set(build.keys()) == expected_keys if has_reserved_build: assert build['build_id'] == build_id assert build['name'] == component assert build['version'] == version assert build['release'] == release assert build['source'] == 'git://hostname/path#123456' start_time = build['start_time'] assert isinstance(start_time, int) and start_time end_time = build['end_time'] assert isinstance(end_time, int) and end_time extra = build['extra'] assert isinstance(extra, dict) assert 'osbs_build' in extra osbs_build = extra['osbs_build'] assert isinstance(osbs_build, dict) assert 'kind' in osbs_build assert osbs_build['kind'] == KOJI_KIND_IMAGE_BUILD assert 'subtypes' in osbs_build assert osbs_build['subtypes'] == [] assert 'engine' in osbs_build assert osbs_build['engine'] == 'podman' assert 'image' in extra image = extra['image'] assert isinstance(image, dict) if expected_media_types: media_types = image['media_types'] assert isinstance(media_types, list) assert sorted(media_types) == sorted(expected_media_types) for buildroot in buildroots: self.validate_buildroot(buildroot) # Unique within buildroots in this metadata assert len([b for b in buildroots if b['id'] == buildroot['id']]) == 1 for output in output_files: self.validate_output(output, False) buildroot_id = output['buildroot_id'] # References one of the buildroots assert len([buildroot for buildroot in buildroots if buildroot['id'] == buildroot_id]) == 1 build_id = runner.plugins_results[KojiImportPlugin.key] assert build_id == "123" assert set(session.uploaded_files.keys()) == {OSBS_BUILD_LOG_FILENAME} osbs_build_log = session.uploaded_files[OSBS_BUILD_LOG_FILENAME] assert osbs_build_log == b"log message A\nlog message B\nlog message C\n" assert workflow.data.annotations['koji-build-id'] == '123' def test_koji_import_owner_submitter(self, workflow, source_dir): session = MockedClientSession('') session.getTaskInfo = lambda x: {'owner': 1234, 'state': 1} setattr(session, 'getUser', lambda x: {'name': 'dev1'}) mock_environment(workflow, source_dir, session=session, name='ns/name', version='1.0', release='1') runner = create_runner(workflow) workflow.user_params['koji_task_id'] = 1234 runner.run() metadata = session.metadata assert metadata['build']['extra']['submitter'] == 'osbs' assert metadata['build']['owner'] == 'dev1' def test_koji_import_pullspec(self, workflow, source_dir): session = MockedClientSession('') name = 'myproject/hello-world' version = '1.0' release = '1' mock_environment(workflow, source_dir, session=session, name=name, version=version, release=release) runner = create_runner(workflow) runner.run() log_outputs = [ output for output in session.metadata['output'] if output['type'] == 'log' ] assert log_outputs docker_outputs = [ output for output in session.metadata['output'] if output['type'] == 'docker-image' ] assert len(docker_outputs) == 1 docker_output = docker_outputs[0] digest_pullspecs = [ repo for repo in docker_output['extra']['docker']['repositories'] if '@sha256' in repo ] assert len(digest_pullspecs) == 1 # Check registry reg = set(ImageName.parse(repo).registry for repo in docker_output['extra']['docker']['repositories']) assert len(reg) == 1 assert reg == {'docker-registry.example.com:8888'} def test_koji_import_without_build_info(self, workflow, source_dir): class LegacyCGImport(MockedClientSession): def CGImport(self, metadata, server_dir, token=None): super(LegacyCGImport, self).CGImport(metadata, server_dir, token) return session = LegacyCGImport('') name = 'ns/name' version = '1.0' release = '1' mock_environment(workflow, source_dir, session=session, name=name, version=version, release=release) runner = create_runner(workflow) runner.run() assert runner.plugins_results[KojiImportPlugin.key] is None @pytest.mark.parametrize('add_help_results,expected_help_file', [ [{}, None], [{AddHelpPlugin.key: {}}, None], [{AddHelpPlugin.key: {'help_file': None}}, None], [{AddHelpPlugin.key: {'help_file': 'help.md'}}, 'help.md'], ]) def test_koji_import_add_help(self, add_help_results, expected_help_file, workflow, source_dir): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) workflow.data.plugins_results.update(add_help_results) runner = create_runner(workflow) runner.run() data = session.metadata extra_image = data['build']['extra']['image'] if not add_help_results or not add_help_results[AddHelpPlugin.key]: assert 'help' not in extra_image else: assert expected_help_file == extra_image['help'] @pytest.mark.skipif(not MODULEMD_AVAILABLE, reason="libmodulemd not available") def test_koji_import_flatpak(self, workflow, source_dir): workflow.user_params['flatpak'] = True session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) setup_flatpak_composes(workflow) (flexmock(FlatpakUtil) .should_receive('get_flatpak_compose_info') .replace_with(setup_flatpak_compose_info)) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'image' in extra image = extra['image'] assert isinstance(image, dict) assert 'osbs_build' in extra osbs_build = extra['osbs_build'] assert osbs_build['subtypes'] == ['flatpak'] assert image.get('flatpak') is True assert image.get('modules') == ['eog-f28-20170629213428', 'flatpak-runtime-f28-20170701152209'] assert image.get('source_modules') == ['eog:f28'] assert image.get('odcs') == { 'compose_ids': [22422, 42], 'signing_intent': 'unsigned', 'signing_intent_overridden': False, } @pytest.mark.parametrize('build_result,expected', [ [{}, None], [{PLUGIN_VERIFY_MEDIA_KEY: []}, []], [ {PLUGIN_VERIFY_MEDIA_KEY: [MEDIA_TYPE_DOCKER_V2_SCHEMA2]}, [MEDIA_TYPE_DOCKER_V2_SCHEMA2], ], ]) def test_koji_import_set_media_types( self, workflow, source_dir, build_result, expected ): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) workflow.data.plugins_results.update(build_result) runner = create_runner(workflow) runner.run() data = session.metadata image = data['build']['extra']['image'] if not build_result or not build_result[PLUGIN_VERIFY_MEDIA_KEY]: assert 'media_types' not in image else: assert expected == image['media_types'] @pytest.mark.parametrize('is_scratch', [True, False]) @pytest.mark.parametrize('digest', [ None, ManifestDigest(v2_list='sha256:e6593f3e'), ]) def test_koji_import_set_manifest_list_info(self, caplog, workflow, source_dir, is_scratch, digest): session = MockedClientSession('') version = '1.0' release = '1' name = 'ns/name' unique_tag = "{}-timestamp".format(version) mock_environment(workflow, source_dir, name=name, version=version, release=release, session=session, add_tag_conf_primaries=not is_scratch, scratch=is_scratch) group_manifest_result = {"media_type": MEDIA_TYPE_DOCKER_V2_SCHEMA2} if digest: group_manifest_result = { 'media_type': MEDIA_TYPE_DOCKER_V2_MANIFEST_LIST, 'manifest_digest': digest } workflow.data.plugins_results[PLUGIN_GROUP_MANIFESTS_KEY] = group_manifest_result flexmock(koji_cli.lib).should_receive('unique_path').and_return('upload-dir') runner = create_runner(workflow) runner.run() if is_scratch: medata_tag = '_metadata_' metadata_file = 'metadata.json' assert metadata_file in session.uploaded_files data = json.loads(session.uploaded_files[metadata_file]) meta_rec = {x.arch: x.message for x in caplog.records if hasattr(x, 'arch') and x.arch == medata_tag} assert medata_tag in meta_rec assert os.path.join('upload-dir', metadata_file) == meta_rec[medata_tag] else: data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'image' in extra image = extra['image'] assert isinstance(image, dict) expected_results = {'unique_tags': [unique_tag]} expected_results['floating_tags'] = [ tag.tag for tag in workflow.data.tag_conf.floating_images ] if is_scratch: expected_results['tags'] = [ tag.tag for tag in workflow.data.tag_conf.images ] else: expected_results['tags'] = [ tag.tag for tag in workflow.data.tag_conf.primary_images ] for tag in expected_results['tags']: if '-' in tag: version_release = tag break else: raise RuntimeError("incorrect test data") if digest: assert 'index' in image.keys() pullspec = "{}/{}@{}".format(REGISTRY, name, digest.v2_list) expected_results['pull'] = [pullspec] pullspec = "{}/{}:{}".format(REGISTRY, name, version_release) expected_results['pull'].append(pullspec) expected_results['digests'] = { 'application/vnd.docker.distribution.manifest.list.v2+json': digest.v2_list} assert image['index'] == expected_results else: assert 'index' not in image.keys() assert 'output' in data for output in data['output']: if output['type'] == 'log': continue assert 'extra' in output extra = output['extra'] assert 'docker' in extra assert 'tags' in extra['docker'] assert 'floating_tags' in extra['docker'] assert 'unique_tags' in extra['docker'] assert sorted(expected_results['tags']) == sorted(extra['docker']['tags']) assert (sorted(expected_results['floating_tags']) == sorted(extra['docker']['floating_tags'])) assert (sorted(expected_results['unique_tags']) == sorted(extra['docker']['unique_tags'])) repositories = extra['docker']['repositories'] assert len(repositories) == 2 assert len([pullspec for pullspec in repositories if '@' in pullspec]) == 1 by_tags = [pullspec for pullspec in repositories if '@' not in pullspec] assert len(by_tags) == 1 by_tag = by_tags[0] # This test uses a metadata fragment which reports the # following registry. In real uses this would really # be a Crane registry URI. registry = 'docker-registry.example.com:8888' assert by_tag == '%s/myproject/hello-world:%s' % (registry, version_release) @pytest.mark.parametrize(('add_tag_conf_primaries', 'success'), ( (False, False), (True, True), )) def test_koji_import_primary_images(self, workflow, source_dir, add_tag_conf_primaries, success): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', add_tag_conf_primaries=add_tag_conf_primaries, session=session) runner = create_runner(workflow) if not success: with pytest.raises(PluginFailedException) as exc_info: runner.run() assert 'Unable to find version-release image' in str(exc_info.value) return runner.run() @pytest.mark.parametrize(('comp', 'sign_int', 'override'), [ ([{'id': 1}, {'id': 2}, {'id': 3}], "beta", True), ([{'id': 2}, {'id': 3}, {'id': 4}], "release", True), ([{'id': 3}, {'id': 4}, {'id': 5}], "beta", False), ([{'id': 4}, {'id': 5}, {'id': 6}], "release", False), (None, None, None) ]) def test_odcs_metadata_koji(self, workflow, source_dir, comp, sign_int, override): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) workflow.data.plugins_results[PLUGIN_RESOLVE_COMPOSES_KEY] = { 'composes': comp, 'yum_repourls': {'x86_64': []}, 'include_koji_repo': False, 'signing_intent': sign_int, 'signing_intent_overridden': override, } runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'image' in extra image = extra['image'] assert isinstance(image, dict) if comp: comp_ids = [item['id'] for item in comp] assert 'odcs' in image odcs = image['odcs'] assert isinstance(odcs, dict) assert odcs['compose_ids'] == comp_ids assert odcs['signing_intent'] == sign_int assert odcs['signing_intent_overridden'] == override else: assert 'odcs' not in image @pytest.mark.parametrize('resolve_run', [ True, False, ]) def test_odcs_metadata_koji_plugin_run(self, workflow, source_dir, resolve_run): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session) if resolve_run: workflow.data.plugins_results[PLUGIN_RESOLVE_COMPOSES_KEY] = {'composes': None} runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'image' in extra image = extra['image'] assert isinstance(image, dict) assert 'odcs' not in image @pytest.mark.parametrize('container_first', [True, False]) def test_go_metadata(self, workflow, source_dir, container_first): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, container_first=container_first) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'image' in extra image = extra['image'] assert isinstance(image, dict) if container_first: assert 'go' in image go = image['go'] assert isinstance(go, dict) assert 'modules' in go modules = go['modules'] assert isinstance(modules, list) assert len(modules) == 1 module = modules[0] assert module['module'] == 'example.com/packagename' else: assert 'go' not in image @pytest.mark.parametrize('yum_repourl', [ None, [], ["http://example.com/my.repo", ], ["http://example.com/my.repo", "http://example.com/other.repo"], ]) def test_yum_repourls_metadata(self, workflow, source_dir, yum_repourl): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, yum_repourls=yum_repourl) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'image' in extra image = extra['image'] assert isinstance(image, dict) if yum_repourl: assert 'yum_repourls' in image repourls = image['yum_repourls'] assert isinstance(repourls, list) assert repourls == yum_repourl else: assert 'yum_repourls' not in image @pytest.mark.parametrize('has_appregistry_manifests', [True, False]) @pytest.mark.parametrize('has_bundle_manifests', [True, False]) @pytest.mark.parametrize('push_operator_manifests', [True, False]) def test_set_operators_metadata( self, workflow, source_dir, has_appregistry_manifests, has_bundle_manifests, push_operator_manifests): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, has_op_appregistry_manifests=has_appregistry_manifests, has_op_bundle_manifests=has_bundle_manifests, push_operator_manifests_enabled=push_operator_manifests) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'osbs_build' in extra osbs_build = extra['osbs_build'] if has_appregistry_manifests or has_bundle_manifests: assert 'operator_manifests_archive' in extra operator_manifests = extra['operator_manifests_archive'] assert isinstance(operator_manifests, str) assert operator_manifests == OPERATOR_MANIFESTS_ARCHIVE assert 'typeinfo' in extra assert 'operator-manifests' in extra['typeinfo'] operator_typeinfo = extra['typeinfo']['operator-manifests'] assert isinstance(operator_typeinfo, dict) assert operator_typeinfo['archive'] == OPERATOR_MANIFESTS_ARCHIVE else: assert 'operator_manifests_archive' not in extra assert 'typeinfo' not in extra # having manifests pushed without extraction cannot happen, but plugins handles # results independently so test it this way if push_operator_manifests: assert extra['operator_manifests']['appregistry'] == PUSH_OPERATOR_MANIFESTS_RESULTS else: assert 'operator_manifests' not in extra assert osbs_build['subtypes'] == [ stype for yes, stype in [ (has_appregistry_manifests, KOJI_SUBTYPE_OP_APPREGISTRY), (has_bundle_manifests, KOJI_SUBTYPE_OP_BUNDLE) ] if yes ] @pytest.mark.usefixtures('_os_env') @pytest.mark.parametrize('has_bundle_manifests', [True, False]) def test_operators_bundle_metadata( self, workflow, source_dir, has_bundle_manifests): """Test if metadata (extra.image.operator_manifests) about operator bundles are properly exported""" session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, has_op_bundle_manifests=has_bundle_manifests) if has_bundle_manifests: workflow.data.plugins_results[PLUGIN_PIN_OPERATOR_DIGESTS_KEY] = { 'custom_csv_modifications_applied': False, 'related_images': { 'pullspecs': [ { 'original': ImageName.parse('old-registry/ns/spam:1'), 'new': ImageName.parse('new-registry/new-ns/new-spam@sha256:4'), 'pinned': True, 'replaced': True }, { 'original': ImageName.parse('old-registry/ns/spam@sha256:4'), 'new': ImageName.parse('new-registry/new-ns/new-spam@sha256:4'), 'pinned': False, 'replaced': True }, { 'original': ImageName.parse( 'registry.private.example.com/ns/foo@sha256:1'), 'new': ImageName.parse('registry.private.example.com/ns/foo@sha256:1'), 'pinned': False, 'replaced': False }, ], 'created_by_osbs': True, } } runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) if has_bundle_manifests: assert 'operator_manifests' in extra['image'] expected = { 'custom_csv_modifications_applied': False, 'related_images': { 'pullspecs': [ { 'original': 'old-registry/ns/spam:1', 'new': 'new-registry/new-ns/new-spam@sha256:4', 'pinned': True, }, { 'original': 'old-registry/ns/spam@sha256:4', 'new': 'new-registry/new-ns/new-spam@sha256:4', 'pinned': False, }, { 'original': 'registry.private.example.com/ns/foo@sha256:1', 'new': 'registry.private.example.com/ns/foo@sha256:1', 'pinned': False, }, ], 'created_by_osbs': True, } } assert extra['image']['operator_manifests'] == expected else: assert 'operator_manifests' not in extra['image'] @pytest.mark.usefixtures('_os_env') @pytest.mark.parametrize('has_op_csv_modifications', [True, False]) def test_operators_bundle_metadata_csv_modifications( self, workflow, source_dir, has_op_csv_modifications): """Test if metadata (extra.image.operator_manifests.custom_csv_modifications_applied) about operator bundles are properly exported""" session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, has_op_bundle_manifests=True) plugin_res = { 'custom_csv_modifications_applied': has_op_csv_modifications, 'related_images': { 'pullspecs': [], 'created_by_osbs': True, } } workflow.data.plugins_results[PLUGIN_PIN_OPERATOR_DIGESTS_KEY] = plugin_res runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'operator_manifests' in extra['image'] expected = { 'custom_csv_modifications_applied': has_op_csv_modifications, 'related_images': { 'pullspecs': [], 'created_by_osbs': True, } } assert extra['image']['operator_manifests'] == expected @pytest.mark.parametrize('has_remote_source', [True, False]) @pytest.mark.parametrize('allow_multiple_remote_sources', [True, False]) def test_remote_sources(self, workflow, source_dir, has_remote_source, allow_multiple_remote_sources): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, has_remote_source=has_remote_source) mock_reactor_config(workflow, allow_multiple_remote_sources) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) # https://github.com/PyCQA/pylint/issues/2186 # pylint: disable=W1655 if has_remote_source: if allow_multiple_remote_sources: assert extra['image']['remote_sources'] == [ { 'name': None, 'url': 'https://cachito.com/api/v1/requests/21048', } ] assert 'typeinfo' in extra assert 'remote-sources' in extra['typeinfo'] assert extra['typeinfo']['remote-sources'] == [ { 'name': None, 'url': 'https://cachito.com/api/v1/requests/21048', 'archives': ['remote-source.json', 'remote-source.tar.gz'], } ] assert REMOTE_SOURCE_TARBALL_FILENAME in session.uploaded_files.keys() assert REMOTE_SOURCE_JSON_FILENAME in session.uploaded_files.keys() else: assert ( extra['image']['remote_source_url'] == 'https://cachito.com/api/v1/requests/21048/download' ) assert extra['typeinfo']['remote-sources'] == { "remote_source_url": "https://cachito.com/api/v1/requests/21048/download" } assert REMOTE_SOURCE_TARBALL_FILENAME in session.uploaded_files.keys() assert REMOTE_SOURCE_JSON_FILENAME in session.uploaded_files.keys() else: assert 'remote_source_url' not in extra['image'] assert 'typeinfo' not in extra assert REMOTE_SOURCE_TARBALL_FILENAME not in session.uploaded_files.keys() assert REMOTE_SOURCE_JSON_FILENAME not in session.uploaded_files.keys() @pytest.mark.parametrize('has_remote_source_file', [True, False]) def test_remote_source_files(self, workflow, source_dir, has_remote_source_file): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, has_remote_source_file=has_remote_source_file) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) # https://github.com/PyCQA/pylint/issues/2186 # pylint: disable=W1655 if has_remote_source_file: assert 'typeinfo' in extra assert 'remote-source-file' in extra['typeinfo'] assert REMOTE_SOURCE_FILE_FILENAME in session.uploaded_files.keys() else: assert 'typeinfo' not in extra assert REMOTE_SOURCE_FILE_FILENAME not in session.uploaded_files.keys() @pytest.mark.parametrize('has_pnc_build_metadata', [True, False]) def test_pnc_build_metadata(self, workflow, source_dir, has_pnc_build_metadata): session = MockedClientSession('') mock_environment(workflow, source_dir, name='ns/name', version='1.0', release='1', session=session, has_pnc_build_metadata=has_pnc_build_metadata) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) # https://github.com/PyCQA/pylint/issues/2186 # pylint: disable=W1655 if has_pnc_build_metadata: assert 'pnc' in extra['image'] assert 'builds' in extra['image']['pnc'] for build in extra['image']['pnc']['builds']: assert 'id' in build else: assert 'pnc' not in extra['image'] @pytest.mark.parametrize('blocksize', (None, 1048576)) @pytest.mark.parametrize(('has_config', 'oci'), ((True, False), (False, True))) @pytest.mark.parametrize(('verify_media', 'expect_id'), ( (['v1', 'v2', 'v2_list'], 'ab12'), (['v1'], 'ab12'), (False, 'ab12') )) @pytest.mark.parametrize('has_reserved_build', (True, False)) @pytest.mark.parametrize(('task_states', 'skip_import'), [ (['OPEN'], False), (['FAILED'], True), ]) @pytest.mark.parametrize(('userdata'), [ None, {}, {'custom': 'userdata'}, ]) def test_koji_import_success_source(self, workflow, source_dir, caplog, blocksize, has_config, oci, verify_media, expect_id, has_reserved_build, task_states, skip_import, userdata): session = MockedClientSession('', task_states=task_states) # When target is provided koji build will always be tagged, # either by koji_import or koji_tag_build. component = 'component' name = 'ns/name' version = '1.0' release = '1' mock_environment(workflow, source_dir, oci=oci, session=session, name=name, component=component, version=version, release=release, has_config=has_config, source_build=True) workflow.data.koji_source_nvr = {'name': component, 'version': version, 'release': release} workflow.data.koji_source_source_url = 'git://hostname/path#123456' if verify_media: workflow.data.plugins_results[PLUGIN_VERIFY_MEDIA_KEY] = verify_media expected_media_types = verify_media or [] workflow.data.image_id = expect_id build_token = 'token_12345' build_id = '123' if has_reserved_build: workflow.data.reserved_build_id = build_id workflow.data.reserved_token = build_token if has_reserved_build: (flexmock(session) .should_call('CGImport') .with_args(dict, str, token=build_token) ) else: (flexmock(session) .should_call('CGImport') .with_args(dict, str) ) target = 'images-docker-candidate' source_manifest = { 'config': { 'digest': expect_id, }, 'layers': [ {'size': 20000, 'digest': 'sha256:123456789'}, {'size': 30000, 'digest': 'sha256:987654321'}, ] } workflow.data.koji_source_manifest = source_manifest runner = create_runner(workflow, target=target, blocksize=blocksize, upload_plugin_name=KojiImportSourceContainerPlugin.key, userdata=userdata) runner.run() if skip_import: log_msg = "Koji task is not in Open state, but in {}, not importing build".\ format(task_states[0]) assert log_msg in caplog.text return data = session.metadata assert set(data.keys()) == { 'metadata_version', 'build', 'buildroots', 'output', } assert data['metadata_version'] in ['0', 0] build = data['build'] assert isinstance(build, dict) buildroots = data['buildroots'] assert isinstance(buildroots, list) assert len(buildroots) > 0 output_files = data['output'] assert isinstance(output_files, list) expected_keys = { 'name', 'version', 'release', 'source', 'start_time', 'end_time', 'extra', # optional but always supplied 'owner', } if has_reserved_build: expected_keys.add('build_id') assert set(build.keys()) == expected_keys if has_reserved_build: assert build['build_id'] == build_id assert build['name'] == component assert build['version'] == version assert build['release'] == release assert build['source'] == 'git://hostname/path#123456' start_time = build['start_time'] assert isinstance(start_time, int) and start_time end_time = build['end_time'] assert isinstance(end_time, int) and end_time extra = build['extra'] assert isinstance(extra, dict) if userdata: assert extra['custom_user_metadata'] == userdata else: assert 'custom_user_metadata' not in extra assert 'osbs_build' in extra osbs_build = extra['osbs_build'] assert isinstance(osbs_build, dict) assert 'kind' in osbs_build assert osbs_build['kind'] == KOJI_KIND_IMAGE_SOURCE_BUILD assert 'subtypes' in osbs_build assert osbs_build['subtypes'] == [] assert 'engine' in osbs_build assert osbs_build['engine'] == KOJI_SOURCE_ENGINE assert 'image' in extra image = extra['image'] assert isinstance(image, dict) assert image['sources_for_nvr'] == SOURCES_FOR_KOJI_NVR assert image['sources_signing_intent'] == SOURCES_SIGNING_INTENT if expected_media_types: media_types = image['media_types'] assert isinstance(media_types, list) assert sorted(media_types) == sorted(expected_media_types) for buildroot in buildroots: self.validate_buildroot(buildroot, source=True) # Unique within buildroots in this metadata assert len([b for b in buildroots if b['id'] == buildroot['id']]) == 1 for output in output_files: self.validate_output(output, has_config, source=True) buildroot_id = output['buildroot_id'] # References one of the buildroots assert len([buildroot for buildroot in buildroots if buildroot['id'] == buildroot_id]) == 1 build_id = runner.plugins_results[KojiImportSourceContainerPlugin.key] assert build_id == "123" uploaded_filename = 'docker-image-{}.{}.tar.gz'.format(expect_id, os.uname()[4]) assert set(session.uploaded_files.keys()) == { OSBS_BUILD_LOG_FILENAME, uploaded_filename, } osbs_build_log = session.uploaded_files[OSBS_BUILD_LOG_FILENAME] assert osbs_build_log == b"log message A\nlog message B\nlog message C\n" assert workflow.data.annotations['koji-build-id'] == '123' @pytest.mark.parametrize('build_metadatas,platform,_filter,expected', [ [{}, None, None, []], [{}, None, {}, []], [{}, None, {"type": "docker-image"}, []], [{"x86_64": {"output": []}}, None, {"type": "docker-image"}, []], # No output is found by non-existing type. [{"x86_64": {"output": [{"type": "log"}]}}, None, {"type": "docker-image"}, []], # No output is found by unknown key. [{"x86_64": {"output": [{"type": "log"}]}}, None, {"filename": "file.tar.gz"}, []], [ {"x86_64": {"output": [{"type": "log"}]}}, None, {"type": "log", "filename": "file.tar.gz"}, [], ], # Output is found by type. [ {"x86_64": {"output": [{"type": "log"}, {"type": "docker-image"}]}}, None, {"type": "docker-image"}, [("x86_64", {"type": "docker-image"})], ], # No output is found with multiple filters. [ { "x86_64": { "output": [ {"type": "log", "filename": "build.log"}, {"type": "docker-image", "filename": "img.tar.gz"}, ], }, }, None, {"type": "docker-image", "filename": "img-file"}, [], ], # Find out output with multiple filters [ { "x86_64": { "output": [ {"type": "log", "filename": "build.log"}, {"type": "docker-image", "filename": "img.tar.gz"}, ], }, }, None, {"type": "docker-image", "filename": "img.tar.gz"}, [("x86_64", {"type": "docker-image", "filename": "img.tar.gz"})], ], # No output if platform does not exist. [{"x86_64": {"output": [{"type": "log", "filename": "build.log"}]}}, "s390x", None, []], # Filter outputs by platform [ {"x86_64": {"output": [{"type": "log", "filename": "build.log"}]}}, "x86_64", None, [("x86_64", {"type": "log", "filename": "build.log"})], ], # Filter outputs by combination of platform and filter [ { "x86_64": { "output": [ {"type": "log", "filename": "build.log"}, {"type": "docker-image", "filename": "img.tar.gz"}, ], }, }, "x86_64", {"type": "docker-image"}, [("x86_64", {"type": "docker-image", "filename": "img.tar.gz"})], ], # Iterator outputs from multiple platforms [ { "x86_64": { "output": [ {"type": "log", "filename": "build.log"}, {"type": "docker-image", "filename": "img.tar.gz"}, ], }, "s390x": { "output": [ {"type": "log", "filename": "build.log"}, {"type": "docker-image", "filename": "img.tar.gz"}, ], }, }, None, {"type": "docker-image"}, [ ("x86_64", {"type": "docker-image", "filename": "img.tar.gz"}), ("s390x", {"type": "docker-image", "filename": "img.tar.gz"}), ], ], [ { "x86_64": { "output": [ {"type": "log", "filename": "build.log"}, {"type": "docker-image", "filename": "img.tar.gz"}, ], }, "s390x": { # s390x will not be included since no output in docker-image type. "output": [{"type": "log", "filename": "build.log"}], }, }, None, {"type": "docker-image"}, [("x86_64", {"type": "docker-image", "filename": "img.tar.gz"})], ], ]) def test_iter_build_metadata_outputs( self, build_metadatas, platform, _filter, expected, workflow ): mock_reactor_config(workflow) workflow.data.plugins_results[GatherBuildsMetadataPlugin.key] = build_metadatas plugin = KojiImportPlugin(workflow) outputs = list(plugin._iter_build_metadata_outputs(platform, _filter=_filter)) assert expected == outputs @pytest.mark.parametrize("fs_result,expected,log", [ [None, None, None], [{}, None, "expected filesystem-koji-task-id in result"], [{"other-result": 1234}, None, "expected filesystem-koji-task-id in result"], [{"filesystem-koji-task-id": "task_id"}, None, f"invalid task ID {'task_id'!r}"], [{"filesystem-koji-task-id": 1}, 1, None], [{"filesystem-koji-task-id": "1"}, 1, None], ]) def test_property_filesystem_koji_task_id(self, fs_result, expected, log, workflow, caplog): mock_reactor_config(workflow) workflow.data.plugins_results[PLUGIN_ADD_FILESYSTEM_KEY] = fs_result plugin = KojiImportPlugin(workflow) assert expected == plugin._filesystem_koji_task_id if log is not None: assert log in caplog.text @pytest.mark.parametrize('has_op_appregistry_manifests', [True, False]) @pytest.mark.parametrize('has_op_bundle_manifests', [True, False]) def test_binary_build_metadata_includes_exported_operator_manifests( self, has_op_appregistry_manifests, has_op_bundle_manifests, workflow, source_dir ): session = MockedClientSession('') mock_environment(workflow, source_dir, has_op_appregistry_manifests=has_op_appregistry_manifests, has_op_bundle_manifests=has_op_bundle_manifests, name='ns/name', version='1.0', release='1', session=session) runner = create_runner(workflow) runner.run() data = session.metadata assert 'build' in data build = data['build'] assert isinstance(build, dict) assert 'extra' in build extra = build['extra'] assert isinstance(extra, dict) assert 'osbs_build' in extra osbs_build = extra['osbs_build'] if has_op_appregistry_manifests or has_op_bundle_manifests: assert 'operator_manifests_archive' in extra operator_manifests = extra['operator_manifests_archive'] assert isinstance(operator_manifests, str) assert operator_manifests == OPERATOR_MANIFESTS_ARCHIVE assert 'typeinfo' in extra assert 'operator-manifests' in extra['typeinfo'] operator_typeinfo = extra['typeinfo']['operator-manifests'] assert isinstance(operator_typeinfo, dict) assert operator_typeinfo['archive'] == OPERATOR_MANIFESTS_ARCHIVE else: assert 'operator_manifests_archive' not in extra assert 'typeinfo' not in extra assert osbs_build['subtypes'] == [ stype for yes, stype in [ (has_op_appregistry_manifests, KOJI_SUBTYPE_OP_APPREGISTRY), (has_op_bundle_manifests, KOJI_SUBTYPE_OP_BUNDLE) ] if yes ] # Find the operator manifests output output = None for item in session.metadata['output']: if item['type'] == KOJI_BTYPE_OPERATOR_MANIFESTS: output = item break if not has_op_bundle_manifests and not has_op_appregistry_manifests: assert output is None, \ 'Metadata output should not have exported operator manifests.' return assert output is not None, 'Missing output of exported operator manifests' expected_buildroot_id = session.metadata['buildroots'][0]['id'] assert expected_buildroot_id == output['buildroot_id'] assert OPERATOR_MANIFESTS_ARCHIVE in session.uploaded_files
"use strict"; "undefined" != typeof AOS && AOS.init({ duration: 700, easing: "ease-out-quad", once: !0, startEvent: "load", }), (function () { var e = document.querySelectorAll(".card-stack"), o = ["load", "resize", "scroll"]; [].forEach.call(e, function (e) { var t = e.querySelectorAll(".card-stack-item"); o.forEach(function (e) { window.addEventListener(e, function () { var d = [].slice.call(t).reverse(); d.reduce(function (e, t, o) { var n = t.clientHeight + parseInt( window.getComputedStyle(t).getPropertyValue("margin-bottom") ), a = e + (n - (d[o - 1] ? d[o - 1].offsetTop - t.offsetTop : n)) / n, r = t.firstElementChild, l = r.firstElementChild, c = "calc(-1rem * " + a + ")", i = "calc(1 - .2 * " + a + ")", s = "calc(1 - .03 * " + a + ")"; return ( (r.style.transform = "translateY(" + c + ") scale(" + s + ")"), (l.style.opacity = i), a ); }, 0); }); }); }); })(), (function () { var e = document.querySelectorAll('[data-toggle="countup"]'); function o(e) { var t = e.dataset.from ? +e.dataset.from : null, o = e.dataset.to ? +e.dataset.to : null, n = e.dataset.decimals ? +e.dataset.decimals : null, a = e.dataset.duration ? +e.dataset.duration : null, r = e.dataset.options ? JSON.parse(e.dataset.options) : null, l = new CountUp(e, t, o, n, a, r); l.error ? console.error(l.error) : (l.start(), e.classList.add("counted")); } "undefined" != typeof CountUp && e && [].forEach.call(e, function (e) { "countup:in" !== e.getAttribute("data-aos-id") && o(e); }), document.addEventListener("aos:in:countup:in", function (e) { if (e.detail instanceof Element) o(e.detail); else { var t = document.querySelectorAll( '.aos-animate[data-aos-id="countup:in"]:not(.counted)' ); [].forEach.call(t, function (e) { o(e); }); } }); })(), jQuery().fancybox && (($.fancybox.defaults.image.preload = !1), ($.fancybox.defaults.toolbar = !1), ($.fancybox.defaults.clickContent = !1)), (function () { var e = document.querySelectorAll('[data-toggle="flickity"]'); "undefined" != typeof Flickity && e && [].forEach.call(e, function (o) { o.addEventListener("click", function () { var e = parseInt(o.dataset.slide), t = document.querySelector(o.dataset.target); Flickity.data(t).selectCell(e); }); }); })(), (function () { var e = document.querySelectorAll(".highlight"); "undefined" != typeof hljs && e && [].forEach.call(e, function (e) { hljs.highlightBlock(e); }); })(), (function () { var e = document.querySelectorAll("[data-isotope]"), t = document.querySelectorAll("[data-filter]"), o = ["click"]; e && t && Isotope && imagesLoaded && (window.onload = function () { [].forEach.call(e, function (e) { var t, o; (t = e), (o = Isotope.data(t)), new imagesLoaded(t, function () { o.layout(); }); }), [].forEach.call(t, function (t) { t.addEventListener(o[0], function (e) { !(function (e, t) { e.preventDefault(); var o = t.dataset.filter, n = document.querySelector(t.dataset.target); Isotope.data(n).arrange({ filter: o }); })(e, t); }); }); }); })(), (function () { var e = document.querySelectorAll("[data-map]"); "undefined" != typeof mapboxgl && e && [].forEach.call(e, function (e) { var t, o, n, a; (o = (t = e).dataset.map ? JSON.parse(t.dataset.map) : {}), (n = { container: t, style: "mapbox://styles/mapbox/streets-v11", scrollZoom: !1, interactive: !1, }), (a = Object.assign(n, o)), (mapboxgl.accessToken = "pk.eyJ1IjoiZ29vZHRoZW1lcyIsImEiOiJjanU5eHR4N2cybDU5NGVwOHZwNGprb3E0In0.msdw9q16dh8v4azJXUdiXg"), new mapboxgl.Map(a); }); })(), (function () { var e = document.querySelectorAll(".modal"); $(e).on({ "show.bs.modal": function () { document.documentElement.style.overflowX = "visible"; }, "hidden.bs.modal": function () { document.documentElement.style.overflowX = ""; }, }); })(), (function () { var e = document.querySelectorAll( ".navbar-nav .dropdown, .navbar-nav .dropright" ), t = document.querySelectorAll(".navbar-nav .dropdown"), o = document.querySelectorAll(".navbar-nav .dropright"), a = ["mouseenter"], r = ["mouseleave", "click"], l = 16; function c(e) { var t, o, n, a, r; window.innerWidth < 992 || (e.classList.add("showing"), setTimeout(function () { e.classList.remove("showing"), e.classList.add("show"); }, 1), (t = e.parentElement), (o = t.parentElement), (n = o.classList.contains("dropright")), (a = n ? [-32, 0] : [0, 0]), (r = n ? "right-start" : "auto"), Popper.createPopper(o, t, { placement: r, modifiers: [ { name: "offset", options: { offset: a } }, { name: "preventOverflow", options: { padding: l } }, ], })); } [].forEach.call(e, function (t) { var n = t.querySelector(".dropdown-menu"); a.forEach(function (e) { t.addEventListener(e, function () { c(n); }); }), r.forEach(function (e) { t.addEventListener(e, function (e) { var t, o; (t = e), (o = n), window.innerWidth < 992 || (o.classList.contains("show") && (("click" === t.type && t.target.closest(".dropdown-menu form")) || (o.classList.add("showing"), o.classList.remove("show"), setTimeout(function () { o.classList.remove("showing"); }, 200)))); }); }); }), [].forEach.call(o, function (e) { var t = e.querySelector('[data-toggle="dropdown"]'), o = e.querySelector(".dropdown-menu"); t.addEventListener("click", function (e) { e.preventDefault(), (function (e, t) { if (!(992 <= window.innerWidth)) { e.stopPropagation(); var o = t.parentElement .closest(".dropdown-menu") .querySelectorAll(".dropdown-menu"); [].forEach.call(o, function (e) { e !== t && e.classList.remove("show"); }), t.classList.toggle("show"); } })(e, o); }); }), $(t).on("hide.bs.dropdown", function () { var e = this.querySelectorAll(".dropright .dropdown-menu"); [].forEach.call(e, function (e) { var t; (t = e), 992 <= window.innerWidth || t.classList.remove("show"); }); }); })(), (function () { var e = document.querySelectorAll(".navbar-reveal"), t = ["load", "scroll"], a = window.pageYOffset; e && [].forEach.call(e, function (n) { t.forEach(function (e) { window.addEventListener(e, function () { var e, t, o; (e = n), (t = window.pageYOffset), (o = a < t && 0 < t ? "-100%" : "0"), e.querySelector(".navbar-collapse").classList.contains("show") || (e.style.transform = "translateY(".concat(o, ")")), (a = t); }); }); }); })(), (function () { var e = document.querySelectorAll(".navbar"), r = ["load", "scroll"]; function c(e) { e.classList.remove("navbar-dark"), e.classList.add("navbar-light"), (e.style.boxShadow = "inset 1000px 1000px 1000px white"); } function i(e) { e.classList.remove("navbar-light"), e.classList.add("navbar-dark"), s(e); } function s(e) { e.style.boxShadow = ""; } function l(e, t, o, n, a) { var r = window.pageYOffset, l = a.classList.contains("show"); "show" === e.type && c(t), "hidden" === e.type && o && s(t), "hidden" === e.type && ((!n && !o) || (n && !r)) && i(t), ("load" !== e && "scroll" !== e) || !n || l || (r ? c : i)(t); } [].forEach.call(e, function (t) { var o = t.querySelector(".navbar-collapse"), n = t.classList.contains("navbar-light"), a = t.classList.contains("navbar-togglable"); r.forEach(function (e) { window.addEventListener(e, function () { l(e, t, n, a, o); }); }), $(o).on("show.bs.collapse hidden.bs.collapse", function (e) { l(e, t, n, a, o); }); }); })(), (function () { var e = document.querySelectorAll('[data-toggle="password"]'); [].forEach.call(e, function (n) { n.addEventListener("click", function (e) { e.preventDefault(); var t = document.querySelector(n.getAttribute("href")), o = "password" === t.type ? "text" : "password"; t.type = o; }); }); })(), (function () { var e = document.querySelectorAll('[data-toggle="popover"]'); e && $(e).popover(); })(), (function () { var e = document.querySelectorAll('[data-toggle="price"]'); "undefined" != typeof CountUp && e && [].forEach.call(e, function (r) { r.addEventListener("click", function () { var e = r.dataset.target, t = document.querySelector(e), o = t.innerHTML, n = r.dataset.value, a = new CountUp(t, o, n); a.error ? console.error(a.error) : a.start(); }); }); })(), (function () { var e = document.querySelectorAll('[data-toggle="prices"]'); "undefined" != typeof CountUp && e && [].forEach.call(e, function (o) { o.addEventListener("change", function () { var e = o.dataset.target, t = document.querySelectorAll(e), r = o.checked; [].forEach.call(t, function (e) { var t = e.dataset.minValue, o = e.dataset.maxValue, n = e.innerHTML, a = new CountUp(e, n, r ? o : t); a.error ? console.error(a.error) : a.start(); }); }); }); })(), (function () { var e = "[data-scroll]"; "undefined" != typeof SmoothScroll && new SmoothScroll(e, { header: ".navbar.fixed-top", offset: function (e, t) { return t.dataset.offset ? t.dataset.offset : 24; }, }); })(), (function () { var e = document.querySelectorAll(".svg-shim > svg"); /MSIE \d|Trident.*rv:/.test(navigator.userAgent) && [].forEach.call(e, function (e) { !(function (e) { var t = window.getComputedStyle(e, null).getPropertyValue("color"), o = new XMLSerializer().serializeToString(e); o = "data:image/svg+xml," + (o = (o = (o = (o = (o = (o = o.replace( /currentColor/g, t )).replace(/\s\s+/g, " ")).replace(/</g, "%3C")).replace( />/g, "%3E" )).replace(/#/g, "%23")).replace(/"/g, "'")); var n = document.createElement("img"); (n.src = o), (n.alt = "..."); var a = e.parentNode; a.appendChild(n), a.removeChild(e); })(e); }); })(), (function () { var e = document.querySelectorAll(".table-clickable [data-href]"); [].forEach.call(e, function (t) { t.addEventListener("click", function (e) { e.preventDefault(), (document.location.href = t.dataset.href); }); }); })(), (function () { var e = document.querySelectorAll('[data-toggle="table-features"]'); [].forEach.call(e, function (t) { t.addEventListener("change", function () { var e = t.dataset.target; document.querySelector(e).classList.toggle("table-features-alt"); }); }); })(), (function () { var e = document.querySelectorAll('[data-toggle="tooltip"]'); e && $(e).tooltip(); })(), (function () { var e = document.querySelectorAll("[data-typed]"); "undefined" != typeof Typed && e && [].forEach.call(e, function (e) { var t = e.dataset.options ? JSON.parse(e.dataset.options) : {}, o = Object.assign( { typeSpeed: 30, backSpeed: 30, backDelay: 2e3, loop: !0 }, t ); new Typed(e, o); }); })();
#!/usr/bin/env python3 # # Copyright (c) 2020 Xiaomi Corporation (authors: Haowen Qiu) # # See ../../../LICENSE for clarification regarding multiple authors # To run this single test, use # # ctest --verbose -R remove_epsilon_test_py import unittest import k2 class TestRemoveEpsilon(unittest.TestCase): def test1(self): s = ''' 0 4 1 1 0 1 1 1 1 2 0 2 1 3 0 3 1 4 0 2 2 7 0 4 3 7 0 5 4 6 1 2 4 6 0 3 4 8 1 3 4 9 -1 2 5 9 -1 4 6 9 -1 3 7 9 -1 5 8 9 -1 6 9 ''' fsa = k2.Fsa.from_str(s) prop = fsa.properties self.assertFalse(prop & k2.fsa_properties.EPSILON_FREE) dest = k2.remove_epsilon(fsa) prop = dest.properties self.assertTrue(prop & k2.fsa_properties.EPSILON_FREE) log_semiring = False self.assertTrue(k2.is_rand_equivalent(fsa, dest, log_semiring)) class TestRemoveEpsilonsIterativeTropical(unittest.TestCase): def test1(self): s = ''' 0 1 0 1 1 1 2 0 2 1 2 3 0 3 1 3 4 4 4 1 3 5 -1 5 1 4 5 -1 6 1 5 ''' fsa = k2.Fsa.from_str(s) print(fsa.aux_labels) prop = fsa.properties self.assertFalse(prop & k2.fsa_properties.EPSILON_FREE) dest = k2.remove_epsilons_iterative_tropical(fsa) prop = dest.properties self.assertTrue(prop & k2.fsa_properties.EPSILON_FREE) log_semiring = False self.assertTrue(k2.is_rand_equivalent(fsa, dest, log_semiring)) if __name__ == '__main__': unittest.main()
import codepen from './codepen' import repl from './repl' import codesandbox from './codesandbox' export const editorsEndpoints = wrapper => ({ codepen: codepen(wrapper), repl: repl(wrapper), codesandbox: codesandbox(wrapper) })
// login.js //明文密码插件初始化 $(function(){ $('#password').togglePassword({ el: '#togglePassword' }); }); $(function(){ //用JS原生方法实现JQuery的toggle()方法 function hasClass(obj, cls) { return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); } function addClass(obj, cls) { if (!this.hasClass(obj, cls)) obj.className += " " + cls; } function removeClass(obj, cls) { if (hasClass(obj, cls)) { var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); obj.className = obj.className.replace(reg, ' '); } } function toggleClass(obj,cls){ if(hasClass(obj,cls)){ removeClass(obj, cls); }else{ addClass(obj, cls); } } function toggleClassTest(){ var obj = document. getElementById('togglePassword'); toggleClass(obj,"icon-yanjing"); } //异步方法处理登录数据 function getUser() { var name = $(".login-user").val(); var pwd = $(".login-pass").val(); if(name.length === 0) { // alert("请输入用户名!"); $(".login-prove").html("请输入用户名"); $(".login-prove").css("display","block"); return false; } if(pwd.length === 0) { // alert("请输入密码!"); $(".login-prove").html("请输入密码"); $(".login-prove").css("display","block"); return false; } return { username: name, pwd: pwd } } function login() { var user = getUser(); if(!user) { return; } console.log(user); http.login( user, function(res) { console.log(res); if(res.code === 40010 || res.code === 40011) { $(".login-prove").css("display","block"); $(".login-user").val(""); $(".login-pass").val(""); } if(res.code === 200) { removeCover(); $('.cover').remove(); $('.login').css('display','none'); var ls = window.localStorage; ls.setItem("username",res.username); ls.setItem("userState",true); // 点击登陆后刷新借鉴,重新从服务器获取数据 setTimeout(location.reload(),10000); } }, function(xhr, err, type) { console.log(xhr); console.log(err); console.log(type); } ) } // 回车登陆 function enter(){ if (event.which == 13) { event.preventDefault(); login(); } } $(".login-log").click(login); $(".login-user").keydown(enter); $(".login-pass").keydown(enter); //注册提交数据 function getPost() { var name = $(".register-user").val(); var pwd = $(".register-pass").val(); var reconfirmpwd = $(".register-sec-pass").val(); var email = $(".register-email").val(); var blog = $(".register-blog").val(); return { username: name, pwd: pwd, reconfirmpwd: reconfirmpwd, email: email, blog: blog } } //忘记密码提交数据 function getRemember() { var username = $(".remember-user").val(); var email = $(".remember-email").val(); return { username: username, email: email } } //验证码数据提交 function getCode() { var username = $(".remember-user").val(); var email = $(".remember-email").val(); var code = $(".remember-prove").val(); return { username: username, email: email, code: code } } //重置密码数据提交 function getPass() { var pwd = $(".reset-new").val(); var reconfirmpwd = $(".sec-reset").val(); return { pwd: pwd, reconfirmpwd: reconfirmpwd } } // //用户名重复检验 // function getRepeat() { // var pwd = $(".register-tip").val(); // var reconfirmpwd = $(".sec-reset").val(); // return { // pwd: pwd, // reconfirmpwd: reconfirmpwd // } // } //点击输入框label标签内文字变色 function changeColor(input) { input.focus(function() { input.prev().css("color","#000000"); }); input.blur(function() { input.prev().css("color","#b0b0b0"); }) } changeColor($(".register-user")); changeColor($(".register-pass")); changeColor($(".register-sec-pass")); changeColor($(".register-email")); changeColor($(".register-blog")); //注册表单验证 function form() { var oName = document.getElementsByClassName('register-user')[0]; var oPass = document.getElementsByClassName('register-pass')[0]; var oSecPass = document.getElementsByClassName('register-sec-pass')[0]; var oEmail = document.getElementsByClassName('register-email')[0]; var oBlog = document.getElementsByClassName('register-blog')[0]; var count = document.getElementsByClassName('register-count')[0]; var tip = document.getElementsByClassName('register-tip')[0]; var userHint = document.getElementsByClassName('user-hint')[0]; var passwordHint = document.getElementsByClassName('password-hint')[0]; var confirmHint = document.getElementsByClassName('confirm-hint')[0]; var emailHint = document.getElementsByClassName('email-hint')[0]; var blogHint = document.getElementsByClassName('blog-hint')[0]; var oNameLength = 0; var stateOne = false; var stateTwo = false; var stateThree = false; var stateFour = false; var stateFive = false; //定义一个函数,用于获取输入框内输入字符的长度并把汉字转化为双字符。 function getLength(str) { // \x00-xff代表单字节字符。 return str.replace(/[^\x00-\xff]/g, "xx").length; } //提示输入字符个数 oName.onkeyup = function() { oNameLength = getLength(this.value); count.innerHTML = oNameLength + '个字符'; if (oNameLength == 0) { count.innerHTML = ''; } console.log(oNameLength); } //user oName.onblur = function() { oNameLength = getLength(this.value); if(oNameLength > 0 && oNameLength < 11) { userHint.innerHTML = "&#10004"; userHint.style.color = "#99FF00"; stateOne = true; } else { userHint.innerHTML = "&#10006"; userHint.style.color = "#FF6600"; stateOne = false; } } // password //密码强度提示函数封装 function passWord(li) { if($(this).val().length > 5) { li[0].style.display = "block"; } else { li[0].style.display = "none"; } if($(this).val().length > 8) { li[1].style.display = "block"; } else { li[1].style.display = "none"; } if($(this).val().length > 11) { li[2].style.display = "block"; } else { li[2].style.display = "none"; } if($(this).val().length > 14) { li[3].style.display = "block"; } else { li[3].style.display = "none"; } } var power = $('.power li'); var secPower = $('.sec-power li'); $('.register-pass').keyup(function() { passWord.call(this, power); }); $('.reset-new').keyup(function() { passWord.call(this, secPower); }); //检查密码格式 oPass.onblur = function() { var reg = /^[a-zA-Z]\w{5,15}$/; if(reg.test(this.value)) { passwordHint.innerHTML = "&#10004"; passwordHint.style.color = "#99FF00"; stateTwo = true; } else{ passwordHint.innerHTML = "&#10006"; passwordHint.style.color = "#FF6600"; stateTwo = false; } } // confirm oSecPass.onblur = function() { if(oPass.value != '' && oPass.value === oSecPass.value) { confirmHint.innerHTML = "&#10004"; confirmHint.style.color = "#99FF00"; stateThree = true; } else{ confirmHint.innerHTML = "&#10006"; confirmHint.style.color = "#FF6600"; stateThree = false; } } // email oEmail.onblur = function() { var conReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/; if(conReg.test(this.value)) { emailHint.innerHTML = "&#10004"; emailHint.style.color = "#99FF00"; stateFour = true; } else{ emailHint.innerHTML = "&#10006"; emailHint.style.color = "#FF6600"; stateFour = false; } } // blog oBlog.onblur = function() { if($(this).val().length == 0) { blogHint.innerHTML = "&#10006"; blogHint.style.color = "#FF6600"; stateFive = false; } else { blogHint.innerHTML = "&#10004"; blogHint.style.color = "#99FF00"; stateFive = true; } } //重置密码检验 var resetNew = document.getElementsByClassName('reset-new')[0]; var secPasswordHint = document.getElementsByClassName('sec-password-hint')[0]; var secReset = document.getElementsByClassName('sec-reset')[0]; var secConfirmHint = document.getElementsByClassName('sec-confirm-hint')[0]; var resetCompare = document.getElementsByClassName('reset-compare')[0]; var stateSix = false; var stateSeven = false; resetNew.onblur = function() { var reg = /^[a-zA-Z]\w{5,15}$/; if(reg.test(this.value)) { secPasswordHint.innerHTML = "&#10004"; secPasswordHint.style.color = "#99FF00"; stateSix = true; } else{ secPasswordHint.innerHTML = "&#10006"; secPasswordHint.style.color = "#FF6600"; stateSix = false; } } secReset.onblur = function() { if(resetNew.value != '' && secReset.value === resetNew.value) { secConfirmHint.innerHTML = "&#10004"; secConfirmHint.style.color = "#99FF00"; resetCompare.style.display = "none"; stateSeven = true; } else{ secConfirmHint.innerHTML = "&#10006"; secConfirmHint.style.color = "#FF6600"; resetCompare.style.display = "block"; stateSeven = false; } } //各个界面之间切换 var clickNumber = 1; $(".remember-next").click(function() { if(clickNumber == 1) { $(".remember-next").addClass('add'); $(".remember-hidden").css('display','block'); clickNumber++; } else { var data = getCode(); console.log(data); http.post( '/lost/verifycode', data, function(res){ if(res.code === 200){ window.localStorage.setItem('vericode', res.auth); $(".remember").css("display","none"); $(".remember-reset").css("display","block"); console.log('fgfgf'); } if(res.code === 100013){ $(".remember-error").css("display","block"); } if(res.code === 100014){ $(".remember-error").html("验证信息过期"); $(".remember-error").css("display","block"); } }, function(err){ console.log(err) } ) } }); $(".login-register").click(function() { $(".login").css("display","none"); $(".register").css("display","block"); }); $(".register-sure").click(function() { if(stateOne == true && stateTwo == true && stateThree == true && stateFour == true && stateFive == true) { var data = getPost(); console.log(data); http.post( '/register', data, function(res){ if(res.code === 200){ $(".register").css("display","none"); $(".login").css("display","block"); } }, function(err){ console.log(err) } ) } else { return false; } }); $('.remember-next').click(function() { var data = getRemember(); console.log(data); http.post( '/lost/verifyuser', data, function(res){ if(res.code === 100010 || res.code === 100011){ $(".remember-tip").css("display","block"); } }, function(err){ console.log(err) } ) }) $('.remember-send').click(function() { var data = getRemember(); console.log(data); http.post( '/lost/sendcode', data, // function(res){ // if(res.code === 100010 || res.code === 100011){ // $(".remember-tip").css("display","block"); // } // }, function(err){ console.log(err) } ) }) $(".login-found").click(function() { $(".login").css("display","none"); $(".remember").css("display","block"); }); $(".reset-confirm").click(function() { var data = getPass(); var vericode = window.localStorage.getItem('vericode'); data.auth = vericode; console.log(data); http.post( '/lost/updatepwd', data, function(res){ if(res.code === 200){ window.localStorage.clear(); $(".remember-reset").css("display","none"); $(".login").css("display","block"); } }, function(err){ console.log(err) } ) }); } form(); //登录注册界面消失 function addCover(){ $('.nav').css('display','none'); $('.main-container').addClass('hide-main'); } function removeCover(){ $('.nav').css('display','flex'); $('.main-container').removeClass('hide-main'); } $('.login-in').click(function() { console.log("test"); addCover(); $('.show-detail').after('<div class="cover "></div>'); $('.login').css('display','block'); $(".login-user").focus(); }) $('.icon-Delete').click(function() { removeCover(); $('.cover').remove(); $('.login').css('display','none'); $('.register').css('display','none'); $('.remember').css('display','none'); $('.remember-reset').css('display','none'); }) });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Schedule = void 0; class Schedule { constructor(triggerScheduler) { this.enabled = false; this.name = 'New Schedule'; this.triggers = []; if (triggerScheduler == null) { throw new Error(`triggerScheduler may not be null or undefined`); } this.triggerScheduler = triggerScheduler; } setEnabled(enabled) { if (enabled !== this.enabled) { if (enabled) { this.getTriggers().forEach((t) => this.triggerScheduler.register(t)); } else { this.triggerScheduler.destroy(); } this.enabled = enabled; } } setName(name) { if (name == null) { throw new Error(`name may not be null or undefined`); } this.name = name; } isEnabled() { return this.enabled; } getName() { return this.name; } getTriggers() { return this.triggers; } addTrigger(trigger) { if (this.findTriggerById(trigger.getId())) { throw new Error(`Cannot add trigger, trigger id ${trigger.getId()} exists already`); } else { this.triggers.push(trigger); if (this.isEnabled()) { this.triggerScheduler.register(trigger); } } } updateTrigger(trigger) { const index = this.getTriggers().findIndex((t) => t.getId() === trigger.getId()); if (index == -1) { throw new Error(`Cannot update trigger, trigger id ${trigger.getId()} not found`); } else { if (this.isEnabled()) { this.triggerScheduler.unregister(this.getTriggers()[index]); this.triggerScheduler.register(trigger); } this.triggers[index] = trigger; } } removeTrigger(triggerId) { const trigger = this.triggers.find((t) => t.getId() === triggerId); if (trigger) { this.removeTriggerAndUnregister(trigger); } else { throw new Error(`Cannot delete trigger, trigger id ${triggerId} not found`); } } destroy() { if (this.isEnabled()) { this.triggerScheduler.destroy(); } this.triggers = []; } removeTriggerAndUnregister(trigger) { if (this.isEnabled()) { this.triggerScheduler.unregister(trigger); } this.triggers = this.triggers.filter((t) => t.getId() !== trigger.getId()); } findTriggerById(id) { return this.getTriggers().find((t) => t.getId() === id); } } exports.Schedule = Schedule;
'use strict'; app.controller('indexCtrl', ['$scope', '$http', '$settings', function indexCtrl($scope, $http, $settings) { // } ]);
# Copyright 2014 Openstack Foundation # All Rights Reserved. # # 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 random import sys import time from neutron.common import config from neutron.common import utils as n_utils from oslo_config import cfg from oslo_log import log as logging from quark.agent import xapi from quark.cache import security_groups_client as sg_cli CONF = cfg.CONF LOG = logging.getLogger(__name__) agent_opts = [ cfg.IntOpt("polling_interval", default=10, help=_("Number of seconds to wait between poll iterations of " "XAPI and the configured security groups registry.")) ] CONF.register_opts(agent_opts, "AGENT") def _sleep(): # NOTE(amir): add randomness to polling so all machines don't slam # the security groups registry at once time.sleep(CONF.AGENT.polling_interval + random.random() * 2) def partition_vifs(xapi_client, interfaces, security_group_states): """Splits VIFs into three explicit categories and one implicit Added - Groups exist in Redis that have not been ack'd and the VIF is not tagged. Action: Tag the VIF and apply flows Updated - Groups exist in Redis that have not been ack'd and the VIF is already tagged Action: Do not tag the VIF, do apply flows Removed - Groups do NOT exist in Redis but the VIF is tagged Action: Untag the VIF, apply default flows Self-Heal - Groups are ack'd in Redis but the VIF is untagged. We treat this case as if it were an "added" group. Action: Tag the VIF and apply flows NOOP - The VIF is not tagged and there are no matching groups in Redis. This is our implicit category Action: Do nothing """ added = [] updated = [] removed = [] for vif in interfaces: vif_has_groups = vif in security_group_states if vif.tagged and vif_has_groups and security_group_states[vif]: # Already ack'd these groups and VIF is tagged, reapply. # If it's not tagged, fall through and have it self-heal continue if vif.tagged: if vif_has_groups: updated.append(vif) else: removed.append(vif) else: if vif_has_groups: added.append(vif) # if not tagged and no groups, skip return added, updated, removed def ack_groups(client, groups): if len(groups) > 0: client.update_group_states_for_vifs(groups, True) def run(): """Fetches changes and applies them to VIFs periodically Process as of RM11449: * Get all groups from redis * Fetch ALL VIFs from Xen * Walk ALL VIFs and partition them into added, updated and removed * Walk the final "modified" VIFs list and apply flows to each """ groups_client = sg_cli.SecurityGroupsClient() xapi_client = xapi.XapiClient() interfaces = set() while True: try: interfaces = xapi_client.get_interfaces() except Exception: LOG.exception("Unable to get instances/interfaces from xapi") _sleep() continue try: sg_states = groups_client.get_security_group_states(interfaces) new_sg, updated_sg, removed_sg = partition_vifs(xapi_client, interfaces, sg_states) xapi_client.update_interfaces(new_sg, updated_sg, removed_sg) groups_to_ack = [v for v in new_sg + updated_sg if v.success] ack_groups(groups_client, groups_to_ack) except Exception: LOG.exception("Unable to get security groups from registry and " "apply them to xapi") _sleep() continue _sleep() def main(): config.init(sys.argv[1:]) config.setup_logging() n_utils.log_opt_values(LOG) if not CONF.config_file: sys.exit(_("ERROR: Unable to find configuration file via the default" " search paths (~/.neutron/, ~/, /etc/neutron/, /etc/) and" " the '--config-file' option!")) run()
import os import shutil import logging import tensorflow as tf import tensorflow_text as text import tensorflow_hub as hub from official.nlp import optimization # to create AdamW optimizer AUTOTUNE = tf.data.AUTOTUNE SEED = 42 def load_datasets(hparams): """Load pre-split tf.datasets. Args: hparams(dict): A dictionary containing model training arguments. Returns: raw_train_ds(tf.dataset): raw_val_ds(tf.dataset): raw_test_ds(tf.dataset): """ raw_train_ds = tf.keras.preprocessing.text_dataset_from_directory( hparams['data-dir'] + '/train', batch_size=hparams['batch-size'], validation_split=0.2, subset='training', seed=seed) raw_val_ds = tf.keras.preprocessing.text_dataset_from_directory( hparams['data-dir'] + '/train', batch_size=hparams['batch-size'], validation_split=0.2, subset='validation', seed=seed) raw_test_ds = tf.keras.preprocessing.text_dataset_from_directory( hparams['data-dir'] + '/test', batch_size=hparams['batch-size']) return raw_train_ds, raw_val_ds, test_ds def build_text_classifier(hparams, optimizer): """Train and evaluate TensorFlow BERT sentiment classifier. Args: hparams(dict): A dictionary containing model training arguments. Returns: history(tf.keras.callbacks.History): Keras callback that records training event history. """ text_input = tf.keras.layers.Input(shape=(), dtype=tf.string, name='text') preprocessor = hub.KerasLayer(hparams['tf-hub-bert-preprocessor'], name='preprocessing') encoder_inputs = preprocessor(text_input) encoder = hub.KerasLayer(hparams['tf-hub-bert-encoder'], trainable=True, name='BERT_encoder') outputs = encoder(encoder_inputs) classifier = outputs["pooled_output"] classifier = tf.keras.layers.Dropout(0.1, name="dropout")(net) classifier = tf.keras.layers.Dense(1, activation=None, name='classifier')(net) model = tf.keras.Model(text_input, net) loss = tf.keras.losses.BinaryCrossentropy(from_logits=True) metrics = tf.metrics.BinaryAccuracy() model.compile(optimizer=optimizer, loss=loss, metrics=metrics) return model def train_evaluate(hparams): """Train and evaluate TensorFlow BERT sentiment classifier. Args: hparams(dict): A dictionary containing model training arguments. Returns: history(tf.keras.callbacks.History): Keras callback that records training event history. """ train_ds, val_ds, test_ds = load_datasets(hparams) train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE) val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE) test_ds = test_ds.cache().prefetch(buffer_size=AUTOTUNE) epochs = hparams['epochs'] steps_per_epoch = tf.data.experimental.cardinality(train_ds).numpy() n_train_steps = steps_per_epoch * epochs n_warmup_steps = int(0.1*num_train_steps) optimizer = optimization.create_optimizer(init_lr=hparams['initial-learning-rate'], num_train_steps=n_train_steps, num_warmup_steps=n_warmup_steps, optimizer_type='adamw') with tf.distribute.MirroredStrategy(): model = build_model(hparams, optimizer=optimizer) logging.info(model.summary()) logging.info("Test accuracy: %s", model.evaluate(test_ds)) # Export Keras model in TensorFlow SavedModel format. model.save(hparams['model-dir']) return history
////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2014-present, Egret Technology. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the Egret nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS // OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////////////// var Main = (function (_super) { __extends(Main, _super); function Main() { _super.call(this); this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); } var d = __define,c=Main,p=c.prototype; p.onAddToStage = function (event) { //设置加载进度界面 //Config to load process interface this.loadingView = new LoadingUI(); this.stage.addChild(this.loadingView); //初始化Resource资源加载库 //initiate Resource loading library RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); RES.loadConfig("resource/default.res.json", "resource/"); }; /** * 配置文件加载完成,开始预加载preload资源组。 * configuration file loading is completed, start to pre-load the preload resource group */ p.onConfigComplete = function (event) { RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); RES.loadGroup("preload"); }; /** * preload资源组加载完成 * Preload resource group is loaded */ p.onResourceLoadComplete = function (event) { if (event.groupName == "preload") { this.stage.removeChild(this.loadingView); RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); this.createGameScene(); } }; /** * 资源组加载出错 * The resource group loading failed */ p.onItemLoadError = function (event) { console.warn("Url:" + event.resItem.url + " has failed to load"); }; /** * 资源组加载出错 * The resource group loading failed */ p.onResourceLoadError = function (event) { //TODO console.warn("Group:" + event.groupName + " has failed to load"); //忽略加载失败的项目 //Ignore the loading failed projects this.onResourceLoadComplete(event); }; /** * preload资源组加载进度 * Loading process of preload resource group */ p.onResourceProgress = function (event) { if (event.groupName == "preload") { this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal); } }; /** * 创建游戏场景 * Create a game scene */ p.createGameScene = function () { this.user = new User("Player01", 1); this.hero = new Hero("H001", "Heroine", Quality.ORAGE, 3, "Hero_png", HeroType.SABER); this.sword = new Weapon("W001", "Sword", Quality.ORAGE, WeaponType.HANDSWORD, "Weapon_jpg"); this.helment = new Armor("A001", "Helment", Quality.PURPLE, ArmorType.LIGHTARMOR, "Helment_jpg"); this.Defence = new Armor("A002", "Defence", Quality.GREEN, ArmorType.LIGHTARMOR, "Defence_jpg"); this.Armour = new Armor("A003", "Armour", Quality.BLUE, ArmorType.LIGHTARMOR, "Armour_jpg"); this.weaponJewel = new Jewel(Quality.ORAGE); this.armorJewel = new Jewel(Quality.WHITE); this.sword.addJewl(this.weaponJewel); this.helment.addJewl(this.armorJewel); this.Defence.addJewl(this.armorJewel); this.Armour.addJewl(this.armorJewel); this.hero.addWeapon(this.sword); this.hero.addHelment(this.helment); this.hero.addCorseler(this.Defence); this.hero.addShoes(this.Armour); this.user.addHeroInTeam(this.hero); this.user.addHeros(this.hero); this.userPanel = new UserPanel(); this.addChild(this.userPanel); this.userPanel.showHeroInformation(this.hero); this.userPanel.x = (this.stage.width - this.userPanel.width) / 2; this.userPanel.y = (this.stage.height - this.userPanel.height) / 2; //this.equipmentInformationPanel = new EquipmentInformationPanel(); this.userPanel.equipmentInformationPanel.showEquipmentInformation(this.sword); //this.addChild(this.userPanel.equipmentInformationPanel); }; /** * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。 * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json. */ p.createBitmapByName = function (name) { var result = new egret.Bitmap(); var texture = RES.getRes(name); result.texture = texture; return result; }; return Main; }(egret.DisplayObjectContainer)); egret.registerClass(Main,'Main'); //# sourceMappingURL=Main.js.map
const ReactNative = require('react-native'); const { AppCenterReactNative } = ReactNative.NativeModules; function format(tag, msg) { return `[${tag}] ${msg}`; } const AppCenterLog = { LogLevelVerbose: 2, LogLevelDebug: 3, LogLevelInfo: 4, LogLevelWarning: 5, LogLevelError: 6, LogLevelAssert: 7, LogLevelNone: 99, warn(tag, msg) { AppCenterReactNative.getLogLevel().then((logLevel) => { if (logLevel <= AppCenterLog.LogLevelWarning) { console.warn(format(tag, msg)); } }); }, error(tag, msg) { AppCenterReactNative.getLogLevel().then((logLevel) => { if (logLevel <= AppCenterLog.LogLevelError) { console.error(format(tag, msg)); } }); } }; module.exports = AppCenterLog;
define(["Ti/_/declare", "Ti/_/UI/KineticScrollView", "Ti/_/style", "Ti/_/lang", "Ti/UI"], function(declare, KineticScrollView, style, lang, UI) { var isDef = lang.isDef, // The amount of deceleration (in pixels/ms^2) deceleration = 0.001; return declare("Ti.UI.ScrollView", KineticScrollView, { constructor: function(args) { var self = this, contentContainer, scrollbarTimeout; this._initKineticScrollView(contentContainer = UI.createView({ width: UI.SIZE, height: UI.SIZE, _minWidth: "100%", _minHeight: "100%", left: 0, top: 0 }), "both", "both", 1); }, _handleMouseWheel: function() { this._isScrollBarActive && this.fireEvent("scroll",{ x: -this._currentTranslationX, y: -this._currentTranslationY, dragging: false, decelerating: false }); }, _handleDragStart: function() { this.fireEvent("dragStart"); }, _handleDrag: function() { this.fireEvent("scroll",{ x: -this._currentTranslationX, y: -this._currentTranslationY, dragging: true, decelerating: false }); }, _handleDragEnd: function(e, velocityX, velocityY) { if (isDef(velocityX)) { var self = this, velocity = Math.sqrt(velocityX * velocityX + velocityY * velocityY), distance = velocity * velocity / (1.724 * deceleration), duration = velocity / deceleration, theta = Math.atan(Math.abs(velocityY / velocityX)), distanceX = distance * Math.cos(theta) * (velocityX < 0 ? -1 : 1), distanceY = distance * Math.sin(theta) * (velocityY < 0 ? -1 : 1), translationX = Math.min(0, Math.max(self._minTranslationX, self._currentTranslationX + distanceX)), translationY = Math.min(0, Math.max(self._currentTranslationY + distanceY)); self.fireEvent("dragEnd",{ decelerate: true }); self._animateToPosition(translationX, translationY, duration, "ease-out", function() { self._setTranslation(translationX, translationY); self._endScrollBars(); self.fireEvent("scrollEnd"); }); } }, scrollTo: function(x, y) { self._setTranslation(x !== null ? -x : this._currentTranslationX, y !== null ? -y : this._currentTranslationX); }, _defaultWidth: UI.FILL, _defaultHeight: UI.FILL, _getContentOffset: function(){ return this.contentOffset; }, _preLayout: function() { var needsRecalculation = this._contentContainer.layout === this.layout this._contentContainer.layout = this.layout; return needsRecalculation; }, add: function(view) { this._contentContainer._add(view); this._publish(view); }, remove: function(view) { this._contentContainer.remove(view); this._unpublish(view); }, properties: { contentHeight: { get: function(value) { return this._contentContainer.height; }, set: function(value) { this._contentContainer.height = value; return value; } }, contentOffset: { get: function(value) { return { x: -this._currentTranslationX, y: -this._currentTranslationY }; }, set: function(value) { this._setTranslation(isDef(value.x) ? -value.x : this._currentTranslationX, isDef(value.y) ? -value.y : this._currentTranslationY); return value; } }, contentWidth: { get: function(value) { return this._contentContainer.width; }, set: function(value) { this._contentContainer.width = value; return value; } }, disableBounce: false, horizontalBounce: { set: function(value) { return this._horizontalElastic = value; }, value: true }, showHorizontalScrollIndicator: { set: function(value, oldValue) { if (value !== oldValue) { if (value) { this._createHorizontalScrollBar(); } else { this._destroyHorizontalScrollBar(); } } return value; }, value: true }, showVerticalScrollIndicator: { set: function(value, oldValue) { if (value !== oldValue) { if (value) { this._createVerticalScrollBar(); } else { this._destroyVerticalScrollBar(); } } return value; }, value: true }, verticalBounce: { set: function(value) { return this._verticalElastic = value; }, value: true } } }); });
/** * Created by CCNC on 2018/4/25. * echo服务器是一个处理重复性事件的简单例子,当你给它发送数据时,它会把这个数据返回回来。 * telnet设置,参考https://blog.csdn.net/zryxh1/article/details/18951613 */ var net = require('net'); var server = net.createServer(function(socket){ socket.on('data', function(data){//用on方法响应事件 console.log(data.toString());//显示在node控制台 socket.write(data);//显示在telnet控制台 }) }); server.listen(8888);
/****************************************************************************** * * Copyright (c) 2017, the Perspective Authors. * * This file is part of the Perspective library, distributed under the terms of * the Apache License 2.0. The full license can be found in the LICENSE file. * */ module.exports = perspective => { describe("Delete", function() { it("calls all delete callbacks registered on table", async function() { const table = perspective.table([{x: 1}]); const cb1 = jest.fn(); const cb2 = jest.fn(); table.on_delete(cb1); table.on_delete(cb2); await table.delete(); expect(cb1).toHaveBeenCalledTimes(1); expect(cb2).toHaveBeenCalledTimes(1); }); it("remove_delete unregisters table delete callbacks", async function() { const table = perspective.table([{x: 1}]); const cb1 = jest.fn(); const cb2 = jest.fn(); table.on_delete(cb1); table.on_delete(cb2); table.remove_delete(cb1); await table.delete(); expect(cb1).toHaveBeenCalledTimes(0); expect(cb2).toHaveBeenCalledTimes(1); }); it("calls all delete callbacks registered on view", async function() { const table = perspective.table([{x: 1}]); const view = table.view(); const cb1 = jest.fn(); const cb2 = jest.fn(); view.on_delete(cb1); view.on_delete(cb2); await view.delete(); expect(cb1).toHaveBeenCalledTimes(1); expect(cb2).toHaveBeenCalledTimes(1); await table.delete(); }); it("remove_delete unregisters view delete callbacks", async function() { const table = perspective.table([{x: 1}]); const view = table.view(); const cb1 = jest.fn(); const cb2 = jest.fn(); view.on_delete(cb1); view.on_delete(cb2); view.remove_delete(cb1); await view.delete(); expect(cb1).toHaveBeenCalledTimes(0); expect(cb2).toHaveBeenCalledTimes(1); await table.delete(); }); it("properly removes a failed delete callback on a table", async function(done) { const table = perspective.table([{x: 1}]); // when a callback throws, it should delete that callback table.on_delete(() => { throw new Error("something went wrong!"); }); table.delete(); done(); }); it("properly removes a failed delete callback on a view", async function(done) { const table = perspective.table([{x: 1}]); const view = table.view(); // when a callback throws, it should delete that callback view.on_delete(() => { throw new Error("something went wrong!"); }); view.delete(); table.delete(); done(); }); }); };
import {Data_Type} from '../../libs/byte_array/types.js'; export const Input_Type = { [Data_Type.text.value]: {value: Data_Type.text.value, name: Data_Type.text.name, default: true}, [Data_Type.hex.value]: {value: Data_Type.hex.value, name: Data_Type.hex.name, default: false}, [Data_Type.binary.value]: {value: Data_Type.binary.value, name: Data_Type.binary.name, default: false}, } Object.freeze(Input_Type); export const Input_Events = { SET_INPUT: Symbol('set_comm'), INSERT_INPUT: Symbol('insert_comm'), SEND_INPUT: Symbol('send_comm'), ENABLE: Symbol('enable'), CHANGE_TYPE: Symbol('change_type'), INSERT_KEY: Symbol('insert Key'), PASTE: Symbol('paste'), CHANGE_STATE: Symbol('change_state'), COMMAND_LIST: Symbol('command_list') } Object.freeze(Input_Events);
var gulp = require('gulp'); var plugins = require('gulp-load-plugins')({ rename: { 'gulp-buddy.js': 'buddy' } }); var buildConfig = require('../buildConfig'); var styleguide = require('sc5-styleguide'); var outputPath = 'public/assets/styleguide'; var config = require('../config'); module.exports = function() { gulp.task('doc', function (cb) { gulp.src(['README.md', './public/**/*.js'], {read: false}) .pipe(plugins.jsdoc3(cb)); }); gulp.task('styleguide:generate', function() { plugins.util.log( plugins.util.colors.bold('style-guide: '), plugins.util.colors.magenta('http://localhost:' + buildConfig.options.styleguide.port)); return gulp.src(buildConfig.FILES.FRONTEND_SASS) .pipe(styleguide.generate({ title: 'Kibibit Styleguide', server: true, rootPath: outputPath, overviewPath: 'README.md', port: buildConfig.options.styleguide.port, disableEncapsulation: true, extraHead: [ '<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.11.2/angular-material.min.css">', '<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/icon?family=Material+Icons">', '<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js">' ], "filesConfig": [ { "name": "kibibitCodeEditor", "files": [ //"http://localhost:" + config.port + "/assets/lib/bower_components/angular-material/angular-material.min.js", "http://localhost:" + config.port + "/assets/kibibit.styleguide.js", "http://localhost:" + config.port + "/app/components/searchProject/searchProject.js" ] } ] })) .pipe(gulp.dest(outputPath)); }); gulp.task('styleguide:applyStyles', function() { return gulp.src(buildConfig.FILES.MAIN_SASS) .pipe(plugins.sourcemaps.init()) .pipe(plugins.sass()) .pipe(styleguide.applyStyles()) .pipe(plugins.sourcemaps.write()) //.pipe(rename({ suffix: '.min' })) .pipe(gulp.dest(outputPath)); }); gulp.task('styleguide', ['styleguide:generate', 'styleguide:applyStyles']); };
import { isPresent, escape } from 'angular2/src/facade/lang'; /** * A message extracted from a template. * * The identity of a message is comprised of `content` and `meaning`. * * `description` is additional information provided to the translator. */ export class Message { constructor(content, meaning, description = null) { this.content = content; this.meaning = meaning; this.description = description; } } /** * Computes the id of a message */ export function id(m) { let meaning = isPresent(m.meaning) ? m.meaning : ""; let content = isPresent(m.content) ? m.content : ""; return escape(`$ng|${meaning}|${content}`); } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWVzc2FnZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImFuZ3VsYXIyL3NyYy9pMThuL21lc3NhZ2UudHMiXSwibmFtZXMiOlsiTWVzc2FnZSIsIk1lc3NhZ2UuY29uc3RydWN0b3IiLCJpZCJdLCJtYXBwaW5ncyI6Ik9BQU8sRUFBQyxTQUFTLEVBQUUsTUFBTSxFQUFDLE1BQU0sMEJBQTBCO0FBRTFEOzs7Ozs7R0FNRztBQUNIO0lBQ0VBLFlBQW1CQSxPQUFlQSxFQUFTQSxPQUFlQSxFQUFTQSxXQUFXQSxHQUFXQSxJQUFJQTtRQUExRUMsWUFBT0EsR0FBUEEsT0FBT0EsQ0FBUUE7UUFBU0EsWUFBT0EsR0FBUEEsT0FBT0EsQ0FBUUE7UUFBU0EsZ0JBQVdBLEdBQVhBLFdBQVdBLENBQWVBO0lBQUdBLENBQUNBO0FBQ25HRCxDQUFDQTtBQUVEOztHQUVHO0FBQ0gsbUJBQW1CLENBQVU7SUFDM0JFLElBQUlBLE9BQU9BLEdBQUdBLFNBQVNBLENBQUNBLENBQUNBLENBQUNBLE9BQU9BLENBQUNBLEdBQUdBLENBQUNBLENBQUNBLE9BQU9BLEdBQUdBLEVBQUVBLENBQUNBO0lBQ3BEQSxJQUFJQSxPQUFPQSxHQUFHQSxTQUFTQSxDQUFDQSxDQUFDQSxDQUFDQSxPQUFPQSxDQUFDQSxHQUFHQSxDQUFDQSxDQUFDQSxPQUFPQSxHQUFHQSxFQUFFQSxDQUFDQTtJQUNwREEsTUFBTUEsQ0FBQ0EsTUFBTUEsQ0FBQ0EsT0FBT0EsT0FBT0EsSUFBSUEsT0FBT0EsRUFBRUEsQ0FBQ0EsQ0FBQ0E7QUFDN0NBLENBQUNBIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHtpc1ByZXNlbnQsIGVzY2FwZX0gZnJvbSAnYW5ndWxhcjIvc3JjL2ZhY2FkZS9sYW5nJztcblxuLyoqXG4gKiBBIG1lc3NhZ2UgZXh0cmFjdGVkIGZyb20gYSB0ZW1wbGF0ZS5cbiAqXG4gKiBUaGUgaWRlbnRpdHkgb2YgYSBtZXNzYWdlIGlzIGNvbXByaXNlZCBvZiBgY29udGVudGAgYW5kIGBtZWFuaW5nYC5cbiAqXG4gKiBgZGVzY3JpcHRpb25gIGlzIGFkZGl0aW9uYWwgaW5mb3JtYXRpb24gcHJvdmlkZWQgdG8gdGhlIHRyYW5zbGF0b3IuXG4gKi9cbmV4cG9ydCBjbGFzcyBNZXNzYWdlIHtcbiAgY29uc3RydWN0b3IocHVibGljIGNvbnRlbnQ6IHN0cmluZywgcHVibGljIG1lYW5pbmc6IHN0cmluZywgcHVibGljIGRlc2NyaXB0aW9uOiBzdHJpbmcgPSBudWxsKSB7fVxufVxuXG4vKipcbiAqIENvbXB1dGVzIHRoZSBpZCBvZiBhIG1lc3NhZ2VcbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGlkKG06IE1lc3NhZ2UpOiBzdHJpbmcge1xuICBsZXQgbWVhbmluZyA9IGlzUHJlc2VudChtLm1lYW5pbmcpID8gbS5tZWFuaW5nIDogXCJcIjtcbiAgbGV0IGNvbnRlbnQgPSBpc1ByZXNlbnQobS5jb250ZW50KSA/IG0uY29udGVudCA6IFwiXCI7XG4gIHJldHVybiBlc2NhcGUoYCRuZ3wke21lYW5pbmd9fCR7Y29udGVudH1gKTtcbn0iXX0=
(window.webpackJsonp=window.webpackJsonp||[]).push([[13],{140:function(e){e.exports={pages:[{componentChunkName:"component---src-pages-index-zh-js",jsonName:"index",path:"/"},{componentChunkName:"component---src-pages-404-js",jsonName:"404-html-516",path:"/404.html"},{componentChunkName:"component---src-pages-404-js",jsonName:"404-22d",path:"/404/"},{componentChunkName:"component---src-pages-index-en-js",jsonName:"en-310",path:"/en/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"en-news-we-care-wc-lands-in-peoples-square-f19",path:"/en/news/WeCare-WC-Lands-in-Peoples-Square/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"en-news-the-queen-of-public-restrooms-xtd-plaza-a4a",path:"/en/news/the-queen-of-public-restrooms-xtd-plaza/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"en-news-wecare-wc-goes-portable-b2b",path:"/en/news/wecare-wc-goes-portable/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"en-news-wecare-wc-takes-off-in-pudong-airport-1b6",path:"/en/news/wecare-wc-takes-off-in-pudong-airport/"},{componentChunkName:"component---src-pages-page-2-en-js",jsonName:"en-page-2-065",path:"/en/page-2/"},{componentChunkName:"component---src-pages-my-files-js",jsonName:"my-files-317",path:"/my-files/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"news-we-care-wc落地上海人民广场景区-405",path:"/news/WeCare-WC落地上海人民广场景区/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"news-wecare-wc移动卫生间解决方案-a67",path:"/news/wecare-wc移动卫生间解决方案/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"news-公共卫生间之女王-d06",path:"/news/公共卫生间之女王/"},{componentChunkName:"component---src-templates-blog-post-js",jsonName:"news-喜迎进博会-we-care-wc浦东国际机场项目完成-52f",path:"/news/喜迎进博会WeCare-WC浦东国际机场项目完成/"},{componentChunkName:"component---src-pages-page-2-zh-js",jsonName:"page-2-fbc",path:"/page-2/"}],dataPaths:{"404-22d":"665/path---404-22-d-bce-ZNpXRWbCmk1qYofocrzTyxW3Q","404-html-516":"104/path---404-html-516-62a-ZNpXRWbCmk1qYofocrzTyxW3Q","dev-404-page-5f9":"920/path---dev-404-page-5-f-9-fab-NZuapzHg3X9TaN1iIixfv1W23E","en-310":"427/path---en-310-dec-a7eaqKu3DfGqDpgQlE13zqpX6Q","en-news-the-queen-of-public-restrooms-xtd-plaza-a4a":"175/path---en-news-the-queen-of-public-restrooms-xtd-plaza-a-4-a-c57-xer3hamGdKe0NI1UGUIVtbUk6co","en-news-we-care-wc-lands-in-peoples-square-f19":"765/path---en-news-we-care-wc-lands-in-peoples-square-f-19-019-hVHOp7443nX7NTl4Ddk9E2dhoM","en-news-wecare-wc-goes-portable-b2b":"741/path---en-news-wecare-wc-goes-portable-b-2-b-605-k3XUsMy7Ug5yE3DqcFTefYbQck","en-news-wecare-wc-takes-off-in-pudong-airport-1b6":"821/path---en-news-wecare-wc-takes-off-in-pudong-airport-1-b-6-579-0xOwuUzlDPYJVLv4kr1Venlzxc","en-page-2-065":"59/path---en-page-2-065-ac0-4xRSeOifC7Lu2rz5EVCuhBhW8A",index:"180/path---index-6a9-IPLCzxRrcaaCvBYP766WqHJQFs","my-files-317":"191/path---my-files-317-4c7-BZGobRtQMcPldTH5M4ac28mXPQ","news-we-care-wc落地上海人民广场景区-405":"731/path---news-we-care-wc落地上海人民广场景区-405-295-j7kJr3LQwt2MHHF1xYZpj0u2Pw0","news-wecare-wc移动卫生间解决方案-a67":"921/path---news-wecare-wc移动卫生间解决方案-a-67-8e9-6DK5gN8UGVQAabMBePFdlEg1AMQ","news-公共卫生间之女王-d06":"853/path---news-公共卫生间之女王-d-06-d91-eqIj7ezRtkiYB8Zowl9Tk6pwIEo","news-喜迎进博会-we-care-wc浦东国际机场项目完成-52f":"384/path---news-喜迎进博会-we-care-wc浦东国际机场项目完成-52-f-cc7-6crPAXiRbCO7yTZluKMCDTbxWc","page-2-fbc":"439/path---page-2-fbc-5a8-Gpjp0PvIfeRtzAXUjU5RFSRxRdY","sq--src-layouts-index-js":2825539598,"sq--src-pages-index-en-js":3920006604,"sq--src-pages-index-zh-js":1028222248}}}}]); //# sourceMappingURL=pages-manifest-29ff6a6dacb7266c71a8.js.map
module.exports = { verbose: true, roots: ['<rootDir>'], clearMocks: true, moduleFileExtensions: ['js', 'ts', 'tsx', 'json'], testPathIgnorePatterns: [ '[/\\\\](node_modules|.cache|.vscode|coverage)[/\\\\]', ], coveragePathIgnorePatterns: [ '[/\\\\](node_modules|.cache|.vscode|coverage|test|GlobalStyles|mocks)[/\\\\]', ], transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(ts|tsx)$'], transform: { '^.+\\.(ts|tsx)$': 'ts-jest', }, watchPlugins: [ 'jest-watch-typeahead/filename', 'jest-watch-typeahead/testname', ], moduleNameMapper: { '\\.(gif|woff|woff2|svg|png)$': '<rootDir>/test/__mocks__/fileMock.js', }, setupFilesAfterEnv: ['<rootDir>/test/__mocks__/windowMediaMock.js'], testEnvironment: 'jsdom', }
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Foo(models.Model): name = models.CharField(max_length=50) friend = models.CharField(max_length=50, blank=True) def __str__(self): return "Foo %s" % self.name @python_2_unicode_compatible class Bar(models.Model): name = models.CharField(max_length=50) normal = models.ForeignKey(Foo, related_name='normal_foo') fwd = models.ForeignKey("Whiz") back = models.ForeignKey("Foo") def __str__(self): return "Bar %s" % self.place.name @python_2_unicode_compatible class Whiz(models.Model): name = models.CharField(max_length=50) def __str__(self): return "Whiz %s" % self.name @python_2_unicode_compatible class Child(models.Model): parent = models.OneToOneField('Base') name = models.CharField(max_length=50) def __str__(self): return "Child %s" % self.name @python_2_unicode_compatible class Base(models.Model): name = models.CharField(max_length=50) def __str__(self): return "Base %s" % self.name @python_2_unicode_compatible class Article(models.Model): name = models.CharField(max_length=50) text = models.TextField() submitted_from = models.GenericIPAddressField(blank=True, null=True) def __str__(self): return "Article %s" % self.name
"""Base class for protect data.""" from __future__ import annotations from dataclasses import dataclass import logging from typing import Generator from homeassistant.core import callback from homeassistant.helpers.event import async_track_time_interval from pyunifiprotect.unifi_protect_server import NvrError _LOGGER = logging.getLogger(__name__) @dataclass class UnifiProtectDevice: device_id: str type: str data: dict class UnifiProtectData: """Coordinate updates.""" def __init__(self, hass, protectserver, update_interval): """Initialize an subscriber.""" super().__init__() self._hass = hass self._protectserver = protectserver self.data = {} self._update_interval = update_interval self._subscriptions = {} self._unsub_interval = None self._unsub_websocket = None self.last_update_success = False def get_by_types(self, device_types) -> Generator[UnifiProtectDevice, None, None]: """Get all devices matching types.""" if not self.data: return for device_id, device_data in self.data.items(): device_type = device_data.get("type") if device_type and device_type in device_types: yield UnifiProtectDevice(device_id, device_type, device_data) async def async_setup(self): """Subscribe and do the refresh.""" self._unsub_websocket = self._protectserver.subscribe_websocket( self._async_process_updates ) await self.async_refresh() async def async_stop(self, *args): """Stop processing data.""" if self._unsub_websocket: self._unsub_websocket() self._unsub_websocket = None if self._unsub_interval: self._unsub_interval() self._unsub_interval = None await self._protectserver.async_disconnect_ws() async def async_refresh(self, *_, force_camera_update=False): """Update the data.""" try: self._async_process_updates( await self._protectserver.update( force_camera_update=force_camera_update ) ) self.last_update_success = True except NvrError: if self.last_update_success: _LOGGER.exception("Error while updating") self.last_update_success = False @callback def _async_process_updates(self, updates): """Process update from the protect data.""" for device_id, data in updates.items(): self.data[device_id] = data self.async_signal_device_id_update(device_id) @callback def async_subscribe_device_id(self, device_id, update_callback): """Add an callback subscriber.""" if not self._subscriptions: self._unsub_interval = async_track_time_interval( self._hass, self.async_refresh, self._update_interval ) self._subscriptions.setdefault(device_id, []).append(update_callback) def _unsubscribe(): self.async_unsubscribe_device_id(device_id, update_callback) return _unsubscribe @callback def async_unsubscribe_device_id(self, device_id, update_callback): """Remove a callback subscriber.""" self._subscriptions[device_id].remove(update_callback) if not self._subscriptions[device_id]: del self._subscriptions[device_id] if not self._subscriptions: self._unsub_interval() self._unsub_interval = None @callback def async_signal_device_id_update(self, device_id): """Call the callbacks for a device_id.""" if not self._subscriptions.get(device_id): return for update_callback in self._subscriptions[device_id]: update_callback()
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = sidebar; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function sidebar(options) { var headersContainer = options.headersContainer, sidebarContainer = options.sidebarContainer, headerStartLevel = options.headerStartLevel; listenToChanges(options); var headers = headersContainer.querySelectorAll('h2, h3'); //const select = document.createElement('select'); var list = document.createElement('ul'); var startLevel = headerStartLevel; // we start at h2 list.classList.add('no-mobile'); var currentList = list; var currentLevel = startLevel; //select.addEventListener('change', e => window.location = e.target.value); sidebarContainer.appendChild(list); //sidebarContainer.appendChild(select); sidebarFollowScroll(sidebarContainer.firstChild); activeLinks(sidebarContainer); scrollSpy(sidebarContainer, headersContainer); } function listenToChanges(originalParameters) { var headersContainer = originalParameters.headersContainer, sidebarContainer = originalParameters.sidebarContainer, headerStartLevel = originalParameters.headerStartLevel; } function sidebarFollowScroll(sidebarContainer) { var _getPositionsKeyEleme = getPositionsKeyElements(sidebarContainer), height = _getPositionsKeyEleme.height, navHeight = _getPositionsKeyEleme.navHeight, footerHeight = _getPositionsKeyEleme.footerHeight, menuHeight = _getPositionsKeyEleme.menuHeight, sidebarTop = _getPositionsKeyEleme.sidebarTop; var positionSidebar = function positionSidebar() { var currentScroll = window.pageYOffset; if (currentScroll > sidebarTop - navHeight) { var fold = height - footerHeight - menuHeight - 50; if (currentScroll > fold) { sidebarContainer.style.top = fold - currentScroll + navHeight + 'px'; } else { sidebarContainer.style.top = null; } sidebarContainer.classList.add('fixed'); } else { sidebarContainer.classList.remove('fixed'); } }; window.addEventListener('load', positionSidebar); document.addEventListener('DOMContentLoaded', positionSidebar); document.addEventListener('scroll', positionSidebar); } function scrollSpy(sidebarContainer, headersContainer) { var headers = [].concat(_toConsumableArray(headersContainer.querySelectorAll('h2, h3'))); var setActiveSidebarLink = function setActiveSidebarLink(header) { [].concat(_toConsumableArray(sidebarContainer.querySelectorAll('a'))).forEach(function (item) { if (item.getAttribute('href').slice(1) === header.getAttribute('id')) { item.classList.add('active'); } else { item.classList.remove('active'); } }); }; var findActiveSidebarLink = function findActiveSidebarLink() { var highestVisibleHeaders = headers.map(function (header) { return { element: header, rect: header.getBoundingClientRect() }; }).filter(function (_ref) { var rect = _ref.rect; // top element relative viewport position should be at least 1/3 viewport // and element should be in viewport return rect.top < window.innerHeight / 3 && rect.bottom < window.innerHeight; }) // then we take the closest to this position as reference .sort(function (header1, header2) { return Math.abs(header1.rect.top) < Math.abs(header2.rect.top) ? -1 : 1; }); if (highestVisibleHeaders.length === 0) { setActiveSidebarLink(headers[0]); return; } setActiveSidebarLink(highestVisibleHeaders[0].element); }; findActiveSidebarLink(); window.addEventListener('load', findActiveSidebarLink); document.addEventListener('DOMContentLoaded', findActiveSidebarLink); document.addEventListener('scroll', findActiveSidebarLink); } // The Following code is used to set active items // On the documentation sidebar depending on the // clicked item function activeLinks(sidebarContainer) { var linksContainer = sidebarContainer.querySelector('ul'); linksContainer.addEventListener('click', function (e) { if (e.target.tagName === 'A') { [].concat(_toConsumableArray(linksContainer.querySelectorAll('a'))).forEach(function (item) { return item.classList.remove('active'); }); e.target.classList.add('active'); } }); } function getPositionsKeyElements(sidebar) { var sidebarBBox = sidebar.getBoundingClientRect(); var bodyBBox = document.body.getBoundingClientRect(); var sidebarTop = sidebarBBox.top - bodyBBox.top; var footer = document.querySelector('.ac-footer'); var navigation = document.querySelector('.ac-nav'); var menu = document.querySelector('.sidebar > ul'); var height = document.querySelector('html').getBoundingClientRect().height; var navHeight = navigation.offsetHeight; var footerHeight = footer.offsetHeight; var menuHeight = menu.offsetHeight; return { sidebarTop: sidebarTop, height: height, navHeight: navHeight, footerHeight: footerHeight, menuHeight: menuHeight }; }
import Delta from 'quill-delta'; import Quill from '../../core/quill'; import Module from '../../core/module'; import { TableCell, TableRow, TableBody, TableContainer, tableId, TableHeaderCell, TableHeaderRow, TableHeader, } from '../../formats/table/lite'; import { applyFormat } from '../clipboard'; import isDefined from '../../utils/is_defined'; import makeTableArrowHandler from './utils/make_table_arrow_handler'; import insertParagraphAbove from './utils/insert_pr_below'; import insertParagraphBelow from './utils/insert_pr_above'; import tableSide from './utils/table_side'; import prepareAttributeMatcher from './utils/prepare_attr_matcher'; import { TABLE_FORMATS } from '../../formats/table/attributors/table'; import { CELL_FORMATS } from '../../formats/table/attributors/cell'; const EMPTY_RESULT = [null, null, null, -1]; class TableLite extends Module { static register() { Quill.register(TableHeaderCell, true); Quill.register(TableCell, true); Quill.register(TableHeaderRow, true); Quill.register(TableRow, true); Quill.register(TableBody, true); Quill.register(TableHeader, true); Quill.register(TableContainer, true); [TABLE_FORMATS, CELL_FORMATS].forEach(formats => { Object.keys(formats).forEach(name => { Quill.register({ [`formats/${name}`]: formats[name] }, true); }); }); } constructor(...args) { super(...args); this.tableBlots = [TableCell.blotName, TableHeaderCell.blotName]; this.tableBlots.forEach(blotName => { this.quill.editor.addImmediateFormat(blotName); }); this.integrateClipboard(); this.addKeyboardHandlers(); this.listenBalanceCells(); } integrateClipboard() { this.tableBlots.forEach(blotName => this.quill.clipboard.addTableBlot(blotName), ); this.quill.clipboard.addMatcher('tr', matchTable); this.quill.clipboard.addMatcher('table', prepareAttributeMatcher('table')); this.quill.clipboard.addMatcher('td, th', prepareAttributeMatcher('cell')); } addKeyboardHandlers() { const bindings = TableLite.keyboardBindings; Object.keys(bindings).forEach(name => { if (bindings[name]) { this.quill.keyboard.addBinding(bindings[name]); } }); } balanceTables() { this.quill.scroll.descendants(TableContainer).forEach(table => { table.balanceCells(); }); } deleteColumn() { const [table, , cell] = this.getTable(); if (!isDefined(cell)) { return; } table.deleteColumn(cell.cellOffset()); this.quill.update(Quill.sources.USER); } deleteRow() { const [, row] = this.getTable(); if (!isDefined(row)) { return; } row.remove(); this.quill.update(Quill.sources.USER); } deleteTable() { const [table] = this.getTable(); if (!isDefined(table)) { return; } const offset = table.offset(); table.remove(); this.quill.update(Quill.sources.USER); this.quill.setSelection(offset, Quill.sources.SILENT); } getTable(range = this.quill.getSelection()) { if (!isDefined(range)) { return EMPTY_RESULT; } const [cell, offset] = this.quill.getLine(range.index); if ( !isDefined(cell) || this.tableBlots.indexOf(cell.statics.blotName) === -1 ) { return EMPTY_RESULT; } const row = cell.parent; const table = row.parent.parent; return [table, row, cell, offset]; } insertColumn(offset) { const range = this.quill.getSelection(); const [table, row, cell] = this.getTable(range); if (!isDefined(cell)) { return; } const column = cell.cellOffset(); table.insertColumn(column + offset); this.quill.update(Quill.sources.USER); let shift = row.rowOffset(); if (offset === 0) { shift += 1; } this.quill.setSelection( range.index + shift, range.length, Quill.sources.SILENT, ); } insertColumnLeft() { this.insertColumn(0); } insertColumnRight() { this.insertColumn(1); } insertRow(offset) { const range = this.quill.getSelection(); const [table, row, cell] = this.getTable(range); if (!isDefined(cell)) { return; } const index = row.rowOffset(); table.insertRow(index + offset); this.quill.update(Quill.sources.USER); if (offset > 0) { this.quill.setSelection(range, Quill.sources.SILENT); } else { this.quill.setSelection( range.index + row.children.length, range.length, Quill.sources.SILENT, ); } } insertRowAbove() { this.insertRow(0); } insertRowBelow() { this.insertRow(1); } insertHeaderRow() { const range = this.quill.getSelection(); const [table, , cell] = this.getTable(range); if (!isDefined(cell)) { return; } table.insertHeaderRow(); this.quill.update(Quill.sources.USER); } insertTable(rows, columns) { const range = this.quill.getSelection(); if (!isDefined(range)) { return; } const delta = new Array(rows).fill(0).reduce(memo => { const text = new Array(columns).fill('\n').join(''); return memo.insert(text, { table: tableId() }); }, new Delta().retain(range.index)); this.quill.updateContents(delta, Quill.sources.USER); this.quill.setSelection(range.index, Quill.sources.SILENT); this.balanceTables(); } tableFormats() { return this.tableBlots; } listenBalanceCells() { this.quill.on(Quill.events.SCROLL_OPTIMIZE, mutations => { mutations.some(mutation => { if ( ['TD', 'TH', 'TR', 'TBODY', 'THEAD', 'TABLE'].indexOf( mutation.target.tagName, ) !== -1 ) { this.quill.once(Quill.events.TEXT_CHANGE, (delta, old, source) => { if (source !== Quill.sources.USER) return; this.balanceTables(); }); return true; } return false; }); }); this.quill.on(Quill.events.CONTENT_SETTED, () => { this.quill.once(Quill.events.TEXT_CHANGE, () => { this.balanceTables(); }); }); } } TableLite.keyboardBindings = { 'table backspace': { key: 'backspace', format: ['table', 'tableHeaderCell'], collapsed: true, offset: 0, handler() {}, }, 'table delete': { key: 'del', format: ['table', 'tableHeaderCell'], collapsed: true, suffix: /^$/, handler() {}, }, 'table enter': { key: 'enter', shiftKey: null, format: ['table'], handler(range) { const module = this.quill.getModule('table'); if (module) { const { quill } = this; const [table, row, cell, offset] = module.getTable(range); const shift = tableSide(row, cell, offset); const hasHead = table.children.length > 1 && table.children.head; if (shift == null || (shift < 0 && hasHead)) { return; } const index = table.offset(); if (shift < 0) { insertParagraphAbove({ quill, index, range }); } else { insertParagraphBelow({ quill, index, table }); } } }, }, 'table header enter': { key: 'enter', shiftKey: null, format: ['tableHeaderCell'], handler(range) { const module = this.quill.getModule('table'); if (module) { const { quill } = this; const [table, row, cell, offset] = module.getTable(range); const shift = tableSide(row, cell, offset); if (shift == null) { return; } const index = table.offset(); const hasBody = table.children.length > 1 && table.children.tail; if (shift < 0 || (shift > 0 && hasBody)) { insertParagraphAbove({ quill, index, range }); } else { insertParagraphBelow({ quill, index, table }); } } }, }, 'table tab': { key: 'tab', shiftKey: null, format: ['table', 'tableHeaderCell'], handler(range, context) { const { event, line: cell } = context; const offset = cell.offset(this.quill.scroll); if (event.shiftKey) { this.quill.setSelection(offset - 1, Quill.sources.USER); } else { this.quill.setSelection(offset + cell.length(), Quill.sources.USER); } }, }, 'table down': makeTableArrowHandler(false, ['table', 'tableHeaderCell']), 'table up': makeTableArrowHandler(true, ['table', 'tableHeaderCell']), }; function matchTable(node, delta) { const table = node.parentNode.tagName === 'TABLE' ? node.parentNode : node.parentNode.parentNode; const isHeaderRow = node.parentNode.tagName === 'THEAD' ? true : null; const rows = Array.from(table.querySelectorAll('tr')); const row = rows.indexOf(node) + 1; return applyFormat(delta, isHeaderRow ? 'tableHeaderCell' : 'table', row); } export default TableLite;
class AbstractSubscribableStoreQuery { changeParams() { throw new Error('Method not supported. Please create a new query.'); } changePartialParams() { throw new Error('Method not supported. Please create a new query.'); } setSubscribeStore(store) { this._subscribeStore = store; } getSubscribeStore() { if (!this._subscribeStore) { throw new Error('_subscribeStore is not initialized'); } return this._subscribeStore; } fetchAndSubscribe(callback) { return this._subscribe(callback, true); } subscribe(callback) { return this._subscribe(callback, false); } } /* eslint-disable max-lines */ class SubscribeStore { constructor(store) { this.listeners = new Set(); this.store = store; this.keyPath = store.keyPath; } get connection() { return this.store.connection; } subscribe(callback) { this.listeners.add(callback); return () => this.listeners.delete(callback); } callSubscribed(action) { this.listeners.forEach(listener => listener(action)); } createQuerySingleItem(options, transformer) { const query = this.store.createQuerySingleItem(options, transformer); query.setSubscribeStore(this); return query; } createQueryCollection(options, transformer) { const query = this.store.createQueryCollection(options, transformer); query.setSubscribeStore(this); return query; } findAll(criteria, sort) { return this.store.findAll(criteria, sort); } findByKey(key, criteria) { return this.store.findByKey(key, criteria); } findOne(criteria, sort) { return this.store.findOne(criteria, sort); } async insertOne(object) { const inserted = await this.store.insertOne(object); this.callSubscribed({ type: 'inserted', next: [inserted] }); return inserted; } async replaceOne(object) { const replaced = await this.store.replaceOne(object); this.callSubscribed({ type: 'updated', changes: [[object, replaced]] }); return replaced; } async replaceSeveral(objects) { const replacedObjects = await this.store.replaceSeveral(objects); this.callSubscribed({ type: 'updated', changes: objects.map((prev, index) => [prev, replacedObjects[index]]) }); return replacedObjects; } async upsertOne(object, setOnInsertPartialObject) { const result = await this.upsertOneWithInfo(object, setOnInsertPartialObject); return result.object; } async upsertOneWithInfo(object, setOnInsertPartialObject) { const upsertedWithInfo = await this.store.upsertOneWithInfo(object, setOnInsertPartialObject); if (upsertedWithInfo.inserted) { this.callSubscribed({ type: 'inserted', next: [upsertedWithInfo.object] }); } else { throw new Error('TODO'); } return upsertedWithInfo; } async partialUpdateByKey(key, partialUpdate, criteria) { return this.partialUpdateOne(await this.findOne({ [this.store.keyPath]: key, ...criteria }), partialUpdate); } async partialUpdateOne(object, partialUpdate) { const updated = await this.store.partialUpdateOne(object, partialUpdate); this.callSubscribed({ type: 'updated', changes: [[object, updated]] }); return updated; } async partialUpdateMany(criteria, partialUpdate) { const cursor = await this.store.cursor(criteria); const changes = []; await cursor.forEach(async model => { const key = model[this.store.keyPath]; const updated = await this.store.partialUpdateByKey(key, partialUpdate, criteria); changes.push([model, updated]); }); this.callSubscribed({ type: 'updated', changes }); } async deleteByKey(key, criteria) { return this.deleteOne(await this.findByKey(key, criteria)); } async deleteOne(object) { await this.store.deleteOne(object); this.callSubscribed({ type: 'deleted', prev: [object] }); } async deleteMany(criteria) { const cursor = await this.store.cursor(criteria); const prev = await cursor.toArray(); await this.store.deleteMany(criteria); this.callSubscribed({ type: 'deleted', prev }); } async cursor(criteria, sort) { const cursor = await this.store.cursor(criteria, sort); cursor.overrideStore(this); return cursor; } } export { AbstractSubscribableStoreQuery, SubscribeStore }; //# sourceMappingURL=index-browsermodern-dev.es.js.map
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Wrappers for the json returned by the ThreatExchange API to typed objects. """ import collections import typing as t from . import TE class ThreatDescriptor(t.NamedTuple): """ Wrapper around ThreatExchange JSON for a ThreatDescriptor. Example: { "id": "3058061737574159" "raw_indicator": "facefacefacefacefacefacefaceface", "type": "HASH_MD5", "owner": { "id": "616912251743987", ..., }, "status": "MALICIOUS", "tags": null, "added_on": "2020-07-01T18:31:15+0000" ... } """ # You declared the indicator was in the collaboration label set TRUE_POSITIVE = "true_positive" # You declared the indicator was not in the collaboration label set FALSE_POSITIVE = "false_positive" # Someone declared the indicator was not in the collaboration label set DISPUTED = "disputed" # Special tags to mark whether you (or someone else) # has weighed in on the indicator SPECIAL_TAGS = frozenset((TRUE_POSITIVE, FALSE_POSITIVE, DISPUTED)) id: int raw_indicator: str indicator_type: str owner_id: int tags: t.List[str] status: str added_on: str def to_params(self) -> t.Dict[str, t.Any]: params = dict(self.__dict__) params["type"] = params.pop("indicator_type") if not params["tags"]: del params["tags"] return params @property def is_true_positive(self) -> bool: return self.TRUE_POSITIVE in self.tags @property def is_false_positive(self) -> bool: return self.FALSE_POSITIVE in self.tags @property def is_mine(self) -> bool: """This Descriptor is my App's Opinion""" # TODO - come up with a way to do this that doesn't use class state return TE.Net.APP_TOKEN.partition("|")[0] == str(self.owner_id) class SimpleDescriptorRollup: """ A simple way to merge opinions on the same indicator. This contains all the information needed for simple SignalType state. """ IS_MY_OPINION = "mine" __slots__ = ["first_descriptor_id", "added_on", "labels"] def __init__( self, first_descriptor_id: int, added_on: str, labels: t.Set[str] ) -> None: self.first_descriptor_id = first_descriptor_id self.added_on = added_on # TODO - convert to int? self.labels = set(labels) @classmethod def from_descriptor(cls, descriptor: ThreatDescriptor) -> "SimpleDescriptorRollup": return cls(descriptor.id, descriptor.added_on, descriptor.tags) def merge(self, descriptor: ThreatDescriptor) -> None: # Is the other descriptor mine? If so, unconditionally take it and clear # everything else if descriptor.is_mine: self.added_on = self.IS_MY_OPINION self.first_descriptor_id = descriptor.id self.labels = descriptor.tags return # My descriptor beats my reactions, and I don't want # to take anyone else's opinion elif self.added_on == self.IS_MY_OPINION: return # Is my reaction? elif descriptor.is_false_positive: self.added_on = self.IS_MY_OPINION self.first_descriptor_id = descriptor.id self.labels = descriptor.tags return # Else merge the labels together self.added_on, self.first_descriptor_id = min( (self.added_on, self.first_descriptor_id), (descriptor.added_on, descriptor.id), ) self.labels.union(descriptor.tags) def as_row(self) -> t.Tuple[int, str, str]: """Simple conversion to CSV row""" return self.first_descriptor_id, self.added_on, " ".join(self.labels) @classmethod def from_row(cls, row: t.Iterable) -> "SimpleDescriptorRollup": """Simple conversion from CSV row""" labels = [] if row[2]: labels = row[2].split(" ") return cls(int(row[0]), row[1], labels)
// this is an optional global configuration option for your <%= name.raw %> generator module.exports = { }
import React from 'react'; let defaultOptions = { bindI18n: 'languageChanged', bindI18nStore: '', transEmptyNodeValue: '', transSupportBasicHtmlNodes: true, transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'], useSuspense: true, }; let i18nInstance; let hasUsedI18nextProvider; export const I18nContext = React.createContext(); export function usedI18nextProvider(used) { hasUsedI18nextProvider = used; } export function getHasUsedI18nextProvider() { return hasUsedI18nextProvider; } export function setDefaults(options = {}) { defaultOptions = { ...defaultOptions, ...options }; } export function getDefaults() { return defaultOptions; } export class ReportNamespaces { constructor() { this.usedNamespaces = {}; } addUsedNamespaces(namespaces) { namespaces.forEach(ns => { if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true; }); } getUsedNamespaces() { return Object.keys(this.usedNamespaces); } } export function setI18n(instance) { i18nInstance = instance; } export function getI18n() { return i18nInstance; } export const initReactI18next = { type: '3rdParty', init(instance) { setDefaults(instance.options.react); setI18n(instance); }, }; export function composeInitialProps(ForComponent) { return ctx => new Promise(resolve => { const i18nInitialProps = getInitialProps(); if (ForComponent.getInitialProps) { ForComponent.getInitialProps(ctx).then(componentsInitialProps => { resolve({ ...componentsInitialProps, ...i18nInitialProps, }); }); } else { resolve(i18nInitialProps); } }); // Avoid async for now - so we do not need to pull in regenerator // return async ctx => { // const componentsInitialProps = ForComponent.getInitialProps // ? await ForComponent.getInitialProps(ctx) // : {}; // const i18nInitialProps = getInitialProps(); // return { // ...componentsInitialProps, // ...i18nInitialProps, // }; // }; } export function getInitialProps() { const i18n = getI18n(); const namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : []; const ret = {}; const initialI18nStore = {}; i18n.languages.forEach(l => { initialI18nStore[l] = {}; namespaces.forEach(ns => { initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {}; }); }); ret.initialI18nStore = initialI18nStore; ret.initialLanguage = i18n.language; return ret; }
############################################################################## # # Copyright (c) 2007 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTLAR PURPOSE. # ############################################################################## """Testing all XML Locale functionality. """ import os import unittest import z3c.rml.tests from z3c.rml import rml2pdfscript from z3c.rml.tests.test_rml import ComparePDFTestCase from z3c.rml.tests.test_rml import RMLRenderingTestCase class RMLRenderingTestCase(RMLRenderingTestCase): def runTest(self): rml2pdfscript.goSubProcess(self._inPath, self._outPath, True) def test_suite(): suite = unittest.TestSuite() if False: inputDir = os.path.join(os.path.dirname(z3c.rml.tests.__file__), 'input') outputDir = os.path.join(os.path.dirname(z3c.rml.tests.__file__), 'output') expectDir = os.path.join(os.path.dirname(z3c.rml.tests.__file__), 'expected') for filename in os.listdir(inputDir): if not filename.endswith(".rml"): continue inPath = os.path.join(inputDir, filename) outPath = os.path.join(outputDir, filename[:-4] + '.pdf') expectPath = os.path.join(expectDir, filename[:-4] + '.pdf') # ** Test RML to PDF rendering ** # Create new type, so that we can get test matching TestCase = type(filename[:-4], (RMLRenderingTestCase,), {}) case = TestCase(inPath, outPath) suite.addTest(case) # ** Test PDF rendering correctness ** TestCase = type('compare-'+filename[:-4], (ComparePDFTestCase,), {}) case = TestCase(expectPath, outPath) suite.addTest(case) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
(()=>{"use strict";var e,t,n,a,i={315:(e,t,n)=>{n.d(t,{Z:()=>r});var a=n(645),i=n.n(a)()((function(e){return e[1]}));i.push([e.id,"input:checked~.dot{transform:translateX(100%);background-color:#00ff6a}",""]);const r=i},645:e=>{e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=e(t);return t[2]?"@media ".concat(t[2]," {").concat(n,"}"):n})).join("")},t.i=function(e,n,a){"string"==typeof e&&(e=[[null,e,""]]);var i={};if(a)for(var r=0;r<this.length;r++){var o=this[r][0];null!=o&&(i[o]=!0)}for(var s=0;s<e.length;s++){var l=[].concat(e[s]);a&&i[l[0]]||(n&&(l[2]?l[2]="".concat(n," and ").concat(l[2]):l[2]=n),t.push(l))}},t}},379:(e,t,n)=>{var a,i=function(){var e={};return function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}e[t]=n}return e[t]}}(),r=[];function o(e){for(var t=-1,n=0;n<r.length;n++)if(r[n].identifier===e){t=n;break}return t}function s(e,t){for(var n={},a=[],i=0;i<e.length;i++){var s=e[i],l=t.base?s[0]+t.base:s[0],d=n[l]||0,c="".concat(l," ").concat(d);n[l]=d+1;var u=o(c),f={css:s[1],media:s[2],sourceMap:s[3]};-1!==u?(r[u].references++,r[u].updater(f)):r.push({identifier:c,updater:h(f,t),references:1}),a.push(c)}return a}function l(e){var t=document.createElement("style"),a=e.attributes||{};if(void 0===a.nonce){var r=n.nc;r&&(a.nonce=r)}if(Object.keys(a).forEach((function(e){t.setAttribute(e,a[e])})),"function"==typeof e.insert)e.insert(t);else{var o=i(e.insert||"head");if(!o)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");o.appendChild(t)}return t}var d,c=(d=[],function(e,t){return d[e]=t,d.filter(Boolean).join("\n")});function u(e,t,n,a){var i=n?"":a.media?"@media ".concat(a.media," {").concat(a.css,"}"):a.css;if(e.styleSheet)e.styleSheet.cssText=c(t,i);else{var r=document.createTextNode(i),o=e.childNodes;o[t]&&e.removeChild(o[t]),o.length?e.insertBefore(r,o[t]):e.appendChild(r)}}function f(e,t,n){var a=n.css,i=n.media,r=n.sourceMap;if(i?e.setAttribute("media",i):e.removeAttribute("media"),r&&"undefined"!=typeof btoa&&(a+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),e.styleSheet)e.styleSheet.cssText=a;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(a))}}var p=null,m=0;function h(e,t){var n,a,i;if(t.singleton){var r=m++;n=p||(p=l(t)),a=u.bind(null,n,r,!1),i=u.bind(null,n,r,!0)}else n=l(t),a=f.bind(null,n,t),i=function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(n)};return a(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;a(e=t)}else i()}}e.exports=function(e,t){(t=t||{}).singleton||"boolean"==typeof t.singleton||(t.singleton=(void 0===a&&(a=Boolean(window&&document&&document.all&&!window.atob)),a));var n=s(e=e||[],t);return function(e){if(e=e||[],"[object Array]"===Object.prototype.toString.call(e)){for(var a=0;a<n.length;a++){var i=o(n[a]);r[i].references--}for(var l=s(e,t),d=0;d<n.length;d++){var c=o(n[d]);0===r[c].references&&(r[c].updater(),r.splice(c,1))}n=l}}}}},r={};function o(e){var t=r[e];if(void 0!==t)return t.exports;var n=r[e]={id:e,exports:{}};return i[e](n,n.exports,o),n.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{const e=(e,t,n,a)=>{const i=document.createElement(e);return i.innerText=n,Object.keys(t).forEach((e=>i.setAttribute(e,t[e]))),i&&document.getElementById(a).appendChild(i),i},t=()=>{const t=document.getElementById("status");!t||t.remove(),window.weather&&(e("div",{class:"my-4 flex w-full",id:"status"},"","body-content"),e("div",{class:"fp-2 w-full",id:"status-div"},"","status"),e("div",{class:"h-full flex flex-col p-4 rounded-lg bg-blue-50",id:"weather-details"},"","status-div"),e("div",{class:"flex my-2",id:"weather-icon"},"","weather-details"),e("img",{alt:"icon",class:"w-16 h-16 bg-blue-200 object-cover object-center flex-shrink-0 rounded-full mr-4",src:window.icon},"","weather-icon"),e("h1",{class:"my-3 text-gray-900 title-font text-3xl font-bold"},window.weather.description,"weather-icon"),e("div",{class:"grid grid-flow-col p-2 justify-baseline justify-items-stretch",id:"country-details"},"","weather-details"),e("span",{class:"text-gray-500"},`Country: ${window.weather.country}`,"country-details"),e("span",{class:"text-gray-500"},`Feels like: ${window.weather.feels_like}`,"country-details"),e("div",{class:"grid grid-flow-col p-2 justify-baseline justify-items-stretch",id:"temp-details"},"","weather-details"),e("span",{class:"text-gray-500"},`Temp: ${window.weather.temp}`,"temp-details"),e("span",{class:"text-gray-500"},`Min: ${window.weather.temp_min}`,"temp-details"),e("span",{class:"text-gray-500"},`Max: ${window.weather.temp_max}`,"temp-details"),e("div",{class:"grid grid-flow-col p-2 justify-baseline justify-items-stretch",id:"stat-details"},"","weather-details"),e("span",{class:"text-gray-500"},`Clouds: ${window.weather.clouds}`,"stat-details"),e("span",{class:"text-gray-500"},`Humidity: ${window.weather.humidity}`,"stat-details"),e("span",{class:"text-gray-500"},`Pressure: ${window.weather.pressure}`,"stat-details"),e("div",{class:"grid grid-flow-col p-2 justify-baseline justify-items-stretch",id:"wind-details"},"","weather-details"),e("span",{class:"text-gray-500"},"Winds ","wind-details"),e("span",{class:"text-gray-500"},`Deg: ${window.weather.deg}`,"wind-details"),e("span",{class:"text-gray-500"},`Speed: ${window.weather.speed}`,"wind-details"))},n=n=>{try{n.preventDefault();const a=(e,t,n,a,i,r,o,s,l,d,c,u,f)=>({icon:e,country:t,main:n,description:a,feels_like:i,humidity:r,pressure:o,temp:s,temp_max:l,temp_min:d,clouds:c,deg:u,speed:f}),i=(e,t,n="16b763577392ee505e23d81e111408f0")=>({city:e,units:t,apikey:n}),r=document.getElementById("toggle-status").checked?"imperial":"metric",o=i(document.getElementById("location-name").value,r),s=`https://api.openweathermap.org/data/2.5/weather?q=${o.city}&units=${o.units}&appid=${o.apikey}`;return fetch(s).then((e=>e.json())).then((n=>{if(n.message){const t=document.getElementById("error");!t||t.remove(),e("span",{class:"text-red-700 transition-colors duration-200 ease-in-out",id:"error"},`${n.message}`,"loaction-form")}else{const e=document.getElementById("error");!e||e.remove(),window.weather=a(n.weather[0].icon,n.sys.country,n.weather[0].main,n.weather[0].description,n.main.feels_like,n.main.humidity,n.main.pressure,n.main.temp,n.main.temp_max,n.main.temp_min,n.clouds.all,n.wind.deg,n.wind.speed),window.icon=`http://openweathermap.org/img/wn/${window.weather.icon}@2x.png`,t()}})),{units:r}}catch(n){}};e("header",{class:"text-gray-600 body-font my-3",id:"header"},"","content"),e("div",{class:"container mx-auto flex flex-wrap p-5 flex-col md:flex-row justify-center",id:"headercontainer"},"","header"),e("a",{class:"title-font cursor-pointer font-medium items-center text-gray-900 text-3xl",href:"#"},"Weather App","headercontainer"),e("section",{class:"text-gray-600 body-font overflow-hidden",id:"body-section"},"","content"),e("div",{class:"container px-5 py-24 mx-auto",id:"body-container"},"","body-section"),e("div",{class:"flex flex-wrap -m-4 justify-center ",id:"body-flex-container"},"","body-container"),e("div",{class:"p-4 xl:w-1/2 md:w-1/2 w-full",id:"body-flex-sub-container"},"","body-flex-container"),e("div",{class:"h-full p-6 px-11 rounded-lg border-2 border-gray-300 flex flex-col relative overflow-hidden items-center",id:"body-content"},"","body-flex-sub-container"),e("label",{class:"flex items-center cursor-pointer my-4",for:"toggle-status",id:"toggle-button-label"},"","body-content"),e("span",{class:""},"Celsius","toggle-button-label"),e("div",{class:"relative mx-3",id:"toggle-button-container"},"","toggle-button-label"),e("input",{class:"sr-only",type:"checkbox",id:"toggle-status"},"","toggle-button-container").addEventListener("change",n),e("div",{class:"w-10 h-4 bg-gray-400 rounded-full shadow-inner"},"","toggle-button-container"),e("div",{class:"dot absolute w-6 h-6 bg-white rounded-full shadow -left-1 -top-1 transition"},"","toggle-button-container"),e("span",{class:""},"Fahrenheit","toggle-button-label"),e("form",{class:"relative w-full mb-4",id:"loaction-form"},"","body-content").addEventListener("submit",n),e("input",{class:"w-full bg-gray-100 rounded border bg-opacity-50 border-gray-300 focus:ring-2 focus:ring-indigo-200 focus:bg-transparent focus:border-indigo-500 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out",type:"text",id:"location-name",name:"name",placeholder:"Name",required:""},"","loaction-form"),n(),t()})(),e=o(379),t=o.n(e),n=o(315),a={insert:"head",singleton:!1},t()(n.Z,a),n.Z.locals})();
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt import numpy as np #Check if GPU loaded a= tf.test.gpu_device_name() print(a) #Hyper-parameters batchSize = 80 #128 epochs = 500 #1000 margin = 0.1 #0.1 learningRate = 0.001 #0.001 displaySteps = 100 #100 dropout = 0.3 # Dropout, probability to keep units class TripletNet: def __init__(self): self.x1 = tf.placeholder(tf.float32, [None, 784]) self.x2 = tf.placeholder(tf.float32, [None, 784]) self.x3 = tf.placeholder(tf.float32, [None, 784]) self.y_ = tf.placeholder(tf.float32, [None,2],) with tf.variable_scope("triplet") as scope: self.output1 = self.network(tf.reshape(self.x1,[batchSize,28,28,1])) scope.reuse_variables() self.output2 = self.network(tf.reshape(self.x2,[batchSize,28,28,1])) scope.reuse_variables() self.output3 = self.network(tf.reshape(self.x3,[batchSize,28,28,1])) scope.reuse_variables() self.classOutput = self.classification(self.output3) self.classLoss = self.ClassLoss() self.loss = self.TripletLoss() self.Accuracy = self.GetAccuracy() #self.eva = self.Evaluate() def network(self, input, reuse = tf.AUTO_REUSE) : if (reuse): tf.get_variable_scope().reuse_variables() with tf.name_scope("network") : with tf.variable_scope("conv1") as scope: net = tf.contrib.layers.conv2d(input, 32, [7, 7],biases_initializer=tf.zeros_initializer(), activation_fn=tf.nn.relu, padding='SAME', weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),scope=scope,reuse=reuse) net = tf.contrib.layers.max_pool2d(net, [2, 2], padding='SAME') net = tf.contrib.layers.batch_norm(net, center=True, scale=True, is_training=True, scope='conv1', reuse= reuse) with tf.variable_scope("conv2") as scope: net = tf.contrib.layers.conv2d(net, 64, [5, 5], activation_fn=tf.nn.relu, padding='SAME', weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),scope=scope,reuse=reuse) net = tf.contrib.layers.max_pool2d(net, [2, 2], padding='SAME') net = tf.contrib.layers.batch_norm(net, center=True, scale=True, is_training=True, scope='conv2', reuse= reuse) with tf.variable_scope("conv3") as scope: net = tf.contrib.layers.conv2d(net, 128, [3, 3], activation_fn=tf.nn.relu, padding='SAME', weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),scope=scope,reuse=reuse) net = tf.contrib.layers.max_pool2d(net, [2, 2], padding='SAME') net = tf.contrib.layers.batch_norm(net, center=True, scale=True, is_training=True, scope='conv3', reuse= reuse) with tf.variable_scope("conv4") as scope: net = tf.contrib.layers.conv2d(net, 256, [1, 1], activation_fn=tf.nn.relu, padding='SAME', weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),scope=scope,reuse=reuse) net = tf.contrib.layers.max_pool2d(net, [2, 2], padding='SAME') net = tf.contrib.layers.batch_norm(net, center=True, scale=True, is_training=True, scope='conv4', reuse= reuse) with tf.variable_scope("conv5") as scope: net = tf.contrib.layers.conv2d(net, 2, [1, 1], activation_fn=None, padding='SAME', weights_initializer=tf.contrib.layers.xavier_initializer_conv2d(),scope=scope,reuse=reuse) net = tf.contrib.layers.max_pool2d(net, [2, 2], padding='SAME') net = tf.contrib.layers.batch_norm(net, center=True, scale=True, is_training=True, scope='conv5', reuse= reuse) net = tf.contrib.layers.flatten(net) #embedding return net def classification(self, input, reuse = tf.AUTO_REUSE) : if (reuse): tf.get_variable_scope().reuse_variables() #test net = input ''' with tf.name_scope("classification") : with tf.variable_scope("FullyConnected1") as scope: net = tf.contrib.layers.fully_connected(input,2,reuse=reuse,activation_fn=tf.nn.relu, biases_initializer=tf.zeros_initializer(), scope = 'FullyConnected1') weights_initializer = tf.contrib.layers.xavier_initializer(uniform=True, seed=None, dtype=tf.float32) with tf.variable_scope("FullyConnected2") as scope: net = tf.contrib.layers.fully_connected(net,2,reuse=reuse,activation_fn=tf.nn.relu , biases_initializer=tf.zeros_initializer(), scope = 'FullyConnected2') weights_initializer = tf.contrib.layers.xavier_initializer(uniform=True, seed=None, dtype=tf.float32) with tf.variable_scope("FullyConnected3") as scope: net = tf.contrib.layers.fully_connected(net,2,reuse=reuse,activation_fn=tf.nn.relu, biases_initializer=tf.zeros_initializer(), scope = 'FullyConnected3') weights_initializer = tf.contrib.layers.xavier_initializer(uniform=True, seed=None, dtype=tf.float32) with tf.variable_scope("Dropout") as scope: net = tf.contrib.layers.dropout(net, keep_prob=dropout, noise_shape=None, is_training=True, outputs_collections=None, scope=None, seed=None) ''' return net def GetAccuracy(self) : anchor_feature = self.output3 positive_feature = self.output2 negative_feature = self.output1 pos_dis = tf.reduce_mean(tf.square(tf.subtract(anchor_feature, positive_feature)),1, keepdims=True) neg_dis = tf.reduce_mean(tf.square(tf.subtract(anchor_feature, negative_feature)),1, keepdims=True) correct = tf.less_equal(pos_dis +margin, neg_dis) acc = tf.reduce_sum(tf.cast(correct, tf.float32))/batchSize return acc def TripletLoss(self) : # could replace by improved triplet loss with ratio for pos and neg. or hybrid loss function anchor_feature = self.output3 positive_feature = self.output2 negative_feature = self.output1 with tf.name_scope("triplet_loss"): pos_dis = tf.reduce_mean(tf.square(tf.subtract(anchor_feature, positive_feature)),1, keepdims=True) neg_dis = tf.reduce_mean(tf.square(tf.subtract(anchor_feature, negative_feature)),1, keepdims=True) res = tf.maximum(0., pos_dis + margin - neg_dis) loss = tf.reduce_mean(res) return loss def ClassLoss(self) : loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.classOutput, labels = self.y_)) return loss #Get image of the opposite parity def GetOpositeParityImage(mnist, par) : parity = par ran = -1 while(parity == par) : ran = np.random.randint(0,mnist.train.labels.shape[0], 1) label = mnist.train.labels[ran] parity = (label % 2 == 0) return ran # Create random Triplet and assign binary Label def GetTriplet(mnist) : ran = np.random.randint(0,mnist.train.labels.shape[0], 1) lab = mnist.train.labels[ran] par = [(lab % 2 == 0)] return np.array([ran, GetOpositeParityImage(mnist, par), GetOpositeParityImage(mnist, par), par]) #return [negative, positive, anchor, binary label] par = 0 even, odd, odd par = 1 odd, even, even #Creates batch of shape (128,4) where as 128 is batch size and 4 stands for a triplet plus binary label def CreateTripletBatch(mnist) : Triplet_Set = [] for i in range(batchSize) : Triplet_Set.append(GetTriplet(mnist)) return np.array(Triplet_Set) def CreateTestBatch(mnist) : Test_Set = [] for i in range(batchSize) : ran = np.random.randint(0,mnist.test.labels.shape[0], 1) lab = mnist.test.labels[ran] par = (lab % 2 == 0) Test_Set.append(np.array([ran, par])) return np.array(Test_Set) #Fetch image data from index def FetchImages(mnist, indexes, training) : imgList = [] for i in indexes : if(training) : imgList.append(mnist.train.images[i]) else: imgList.append(mnist.test.images[i]) res = np.asarray(imgList) return np.reshape(res, (batchSize,784)) #Main mnist = input_data.read_data_sets('MNIST_data', one_hot=False) g = tf.Graph() #reset graph sess = tf.InteractiveSession(graph=g) model = TripletNet(); optimizer = tf.train.AdamOptimizer(learning_rate = learningRate).minimize(model.loss) classifier = tf.train.AdamOptimizer(learning_rate = learningRate).minimize(model.classLoss) tf.initialize_all_variables().run() lossList = [] accList = [] for step in range(epochs): TripletBatch = CreateTripletBatch(mnist) batch_x1 = FetchImages(mnist, TripletBatch[:,0], True) batch_x2 = FetchImages(mnist, TripletBatch[:,1], True) batch_x3 = FetchImages(mnist, TripletBatch[:,2], True) batch_y = np.reshape(TripletBatch[:,3], (batchSize,)) y_list = [] for i in batch_y : if(batch_y[i]==0) : y_list.append(np.array([1.,0.])) else : y_list.append(np.array([0.,1.])) _, loss_v, loss_c, Accuracy, clas = sess.run([optimizer, model.loss, model.classLoss ,model.Accuracy, model.classOutput], feed_dict={ model.x1: batch_x1, model.x2: batch_x2, model.x3: batch_x3, model.y_: y_list, }) lossList.append(loss_v) accList.append(Accuracy) if step % displaySteps == 0: print ('step %3d: loss: %.6f class-loss: %.6f triplet-accuracy: %.3f ' % (step, loss_v, loss_c, Accuracy)) if step== epochs-1 : for i in range(80) : if(batch_y[i]==1) : plt.plot(clas[i,0], clas[i,1], "o", c = 'green') else : plt.plot(clas[i,0], clas[i,1], "o", c = 'red') plt.title('Embeddings') plt.ylabel('y') plt.xlabel('x') plt.show() # plot Loss Graph plt.plot(lossList) plt.title('Loss') plt.ylabel('loss') plt.xlabel('epoch') plt.show() # plot Loss Graph plt.plot(accList) plt.title('Training Accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.show() #Calculating test accuracy count = 0 for step in range(epochs): DualBatch = CreateTestBatch(mnist) batch_x3 = FetchImages(mnist, DualBatch[:,0], False) batch_y = np.reshape(DualBatch[:,1], (batchSize,)) y_list = [] for i in range(batchSize): if(batch_y[i]==0) : y_list.append(np.array([1.,0.])) else : y_list.append(np.array([0.,1.])) batchAcc = sess.run([model.classOutput], feed_dict={model.x3: batch_x3, model.y_: y_list}) for i in range(batchSize): if(np.argmax(batchAcc[0][i]) == np.argmax(y_list[i])) : count += 1 TestAcc = count/(batchSize*epochs) print("TestAccuracy: ", TestAcc)